def validate_auth_code(): """ POST Auth code validation --- responses: 200: description: Returns result of code verification """ sess_token = request.cookies.get('sess_token') if not sess_token or sess_token is None: return redirect(url_for('api.v1.post_email_auth'), code=302) content = request.get_json() auth_code = content.get('code') if not auth_code or auth_code is None: return jsonify({"result": {"message": "no code provided"}}), 400 if auth_code != redis_client.get(f'authcode_{sess_token}'): return jsonify({"result": {"message": "wrong code"}}), 400 resp = make_response(jsonify({"result": {"message": "ok"}}), 200) user_id = redis_client.get(f'sess_token_{sess_token}') ttl = 60 * 60 * 24 * 31 # 31 days sess_id = SessToken() redis_client.set(name=f'sessid_{sess_id.value}', value=user_id, ex=ttl) redis_client.delete(f'authcode_{sess_token}') redis_client.delete(f'sess_token_{sess_token}') session['sessid'] = sess_id.value return resp
def add(task_dict): """ task_dict: { 'owner_token' : str(64) -> person.token, 'due': datetime.datetime, 'title': str(), 'body': str(), 'important': bool(), 'done': bool() } """ p = Person.get(task_dict['owner_token']) if not p: raise Exception('Owner does not exist!') try: t = Task( owner_id= p.id, due= task_dict['due'], title= task_dict['title'], body= task_dict['body'], important= task_dict['important'], done= task_dict['done'], token=token_urlsafe(32) ) except: raise Exception('Problem in request dict') redis_client.delete(Person.get_id(t.owner_id).token + '-tasks') db.session.add(t) db.session.commit() redis_client.set(t.token, json.dumps(t.to_dict()), ex=1800) return t
def profile_image_upload_to_S3(image_name, destination_dir): """ Upload the image to Amazon S3. """ # Full path where the image is stored temporary temp_image_path = Path( f"{current_app.root_path}/base/static/{temp_image_dir}") jpeg_extensions = [".jpg", ".jpeg"] _, file_ext = os.path.splitext(image_name) try: s3.upload_fileobj( open(f"{temp_image_path}/{image_name}", "rb"), aws_bucket_name, f"{destination_dir}{image_name}", ExtraArgs={ "ACL": "public-read", "ContentType": "image/jpeg" if file_ext in jpeg_extensions else "image/png", }, ) os.remove(f"{temp_image_path}/{image_name}" ) # Clean up by deleting the image in the temporary folder redis_client.delete( image_name) # Clean up by deleting the image in redis return "file uploaded" except Exception as err: print(err)
def toggle_done(_token): t = Task.query.filter_by(token=_token).first() if not t: raise Exception('Task does not exist!') else: t.done = not t.done db.session.commit() redis_client.delete(Person.get_id(t.owner_id).token + '-tasks') redis_client.delete(t.token) redis_client.set(t.token, json.dumps(t.to_dict), ex=1800) return t.to_dict()
def post(self): # 1.获取参数 -- post请求体以json格式传递参数 # 1.1 mobile 手机号码 # 1.2 code 用户填写的短信验证码 # 2.参数校验--RequestParser参数提取和参数校验 # 构建解析对象 parser = RequestParser() parser.add_argument("mobile", required=True, location="json", type=regex(r'^1[3-9]\d{9}$')) parser.add_argument("code", required=True, location="json", type=regex(r'\d{6}')) param_ret = parser.parse_args() mobile = param_ret['mobile'] sms_code = param_ret['sms_code'] # 3业务逻辑处理 key = "app:code:{}".format(mobile) real_smscode = redis_client.get(key) redis_client.delete(key) if real_smscode is None: return {"message": "短信验证码为空"} if sms_code != real_smscode: return {"message": "短信验证码错误"} # 3.3 短信验证码通过 # 3.4 根据手机号码作为查询条件,查询用户对象是否存在 # select * from xxxx where xx # 优化查询:options(load_only(User.id)) user = User.query.options(load_only( User.id)).filter(User.mobile == mobile).first() if user is None: user = User(mobile=mobile, name=mobile, last_login=datetime.now()) db.session.add(user) else: user.last_login = datetime.now() try: db.session.commit() except Exception as e: db.session.rollback() return {"message": f"数据库提交异常{e}"}, 507 # 3.8 生成2小时有效的登录token和14天有效的刷新token login_token, refresh_token = self.get_token(user_id=user.id) # 4返回值处理 return {"login_token": login_token, "refresh_token": refresh_token}
def delete(note_id): note = Note.query.get(note_id) if isinstance(note, NoneType) or current_user.id != note.id_user: flash('This note does not exists !', 'warning') else: # remove note from posgres db.session.delete(note) db.session.commit() # remove note from redis redis_client.lrem('notes_id', 0, str(note.id)) redis_client.delete(str(note.id)) flash('Your note has been deleted !', 'success') return redirect(url_for('index'))
def delete(_token): t_redis = redis_client.get(_token) if t_redis: t = Task.from_dict(json.loads(t_redis)) else: t = Task.query.filter_by(token=_token).first() if not t: raise Exception('Task does not exist!') else: redis_client.delete(_token) redis_client.delete(Person.get_id(t.owner_id).token + '-tasks') db.session.delete(Task.get(t.token)) db.session.commit() return 'Task deleted'
def post(self): # 获取参数 parser = RequestParser() parser.add_argument('mobile', required=True, location='json', type=mobile_type) parser.add_argument('code', required=True, location='json', type=regex(r'^\d{6}$')) args = parser.parse_args() mobile = args.mobile code = args.code # 校验短信验证码 key = 'app:code:{}'.format(mobile) real_code = redis_client.get(key) if not real_code or code != real_code.decode(): return {'message': 'Invalid Code', 'data': None}, 400 # 删除验证码 redis_client.delete(key) # 校验成功,查询数据库 user = User.query.options(load_only( User.id)).filter(User.mobile == mobile).first() if user: # 如果用户存在则更新登录时间 user.last_login = datetime.now() else: # 如果用户不存在,则创建用户 user = User(mobile=mobile, name=mobile, last_login=datetime.now()) db.session.add(user) db.session.commit() # token = generate_jwt({'userid': user.id}, # expiry=datetime.utcnow() + timedelta(days=current_app.config['JWT_EXPIRE_DAYS'])) token = generate_jwt({ 'userid': user.id, 'exp': datetime.utcnow() + timedelta(days=current_app.config['JWT_EXPIRE_DAYS']) }) return {'token': token}, 200
def cache_qrcode_code(card_id, card_code): val = '%s-%s' % (card_id, card_code) old_code = redis_client.get(val) old_code and redis_client.delete(old_code) code = random_digit(20) redis_client.set(code, val, 70) # 每分钟刷新 redis_client.set(val, code, 70) # 每分钟刷新 return code
def profile_image_process(image_name, photo_type=None): """ Resize the image file using the PIL image library and save it to the app server or Amazon S3 depending on the configuration. """ temp_image_path = Path( f"{current_app.root_path}/base/static/{temp_image_dir}") img_data = redis_client.get( image_name) # get image from redis using image_name as the key decoded_img = Image.open(io.BytesIO(img_data)) decoded_img.thumbnail((800, 800)) decoded_img.save(f"{temp_image_path}/{image_name}" ) # save the resized image to the temporary folder if image_server_config == "app_server_storage": profile_image_upload_path = Path( f"{current_app.root_path}/base/static/{profile_image_upload_dir}") cover_image_upload_path = Path( f"{current_app.root_path}/base/static/{cover_image_upload_dir}") if photo_type == "profile": shutil.copyfile( f"{temp_image_path}/{image_name}", f"{profile_image_upload_path}/{image_name}", ) else: shutil.copyfile( f"{temp_image_path}/{image_name}", f"{cover_image_upload_path}/{image_name}", ) os.remove(f"{temp_image_path}/{image_name}" ) # Clean up by deleting the image in the temporary folder redis_client.delete( image_name) # Clean up by deleting the image in redis elif image_server_config == "amazon_s3": # Upload the image to Amazon S3 if the configuration is set to "amazon_s3" profile_image_upload_to_S3.delay( image_name, profile_image_upload_dir ) if photo_type == "profile" else profile_image_upload_to_S3.delay( image_name, cover_image_upload_dir)
def delete_from_temporary_storage(self, verification_code): redis_client.delete(verification_code)
def refresh_task(): page = request.args.get('page') rows = request.args.get('pagerows') user = request.args.get('nickname') redis_client.delete('task_list_%s_%s_%s' % (user, page, rows)) return json.dumps("删除成功")
def tearDown(self): redis_client.delete(self.key)