我已阅读此文档以使用蓝图设置 flask-restful。但由于某种原因,我的 curl 请求通过routes.py
. 这是我的文件结构:
backend
|-tools.py
|-app/
|-project/
|-__init__.py
|-heatmap/
|-__init__.py
|-routes.py
该backend/app/project/__init__.py
文件是我注册所有蓝图的地方,我有一个方法可以创建一个烧瓶应用程序,然后我调用backend/tools.py
. 这是我如何注册蓝图和方法的片段:
backend/app/project/__init__.py
def register_blueprints(app):
from .heatmap import heatmap_blueprint
app.register_blueprint(
heatmap_blueprint,
url_prefix='/heatmap'
)
def create_app(debug=False):
app = Flask(__name__)
app.debug = debug
app.url_map.strict_slashes = False
app.config['SECRET_KEY'] = 'super_secret'
initialize_extensions(app)
register_blueprints(app)
@app.teardown_appcontext
def close_db(error):
"""Closes the database again at the end of the request."""
for db_enum in DB:
db = g.pop(db_enum.value, None)
if db is not None:
db.close()
return app
这是热图的片段routes.py
:
backend/app/project/heatmap/routes.py
from flask import request, render_template
from app.core.heatmap_python.Heatmaps import Heatmaps
from . import heatmap_blueprint
@heatmap_blueprint.route('/', methods=["GET", "POST"])
def index():
if request.method == "GET":
return render_template('heatmap/index.html')
elif request.method == "POST":
data = request.form.to_dict()
h = Heatmaps(data)
response = h.run()
return render_template('heatmap/results.html', response=response)
这是目录的__init__.py
文件heatmap
:
backend/app/project/heatmap/__init__.py
from flask_restful import abort, Resource, Api
from webargs import fields
from webargs.flaskparser import use_args
# from investment_tools import api
from flask import Blueprint, url_for
heatmap_blueprint = Blueprint('heatmap', __name__, template_folder='templates',
static_folder='static', static_url_path='/heatmap/static')
from . import routes
api = Api(heatmap_blueprint)
# API
HEATMAPS = {
'A': {'asd': 'asd'},
'B': {'bcd': 'bcd'}
}
def abort_if_arg_doesnt_exist(args):
print(args)
heatmap_args = {
# All are required arguments
'currency': fields.Str(required=True),
'field': fields.Str(required=True),
'sector': fields.Str(required=True),
'seniority': fields.Str(required=True),
}
class HeatmapApi(Resource):
@use_args(heatmap_args)
def post(self, args):
print("The args are: ")
print(args['currency'])
print(args['field'])
return "<h1>Hello World</h1>", 201
api.add_resource(HeatmapApi, '/heatmap')
所以当我POST
在这个设置中提出请求时,他们会通过routes.py
文件。如果我注释掉这部分:
@heatmap_blueprint.route('/', methods=["GET", "POST"])
def index():
if request.method == "GET":
return render_template('bheatmap/index.html')
elif request.method == "POST":
data = request.form.to_dict()
h = Heatmaps(data)
response = h.run()
return render_template('heatmap/results.html', response=response)
backend/app/project/heatmap/__init__.py
然后似乎没有注册中的 post 端点,因为我收到一个错误,即没有这样的端点: TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
。所以我的设置一定是有缺陷的。你能指出我这里有什么不正确的地方吗?