要解决"Unsupported Media Type"错误,可以在请求时添加一个条件判断,如果请求的Content-Type不是application/json,则不记录请求体。可以使用request.headers.get方法来获取请求头中的Content-Type字段,并进行判断。\n\n修改register_request_handlers函数如下:\n\npython\ndef register_request_handlers(app: Flask):\n @app.before_request\n def log_request_body():\n app.logger.info('Record Request Information Start ...')\n \n # Log request arguments if present\n if request.args:\n app.logger.info(f'Request Args is {dict(request.args)}')\n\n # Log request body if Content-Type is application/json\n content_type = request.headers.get('Content-Type')\n if content_type and content_type.startswith('application/json'):\n app.logger.info(f'Request Body is {request.json}')\n\n app.logger.info('End of recording request information ...')\n\n\n这样修改后,只有当请求的Content-Type为application/json时,才会记录请求体。如果没有参数或Content-Type不是application/json,则不会记录请求体,避免了"Unsupported Media Type"错误。

Flask 中使用 before_request 记录请求信息并解决

原文地址: https://www.cveoy.top/t/topic/pVTl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录