Flask 框架中解决 GET 请求报错 "Unsupported Media Type" 的方法
"@app.before_request\n def log_request_body():\n app.logger.info('Record Request Information Start ...')\n if request.args:\n app.logger.info(f'Request Args: {dict(request.args)}')\n if request.method == "POST" or request.method == "PUT":\n if request.json:\n app.logger.info(f'Request Body is {request.json}')\n else:\n app.logger.info('Request Body is empty')\n elif request.method == "GET":\n if "Content-Type" not in request.headers:\n request.headers["Content-Type"] = "application/json"\n app.logger.info('End of recording request information ...')\n"要解决报错"Unsupported Media Type",可以在app.before_request中添加一个条件判断,判断请求方法是否为GET,并且请求头中是否包含"Content-Type"字段,如果不包含则手动添加一个默认的"Content-Type"字段。这样可以避免请求头中缺少"Content-Type"字段而导致的报错。\n\n修改后的代码如下所示:\n\npython\n@app.before_request\ndef log_request_body():\n app.logger.info('Record Request Information Start ...')\n if request.args:\n app.logger.info(f'Request Args: {dict(request.args)}')\n if request.method == \"POST\" or request.method == \"PUT\":\n if request.json:\n app.logger.info(f'Request Body is {request.json}')\n else:\n app.logger.info('Request Body is empty')\n elif request.method == \"GET\":\n if \"Content-Type\" not in request.headers:\n request.headers[\"Content-Type\"] = \"application/json\"\n app.logger.info('End of recording request information ...')\n\n\n这样修改后,即使GET请求不传入json,也不会报错"Unsupported Media Type"了。
原文地址: https://www.cveoy.top/t/topic/pWGZ 著作权归作者所有。请勿转载和采集!