如何让同一Flask应用同时支持HTML模板渲染与Swagger文档端点?
问题解决方法
1. 确认模板文件路径
Flask默认从项目根目录下的templates文件夹加载模板,必须满足两个条件:
- 项目根目录下存在名为
templates的文件夹 index.html文件放置在该文件夹内,路径为./templates/index.html
如果你的模板文件不在默认路径,初始化Flask时可以手动指定模板目录:
app = Flask(__name__, template_folder='自定义模板路径')
2. 避免路由冲突(可选)
当前Api的doc='/api'设置没问题,但如果担心根路由被覆盖,可以给API接口指定前缀,隔离路由空间:
api = Api(app, version='1.0', title='Sample API', description='A sample API', doc='/api', prefix='/api/v1')
此时/get_files接口的访问路径变为/api/v1/get_files,Swagger文档仍保持/api可访问。
3. 验证根路由是否生效
可以给根路由添加调试日志,确认路由是否被触发:
@app.route('/') def index(): print("根路由已触发") # 启动应用后访问根路径,控制台会打印该信息 return render_template('index.html', nodes=config['nodes'], files=[])
如果控制台打印日志但页面仍异常,问题出在模板文件;如果无日志,说明路由被其他规则覆盖。
完整可运行代码
from flask import Flask, render_template, request from flask_restx import Api, Resource app = Flask(__name__) api = Api(app, version='1.0', title='Sample API', description='A sample API', doc='/api') # Sample data config = { 'nodes': ['Node1', 'Node2', 'Node3'], 'files': { 'Node1': ['File1', 'File2'], 'Node2': ['File3', 'File4'], 'Node3': ['File5', 'File6'] } } @app.route('/') def index(): return render_template('index.html', nodes=config['nodes'], files=[]) @api.route('/get_files') class Files(Resource): def post(self): selected_node = request.form['selected_node'] files = config['files'].get(selected_node, []) return {'files': files} if __name__ == '__main__': app.run(debug=True)
内容的提问来源于stack exchange,提问作者Ciasto piekarz
相关产品推荐
相关产品推荐

