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

Python Flask开发:调用REST接口时出现404错误求助

Flask REST接口404错误排查

问题描述

我是Python和Flask新手,学习开发时创建了一个REST接口,但调用时返回404错误,提示请求的URL在服务器上未找到。

调用的curl命令

curl --location --request POST 'http://127.0.0.1:5000/api/send_verification_email' 
--header 'Content-Type: application/json' 
--data-raw '{
  "email": "sdsdsfs@gmail.com",
  "verification_code": "PQRST"
}
'

路由文件(app/api/views.py)代码

from flask import Blueprint, jsonify
from app.services.email_service import send_verification_email
import logging

logger = logging.getLogger('my_logger')

notification_bp = Blueprint('notification_bp', __name__)


@notification_bp.route('/send_verification_email', methods=['POST'])
def send_verification_email_route():
    response, status_code = send_verification_email()
    return jsonify(response), status_code

app.py代码

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_mail import Mail
from config import config

import logging

# Set the log level (choose the appropriate level based on your needs)
logging.basicConfig(level=logging.DEBUG)

# Define the log format (customize it according to your preferences)
log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
logging.basicConfig(format=log_format)

# Optionally, specify a log file to write the logs to a file
# logging.basicConfig(filename='notification_service.log', format=log_format)

app = Flask(__name__)
app.config.from_object(config)

from app.api.views import notification_bp
app.register_blueprint(notification_bp, url_prefix='/api')

#db = SQLAlchemy(app)
mail = Mail(app)

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

错误原因排查及解决方法

  • 蓝图导入路径不匹配:检查from app.api.views import notification_bp是否和你的项目目录结构一致。如果路由文件实际位置不是app/api/views.py,比如放在app/views/notification.py,需要修改导入语句对应路径。
  • 蓝图未成功注册:启动应用时查看DEBUG日志,确认是否有蓝图注册的相关记录。如果没有,说明蓝图导入或注册环节出错,检查是否有语法错误或导入顺序问题。
  • 端口/地址不匹配:确认curl请求的127.0.0.1:5000和app.run()启动的服务地址、端口一致。如果启动时指定了其他端口(比如app.run(port=5001)),需同步修改curl的URL。
  • 路由缩进或语法错误:检查@notification_bp.route装饰器是否正确绑定到send_verification_email_route函数,没有缩进错误或语法问题导致路由未被识别。

另外,即使解决404问题,当前代码还存在一个潜在错误:路由函数调用send_verification_email()时未传递请求中的email和verification_code参数,后续会出现参数缺失问题,建议修改路由函数获取请求数据:

from flask import Blueprint, jsonify, request

# ...

@notification_bp.route('/send_verification_email', methods=['POST'])
def send_verification_email_route():
    data = request.get_json()
    email = data.get('email')
    verification_code = data.get('verification_code')
    response, status_code = send_verification_email(email, verification_code)
    return jsonify(response), status_code

内容的提问来源于stack exchange,提问作者Saurabh Garg

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 23:47:31