Flask搭建OpenAI待办事项生成器测试时遇415错误求助
问题原因与解决方案
415错误的根源
浏览器直接访问localhost:5000/chatbot发起的是GET请求,而你的代码直接尝试读取request.json['message']——GET请求没有请求体,也不会携带Content-Type: application/json请求头,Flask无法解析出JSON数据,因此返回415(不支持的媒体类型)错误。而curl发送的是符合要求的POST请求,携带了正确的请求头和JSON数据,所以能正常返回200。
修复方案
修改路由函数,区分GET和POST请求的处理逻辑:
- GET请求:返回接口使用说明,避免报错
- POST请求:保留原有的JSON数据处理逻辑
修改后的代码
import openai from flask import Flask, request, jsonify, render_template_string app = Flask(__name__) openai.api_key = 'api_code' def generate_response(prompt): response = openai.completions.create( model="gpt-3.5-turbo-instruct", prompt=prompt, max_tokens=150 ) return response.choices[0].text.strip() @app.route('/chatbot', methods=['GET', 'POST']) def chatbot(): if request.method == 'GET': # 返回简单的使用说明页面 return render_template_string(''' <h1>待办事项生成器</h1> <p>请使用POST请求发送JSON数据,格式要求:</p> <pre>{"message": "你的任务描述内容"}</pre> <p>示例curl命令:</p> <pre>curl -X POST http://127.0.0.1:5000/chatbot -H "Content-Type: application/json" -d '{"message": "Buy groceries, clean the house, sleep for 8 hours"}'</pre> ''') elif request.method == 'POST': try: # 先校验请求格式 if not request.is_json: return jsonify({'error': '请发送JSON格式的数据'}), 400 user_input = request.json.get('message') if not user_input: return jsonify({'error': '请求缺少message字段'}), 400 print(f"Received message: {user_input}") prompt = f"Create a to-do list based on the following tasks: {user_input}" response_text = generate_response(prompt) return jsonify({'response': response_text}) except Exception as e: print(f"Error: {e}") return jsonify({'error': 'Internal Server Error'}), 500 if __name__ == '__main__': app.run(port=5000, debug=True)
测试说明
- 浏览器访问
localhost:5000/chatbot(GET请求):会显示接口使用说明,不再返回415错误 - 使用原curl命令发送POST请求:依然能正常生成待办事项列表
内容的提问来源于stack exchange,提问作者Jason Pitt
相关产品推荐
相关产品推荐

