def register(request): """ 注册处理事件 :param request:注册请求 :return: ①result: '0'表示成功, '1'表示用户名重名, '2'表示未知错误,可能昵称/邮箱/密码为空,可能传输出错 ② """ # 回复 response = HttpResponse() response['Content-Type'] = 'application/json' if request.method == 'POST': # 获取客户端信息 nickname = request.POST.get('userName', '') password = request.POST.get('userCode', '') avatar = request.POST.get('avatar', '') if nickname and password: try: user = User.objects.get(nickname=nickname) result = '1' except ObjectDoesNotExist: user = User(nickname=nickname, mail='nomail', password=password, create_time=time.time(), action_time=time.time()) user.save() result = '0' else: result = '2' else: result = '-1' response.write(result) response.write(fetch_recommend()) # 返回首页信息 return response
def add_player(username, first_name, last_name, team): if username: try: user = User.objects.get(username=username) except User.DoesNotExist: user = User(username=username) user.first_name = first_name user.last_name = last_name user.save() team.members.add(user)
def setUp(self): ###### create Users ####### users = ['UserA', 'UserB', 'UserC', 'UserD'] for i in range(4): newUser = AUser(password='', last_login=timezone.now(), is_superuser=True, username=users[i], first_name='Firstname', last_name='Lastname', email='*****@*****.**', is_staff=True, is_active=True, date_joined=timezone.now()) newUser.save() testDBModel.testUsers.append(newUser) testDBModel.testUsersID.append(newUser.pk) ###### add Category ###### category1 = Category(name="hats") testDBModel.testCategory.append(category1) category1.save() category2 = Category(name="glasses") testDBModel.testCategory.append(category2) category2.save() user = User(id=testDBModel.testUsersID[0],user_id=testDBModel.testUsersID[0], user_image="profile1.jpg") user.save() ###### add product ###### addProducts = ["ProductA", "ProductB", "ProductC", "ProductD"] for i in range(4): # # add products newOne = Product(category=category1, name=addProducts[i], brand='brand', url='url', photo='photo', price=1.0, description='') newOne.save() testDBModel.testProducts.append(newOne) ###### add custom product ##### newAdded = Added(owner = testDBModel.testUsers[0], product = testDBModel.testProducts[0]) newAdded.save() newAdded = Added(owner = testDBModel.testUsers[1], product = testDBModel.testProducts[1]) newAdded.save() ###### add temp product ###### tempP = TempProduct(owner = testDBModel.testUsers[0], overlay = 'overlay1ol.jpg', token = '1', category = testDBModel.testCategory[0]) tempP.save() tempP = TempProduct(owner = testDBModel.testUsers[1], overlay = 'overlay2ol.jpg', token = '2', category = testDBModel.testCategory[0]) tempP.save() testDBModel.testOverlay = ['overlay1ol.jpg', 'overlay2ol.jpg'] ##### ## add comments ###### for i in range(4): newOne = Comment(product=testDBModel.testProducts[i], owner=testDBModel.testUsers[i], content="null", time = timezone.now()) newOne.save() testDBModel.testComments.append(newOne) # add to wishlist first for i in range(4): newOne = WishList(product=testDBModel.testProducts[i], owner=testDBModel.testUsers[i]) newOne.save() # add to FitList: for i in range(4): newOne = FitList(product = testDBModel.testProducts[i], owner = testDBModel.testUsers[i]) newOne.save()
def signup(request): if request.POST.has_key('login'): new_user = User() new_user.setName(request.POST['login']) feed = Feed() feed.parent = new_user new_user.save() feed.save() response = HttpResponseRedirect(reverse('main:index')) response.set_cookie('login',request.POST['login']) return response
def test_isfollowing(self): u = User(username = '******', password = "******", email = '*****@*****.**', type=0) u1 = User(username = '******', password = "******", email = '*****@*****.**', type=0) db.session.add(u) db.session.add(u1) db.session.commit() user = u.follow(u1) if user: db.session.commit() following = u.is_following(u1) assert True == following
def test_follow_user(self): u = User(username = '******', password = "******", email = '*****@*****.**', type=0) u1 = User(username = '******', password = "******", email = '*****@*****.**', type=0) db.session.add(u) db.session.add(u1) db.session.commit() user = u.follow(u1) if user: db.session.commit() followers=[] followers.append(u1) assert followers == u.followed.all()
def test_make_unique_nickname(self): u = User(nickname='john', email='*****@*****.**') db.session.add(u) db.session.commit() nickname = User.make_unique_nickname('john') assert nickname != 'john' u = User(nickname=nickname, email='*****@*****.**') db.session.add(u) db.session.commit() nickname2 = User.make_unique_nickname('john') assert nickname2 != 'john' assert nickname2 != nickname
def addComment(postid, host): if session.get('username') != host: return render_template('notlogin.html') else: # 查询登录用户的ID sql = 'SELECT * FROM users WHERE user_name = %s;' parm = (host, ) rows = User().get_User(sql, parm) hostid = rows[0] hostname = rows[1] if request.form['commbox'] == '': error = 'You left nothing!' # 发送内容如果为空,提示并返回主页 sql = 'SELECT * FROM comment WHERE message_id = %s ORDER BY comment_id DESC;' parm = (postid, ) comms = Comment().get_AllComment(sql, parm) # 显示post sql1 = 'SELECT * FROM message WHERE message_id = %s;' parm1 = (postid, ) rows = Post().get_Post(sql1, parm1) post = rows[1] # 获取posthost和posttime posthostid = rows[6] sql2 = 'SELECT * FROM users WHERE user_id = %s;' parm2 = (posthostid, ) row = User().get_User(sql2, parm2) posthost = row[1] posttime = rows[2] return render_template('comments.html', postid=postid, posttime=posttime, posthost=posthost, host=host, error=error, post=post, comms=comms) else: # 添加评论 sql_add = 'INSERT INTO comment (comment_info,comment_time,message_id,user_id,comm_commnum,comm_likenum,user_name) VALUES (%s,%s,%s,%s,0,0,%s);' # 获取当前时间 import datetime now = datetime.datetime.now() # 转换为指定的格式 otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S") parm_add = (request.form['commbox'], otherStyleTime, postid, hostid, hostname) Comment().set_Comment(sql_add, parm_add) return redirect(url_for('comment', postid=postid, host=host))
def test_unfollow_user(self): u = User(username = '******', password = "******", email = '*****@*****.**', type=0) u1 = User(username = '******', password = "******", email = '*****@*****.**', type=0) db.session.add(u) db.session.add(u1) db.session.commit() user = u.follow(u1) if user: db.session.commit() user = u.unfollow(u1) if user: db.session.commit() followers = [] assert followers == u.followed.all()
def init_facebook(self): """Sets up the request specific Facebook and User instance""" facebook = Facebook() user = None # initial facebook request comes in as a POST with a signed_request if u'signed_request' in self.request.POST: facebook.load_signed_request(self.request.get('signed_request')) # we reset the method to GET because a request from facebook with a # signed_request uses POST for security reasons, despite it # actually being a GET. in webapp causes loss of request.POST data. self.request.method = u'GET' self.set_cookie( 'u', facebook.user_cookie, datetime.timedelta(minutes=1440)) elif 'u' in self.request.cookies: facebook.load_signed_request(self.request.cookies.get('u')) # try to load or create a user object if facebook.user_id: user = User.get_by_key_name(facebook.user_id) if user: # update stored access_token if facebook.access_token and \ facebook.access_token != user.access_token: user.access_token = facebook.access_token user.put() # refresh data if we failed in doing so after a realtime ping if user.dirty: user.refresh_data() # restore stored access_token if necessary if not facebook.access_token: facebook.access_token = user.access_token if not user and facebook.access_token: me = facebook.api(u'/me', {u'fields': _USER_FIELDS}) try: friends = [user[u'id'] for user in me[u'friends'][u'data']] user = User(key_name=facebook.user_id, user_id=facebook.user_id, friends=friends, access_token=facebook.access_token, name=me[u'name'], email=me.get(u'email'), picture=me[u'picture'], location='-13.752725,-54.667969') user.put() except KeyError: pass # ignore if can't get the minimum fields self.facebook = facebook self.user = user
def user_signup(request): context = { } if request.is_ajax(): response_data = {} data = json.loads(request.body.decode('utf-8')) postEmail = data.get('email') postUsername = data.get('username') postPassword = data.get('password') user = User(email=postEmail, username=postUsername) user.set_password(postPassword) try: user.save() except IntegrityError as e: response_data['status'] = False response_data['msg'] = 'Sorry! This email is already signed up.' return HttpResponse(json.dumps(response_data), content_type="application/json" ) response_data['status'] = True response_data['msg'] = 'Success!' return HttpResponse( json.dumps(response_data), content_type="application/json" ) else: if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() else: form = UserCreationForm() context.update({'form': form}) return render(request, 'main/pages/signup.html', context)
def createUser(request): #this is how we get queryArgs fn = request.GET['fn'] ln = request.GET['ln'] age = request.GET['age'] sex = request.GET['sex'] email = request.GET['e'] password = request.GET['p'] # TODO - check to make sure email/username isn't taken before creating u = User(createdAt=timezone.now(), inPool=False, signedIn=True, hasReviewed=True, firstName=fn, lastName=ln, age=age, sex=sex, email=email, password=password, totalMatches=0, missedMatches=0) u.save() response = JsonResponse({'possibly': 'created user'}) return response
def test_posts_by_user(self): u = User(username = '******', password = "******", email = '*****@*****.**', type=0) db.session.add(u) db.session.commit() categ = Category("sports") db.session.add(categ) db.session.commit() list_categ=[] list_categ.append(categ) tag = Tags("sports",1) list_tag=[] db.session.add(tag) db.session.commit() list_tag.append(tag) post = Post("title", "excerpt", "description", "image", u.id, list_categ, list_tag) db.session.add(post) db.session.commit() list_posts = u.posts_by_user() expected =1 assert expected == len(list_posts.all())
def register(request): result = {} if request.method == "POST": user = User.objects.filter(UserName=request.POST["username"]) if len(user) != 0: result["success"] = False result["error"] = -1003 else: new_user = User( UserName=request.POST["username"], Password=request.POST["password"], Contract=ContractSize.objects.get(pk=request.POST["contract"]) ) new_user.save() request.session["user"] = new_user.pk result["success"] = True result["info"] = 1002 else: result["success"] = False result["error"] = -1 return JsonResponse(result)
def login_view(request): if 'appSignature' not in request.POST: return JSONResponse({'status': 400, 'message': 'No application signature found'}) if 'phone_number' not in request.POST or 'pin' not in request.POST: return JSONResponse({'status': 400, 'message': 'You need to supply both phone number and pin'}) if request.POST['appSignature'] != constants.APP_SIGNATURE: return JSONResponse({'status': 400, 'message': 'Application Signatures did not match'}) try: phone_number = request.POST['phone_number'] pin = request.POST['pin'] if not User.objects.filter(phone_number=phone_number).exists(): user = User(phone_number=phone_number, pin=pin) user.save() return JSONResponse({'status': 200, 'message': 'User logged in successfully'}) except Exception as e: _log.error('Exception while logging in: %s' % str(e)) return JSONResponse({'status': 401, 'message': str(e)})
def validate(self): if not Form.validate(self): return False if self.nickname.data == self.original_nickname: return True if self.nickname.data != User.make_valid_nickname(self.nickname.data): self.nickname.errors.append(gettest('This nickname has invalid characters. Please choose letters, numbers, dots and underscores only.')) return False user = User.query.filter_by(nickname=self.nickname.data).first() if user != None: self.nickname.errors.append(gettext('This nickname is already in use. Please choose another one.')) return False return True
def get(self, request): #nickname = 'm.lefay' nickname = request.GET.get('nickname') #token = '2377482807.24242fb.55f6b006ec0f43d3a45db141259e2e3a' token = request.GET.get('token') if not nickname or not token: return JsonResponse({'nickname':None,'token':None}) try: u = User.objects.get(nick=nickname) except: u = None if u: # get pic from db r = [] img = u.pic_set.all() if img: for i in img: r.append(i.location) return JsonResponse({'nickname':nickname,'token':token, 'path':r}) #else download and store api = InstAPI(access_token=token) r = api.get_user_popular_media(nickname) u = User(nick=nickname) u.save() epath = os.path.join(settings.BASE_DIR, 'insta', 'pics', nickname) os.mkdir(epath) if r: for link in r: req = requests.get(link, stream=True) ipath = os.path.join(epath, link.split('/')[-1:][0]) if req.status_code == 200: with open(ipath, 'wb') as f: for chunk in req.iter_content(1024): f.write(chunk) p = Pic(owner=u, url=link, location=ipath) p.save() return JsonResponse({'nickname':nickname,'token':token, 'urls':r})
def test_follow(self): u1 = User(nickname='john', email='*****@*****.**') u2 = User(nickname='susan', email='*****@*****.**') db.session.add(u1) db.session.add(u2) db.session.commit() assert u1.unfollow(u2) is None u = u1.follow(u2) db.session.add(u) db.session.commit() assert u1.follow(u2) is None assert u1.is_following(u2) assert u1.followed.count() == 1 assert u1.followed.first().nickname == 'susan' assert u2.followers.count() == 1 assert u2.followers.first().nickname == 'john' u = u1.unfollow(u2) assert u is not None db.session.add(u) db.session.commit() assert not u1.is_following(u2) assert u1.followed.count() == 0 assert u2.followers.count() == 0
def add_quantity(request): # First retrieve all the required arguments try: quantity_name = request.POST['name'] except: return HttpResponse("name is missing") else: try: definition = QuantityDefinition.objects.get(name=quantity_name) except ObjectDoesNotExist: definition = QuantityDefinition(name=quantity_name) definition.save() try: object_name = request.POST['object'] except: return HttpResponse("object is missing") else: try: object = Object.objects.get(name=object_name) except ObjectDoesNotExist: object = Object(name=object_name) object.save() try: value = float(request.POST['value']) except KeyError: return HttpResponse("value is missing") except ValueError: return HttpResponse("value should be a float") try: unit = request.POST['unit'] except: return HttpResponse("unit is missing") try: user_name = request.POST['user'] except: return HttpResponse("user is missing") else: try: user = User.objects.get(name=user_name) except ObjectDoesNotExist: user = User(name=user_name) user.save() # Instantiate the quantity q = Quantity(definition=definition, object=object, value=value, unit=unit, user=user, date_entered=datetime.now() ) # Now optionally set the remaining properties if 'uncertainty' in request.POST: q.uncertainty = float(request.POST['uncertainty']) if 'origin' in request.POST: q.origin = request.POST['origin'] # Save quantity to database q.save() return HttpResponse("success")
def test_follow_posts(self): u1 = User(nickname='john', email='*****@*****.**') u2 = User(nickname='susan', email='*****@*****.**') u3 = User(nickname='mary', email='*****@*****.**') u4 = User(nickname='david', email='*****@*****.**') db.session.add(u1) db.session.add(u2) db.session.add(u3) db.session.add(u4) #make 4 posts utcnow = datetime.utcnow() p1 = Post(body="post from john", author=u1, timestamp=utcnow+timedelta(seconds=1)) p2 = Post(body="post from susan", author = u2, timestamp=utcnow+timedelta(seconds=2)) p3 = Post(body="post from mary", author = u3, timestamp=utcnow+timedelta(seconds=3)) p4 = Post(body="post from david", author = u4, timestamp=utcnow+timedelta(seconds=4)) db.session.add(p1) db.session.add(p2) db.session.add(p3) db.session.add(p4) db.session.commit() #setup followers u1.follow(u1) #john follows himself u1.follow(u2) #john follows susan u1.follow(u4) #john follows david u2.follow(u2) #john follows herself u2.follow(u3) #john follows mary u3.follow(u3) #john follows herself u3.follow(u4) #john follows david u4.follow(u4) #john follows himself db.session.add(p1) db.session.add(p2) db.session.add(p3) db.session.add(p4) db.session.commit() #check followed post of each user f1 = u1.followed_posts().all() f2 = u2.followed_posts().all() f3 = u3.followed_posts().all() f4 = u4.followed_posts().all() assert len(f1) == 3 assert len(f2) == 2 assert len(f3) == 2 assert len(f4) == 1 assert f1 == [p4, p2, p1] assert f2 == [p3, p2] assert f3 == [p4, p3] assert f4 == [p4]
def test_avatar(self): u = User(nickname='john', email='*****@*****.**') avatar = u.avatar(128) expected = 'http://www.gravatar.com/avatar/d4c74594d841139328695756648b6bd6' assert avatar[0:len(expected)] == expected