You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask /generate端点POST请求出现405 Method Not Allowed错误求助

Flask /generate端点POST请求返回405 Method Not Allowed错误排查求助

向Flask应用的/generate端点发送POST请求时,始终收到405 Method Not Allowed错误,尽管已确认该端点配置为处理POST请求,问题仍持续存在。

Flask应用代码(app.py)

from flask import Flask, request, jsonify, render_template, send_from_directory
from flask_cors import CORS
import openai
import logging
import os
import pdfplumber
import docx

# Set up logging
logging.basicConfig(level=logging.INFO)

# Initialize Flask app
app = Flask(__name__, static_folder='frontend', template_folder='frontend')

# Allow CORS for all routes by default with credentials
CORS(app, resources={r"/*": {"origins": "*", "supports_credentials": True}})

# Load OpenAI API key directly
openai.api_key = 'YOUR_OPENAI_API_KEY'  # Replace 'YOUR_OPENAI_API_KEY' with your actual OpenAI API key

# Set the upload folder
UPLOAD_FOLDER = 'uploads'
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# Serve the index.html file
@app.route('/')
def index():
    return render_template('index.html')

# Serve static files (CSS, JS, etc.)
@app.route('/<path:filename>')
def serve_static(filename):
    return send_from_directory(app.static_folder, filename)

# Generate lesson plan
@app.route('/generate', methods=['POST'])
def generate():
    data = request.json
    lcontent = data.get('lcontent', '')
    grade_level = data.get('grade_level')
    learning_outcomes = data.get('learning_outcomes')
    student_count = data.get('student_count')
    learning_styles = data.get('learning_styles')
    technology = data.get('technology')
    prerequisite_skills = data.get('prerequisite_skills')
    duration = data.get('duration')
    additional_instructions = data.get('additional_instructions')

    if not (grade_level and learning_outcomes and student_count and learning_styles and technology and prerequisite_skills and duration and additional_instructions):
        return jsonify({'error': 'All fields are required'}), 400

    lesson_plan = generate_lesson_plan(lcontent, grade_level, learning_outcomes, student_count, learning_styles, technology, prerequisite_skills, duration, additional_instructions)
    return jsonify({'lesson_plan': lesson_plan})

# Other endpoints and functions...

if __name__ == '__main__':
    app.run(debug=True)

前端JavaScript代码

$(document).ready(function () {
    function generateLessonPlan() {
        console.log("generateLessonPlan called");
        const form = $('#lessonPlanForm');
        if (form[0].checkValidity() === false) {
            form.addClass('was-validated');
            return;
        }

        const lessonPlanData = {
            grade_level: $('#grade_level').val(),
            learning_outcomes: $('#learning_outcomes').val(),
            student_count: $('#student_count').val(),
            learning_styles: $('#learning_styles').val(),
            technology: $('#technology').val(),
            prerequisite_skills: $('#prerequisite_skills').val(),
            duration: $('#duration').val(),
            additional_instructions: $('#additional_instructions').val()
        };

        console.log("Collected data:", lessonPlanData);
        showLoadingSpinner();

        $.ajax({
            type: 'POST',
            url: '/generate',
            contentType: 'application/json',
            data: JSON.stringify(lessonPlanData),
            success: function (response) {
                $('#lesson-plan').text(response.lesson_plan);
                localStorage.setItem('lessonPlanContent', response.lesson_plan);
                hideLoadingSpinner();
            },
            error: function (xhr, status, error) {
                console.error('Error generating lesson plan:', error);
                alert('Error generating lesson plan: ' + error);
                hideLoadingSpinner();
            }
        });
    }

    $('#generateButton').click(generateLessonPlan);
});

错误详情

向/generate端点发送POST请求时,无论是通过前端页面还是使用curl工具,都会收到405 Method Not Allowed错误。

Heroku日志输出:

2024-06-09T12:36:28.631907+00:00 heroku[router]: at=info method=POST path="/generate" host=oecslearning-4a5f5abe2dbb.herokuapp.com request_id=73785910-8ef9-4c37-9ee6-56686ed171c2 fwd="69.80.2.203" dyno=web.1 connect=0ms service=1ms status=405 bytes=712 protocol=https

环境信息

  • Flask版本:1.1.2
  • jQuery版本:3.5.1
  • 运行平台:Heroku

已尝试的排查步骤

  • 确认/generate端点已正确配置为处理POST请求
  • 检查请求URL与端点路径完全匹配
  • 使用curl测试端点,仍得到相同错误:
curl -X POST http://127.0.0.1:5000/generate \
-H "Content-Type: application/json" \
-d '{"lcontent": "Sample content", "grade_level": "5", "learning_outcomes": "Understand key concepts", "student_count": 30, "learning_styles": "Visual, Auditory", "technology": "Computers, Projectors", "prerequisite_skills": "Basic Math, Reading", "duration": "60 minutes", "additional_instructions": "Use interactive activities"}'

请求帮助

恳请协助排查该405错误的成因,并提供解决方法。任何见解或建议都将十分感谢。

内容的提问来源于stack exchange,提问作者Royston Emmanuel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 18:28:14