async def decode_token(cls, request: Request, token: str): """check token""" try: secret = AuthenticConfig.ADMIN_SECRETS payload = jwt.decode(token, secret, algorithms='HS256', options={'verify_exp': True}) if isinstance(payload, dict) and isinstance( payload.get('data'), dict): data: dict = payload.get('data') extend_model = data.get('extend_model') user, extend_user = await cls.query_user(**data) await cls._check_redis(token, user, extend_model, extend_user.id) # set/save user, extend_user on request.state request.state.user = user request.state.extend_user = extend_user return payload except jwt.PyJWTError: raise Unauthorized(message='login expired,please login retry!') except OperationalError: logger.error(traceback.format_exc()) raise Unauthorized( message='database connect exception,please request retry')
async def all_exception_handler(request: Request, exc: Exception): logger.error(f"程序异常\n{request.method} | URL:{request.url}\n \ Headers:{request.headers}\n{traceback.format_exc()}") return ORJSONResponse( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content="服务器内部错误", )
def delete_novel(): name = request.values.get('book_name') book = Book.query.filter_by(name=name).first() try: db.session.delete(book) db.session.commit() except sqlalchemy.orm.exc.UnmappedInstanceError as e: logger.error(e) return "移除失败" return redirect(url_for('novel.novel_cases'))
async def validation_exception_handler(request: Request, exc: RequestValidationError): """ 捕获请求参数 验证错误 :param request: :param exc: :return: """ logger.error(f"参数错误\nURL:{request.url}\nHeaders:{request.headers}\n{traceback.format_exc()}") return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content=jsonable_encoder({"code": 400, "data": {"tip": exc.errors()}, "body": exc.body, "message": "fail"}), )
async def query_params_exception_handler(request: Request, exc: PostParamsError): """ 捕获自定义抛出异常 :param request: :param exc: :return: """ logger.error(f"参数查询异常\nURL:{request.url}\nHeaders:{request.headers}\n{traceback.format_exc()}") return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content={"code": 400, "data": {"tip": exc.err_desc}, "message": "fail"}, )
async def token_exception_handler(request: Request, exc: TokenAuthError): logger.error( f"参数查询异常\nURL:{request.url}\nHeaders:{request.headers}\n{traceback.format_exc()}" ) return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content={ "code": 400, "data": None, "message": exc.err_desc }, )
def download_page(url, **kwargs): """ download html page """ while True: try: if kwargs and kwargs['params']: r = requests.get(url, headers=headers, params=kwargs["params"], timeout=1.5) else: r = requests.get(url, headers=headers, timeout=1.5) except requests.exceptions.ConnectionError as e: logger.error(e) else: return r.text
async def all_exception_handler(request: Request, exc: Exception): logger.error( f"全局异常\nURL:{request.url}\nHeaders:{request.headers}\n{traceback.format_exc()}" ) return JSONResponse( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content={ "code": 500, "data": { "tip": "服务器错误" }, "message": "fail" }, )
async def log_request_detail(request: Request): logger.info('start request'.center(60, '*')) logger.info(f'{request.method} {request.url}') methods = ['POST', 'PUT', 'PATCH'] content_type = request.headers.get('content-type', '') if request.method in methods and 'application/json' in content_type: try: payload = await request.json() if payload: logger.info(payload) except JSONDecodeError: logger.error('encounter JSONDecodeError') except UnicodeDecodeError: logger.error('encounter UnicodeDecodeError') logger.info('end request'.center(60, '*')) return await original_route_handler(request)
async def on_message(message): # Parsing and forwarding the command, if message starts with bot prefix. if message.content.startswith(Config.COMMAND_PREFIX): command = message.content.split()[0][1:] arguments = [] try: arguments = message.content.split()[1:] except IndexError: pass try: await getattr(commands, command)(message, arguments) except Exception as e: logger.error(e) print(e) # Checking user, and adding to database if not exists. user = get_user(discord_id=message.author.id).first() if not user: user = create_user(discord_id=message.author.id) # Properly rewarding user for contribution. if not message.content.startswith(Config.COMMAND_PREFIX): message_length = len(message.content) add_currency_to_user(user.id, Config.CURRENCY_CODE, int(message_length / 5)) # Checking currency conversion data request time. last_update = get_system_variable("currency_last_update") if not last_update: last_update = create_system_variable("currency_last_update", get_current_date()) if (get_current_date() - datetime.strptime(last_update.value, "%Y-%m-%d %H:%M:%S.%f")) >= timedelta(hours=1): update_currencies() last_update.value = get_current_date() session.commit()
def register(): if request.method == 'POST': user = User() if not register_filter( request.form.get('username'), request.form.get('email'), request.form.get('password1'), request.form.get('password2')): abort(403) try: user.username = request.form.get('username') user.email = request.form.get('email') user.password = request.form.get('password1') user.publish_date = datetime.datetime.now() user.modified_date = datetime.datetime.now() db.session.add(user) db.session.commit() except sqlalchemy.exc.IntegrityError: logger.error("注册失败-> 密码或用户名已被他人所占用") return '密码或用户名已被他人所占用', 400 else: login_user(user) logger.info('用户 "{}" 注册成功'.format(user.username)) return redirect(url_for('main.index')) return render_template('blog/register.html')
async def all_exception_handler(request: Request, exc: HTTPException): logger.error( f"全局异常\n{request.method} | URL:{request.url}\nHeaders:{request.headers}\n{traceback.format_exc()}" ) return response_code.resp_500()