def test_defaults(self): """ Do not provide fields that can be defaulted and test their values """ user = User(email='*****@*****.**', password='******') user.save() self.assertNotEqual(None, user) self.assertIsInstance(user, User)
def test_invalid_age(self): """ The size field was not provided """ user = User(first_name='test', last_name='user', phone='+919999999999', facebook_id='fb001', email='*****@*****.**', age='20') user.save() print(user)
def test_fb_id_too_long(self): """ The fb_id field was too long """ msg = 'value too long for type character varying(100)' with self.assertRaisesMessage(DataError, msg): user = User(first_name='test', last_name='user', phone='+919999999999', facebook_id='f' * 101, email='*****@*****.**', age=20) user.save() self.fail("'test_fb_id_too_long' did not get the expected error")
def test_email_too_long(self): """ The archive_location field was too long """ msg = 'value too long for type character varying(254)' with self.assertRaisesMessage(DataError, msg): user = User(first_name='test', last_name='user', phone='+919999999999', facebook_id='fb001', email='*****@*****.**' * 256, age=20) user.save() self.fail( "'test_archive_location_too_long' did not get the expected error" )
def verify_token(token): '''用于检查用户请求是否有token,并且token真实存在,还在有效期内''' g.current_user = User.verify_jwt(token) if token else None if g.current_user: # 每次认证通过后(即将访问资源API),更新 last_seen 时间 g.current_user.update_token() db.session.commit() return g.current_user is not None
def test_valid_data(self): """ User with valid data """ user = User(first_name='test', last_name='user', phone='+919999999999', facebook_id='fb001', email='*****@*****.**', age=20) user.save() self.assertNotEqual(None, user) self.assertIsInstance(user, User) self.assertEqual('test', user.first_name) self.assertEqual('user', user.last_name) self.assertEqual('+919999999999', user.phone) self.assertEqual('fb001', user.facebook_id) self.assertEqual('*****@*****.**', user.email) self.assertEqual(20, user.age)
def __call__(self, request: WSGIRequest): # 放行的URL if self._except_path(request) is True: return self.get_response(request) # token 验证 token = self._token(request) passport = Passport() if token is not None and passport.check(token) is True: # 绑定 user request.user = User(**passport.user(token)['data']) return self.get_response(request) else: return HttpResponseRedirect(reverse('community.login'), {'app_key': PASSPORT['key']})
def register(): if current_user.is_authenticated: return redirect(url_for('Home')) form = RegistrationForm() if form.validate_on_submit(): encrypted_password = bcrypt.generate_password_hash( form.password.data).decode( 'UTF-8') #hashing passwords before storing in db user = User(username=form.username.data, email=form.email.data, password=encrypted_password) db.session.add(user) db.session.commit() flash('Your account has been created, Please try to log in', 'success') return redirect(url_for('login')) return render_template('register.html', title='register', form=form)
def test_updated_at(self): """ Check is updated_at changes after updating a object """ user = User(first_name='test', last_name='user', phone='+919999999999', facebook_id='fb001', email='*****@*****.**', age='20') user.save() updated1 = user.updated_at user.first_name = 'Sumeet' user.save(update_fields=['first_name']) updated2 = user.updated_at result = updated2 > updated1 self.assertTrue(result, True)
def register(): """注册接口 请求的参数: 手机号, 短信验证码, 密码, 确认密码 """ # 获取请求的json, 返回字典 req_dict = request.get_json() mobile = req_dict.get("mobile") sms_code = str(req_dict.get("sms_code")) password = req_dict.get("password") password2 = req_dict.get("password2") # 校验参数 if not all([mobile, sms_code, password, password2]): return jsonify(errno=RET.PARAMERR, errmsg="参数不完整") # 校验手机号 if not re.match(r"1[34578]\d{9}", mobile): return jsonify(errno=RET.PARAMERR, errmsg="手机号格式错误") if password != password2: return jsonify(errno=RET.PARAMERR, errmsg="两次密码验证不正确") # 从redis取出短信验证码 try: real_sms_code = redis_store.get("sms_code_%s" % mobile) except Exception as e: current_app.logger.error(e) return jsonify(errno=RET.DBERR, errmsg="读取真实短信验证码异常") # 检查短信验证码是否过期 if real_sms_code is None: return jsonify(errno=RET.DATAERR, errmsg="短信验证码已过期") # 删除短信验证码信息,防止用户重复校正 try: redis_store.delete("sms_code_%s" % mobile) except Exception as e: current_app.logger.error(e) # 判断用户填写的短信验证码是否正确 print("real:%s , send: %s" % (real_sms_code, sms_code.encode('UTF-8'))) real_sms_code_str = real_sms_code.decode("UTF-8") if real_sms_code_str != sms_code: return jsonify(errno=RET.DATAERR, errmsg="短信验证码错误") # 保存用户的数据到数据库 user = User(phone=mobile, nick_name="笨笨猪" + str(random.randint(1, 99999))) # 在这里设置password,password在数据库模型用已经定义好,包括加密处理,这里的password是一个类属性,可以set,也可以get user.password = password try: db.session.add(user) db.session.commit() # 这里跑出一个数据库异常 except IntegrityError as e: # 数据库操作错误后的回滚 db.session.rollback() # 表示手机号重复 current_app.logger.error(e) return jsonify(errno=RET.DATAEXIST, errmsg="手机号已存在") except Exception as e: current_app.logger.error(e) return jsonify(errno=RET.DBERR, errmsg="查询数据库异常") # 保存登录状态到session session["name"] = mobile session["mobile"] = mobile session["user_id"] = user.id # 返回结果 return jsonify(errno=RET.OK, errmsg="注册成功")