python - Flask 路由到不同模块中具有相同名称的函数

标签 python flask

如果我有 2 个文件,例如:

moduleA.py

from MyPackage import app

@app.route('/moduleA/get')
def get():
    return "a"

moduleB.py

from MyPackage import app

@app.route('/moduleB/get')
def get():
    return "b"

并在 __init__.py

from flask import Flask
import IPython
import logging

app = Flask(__name__,
        static_url_path='', 
        static_folder='static',
        template_folder='templates')
from MyPackage import moduleA, moduleB

然后flask会抛出错误AssertionError: View function mapping is overwriting an existing endpoint function: get

我认为 python 本身在这里没有看到冲突,因为函数在 2 个独立的模块中,但是 flask 有。有没有更好的标准可以在这里使用,还是我必须将函数名称命名为 def getModuleA

最佳答案

可以考虑使用Blueprint

Factor an application into a set of blueprints. This is ideal for larger applications; a project could instantiate an application object, initialize several extensions, and register a collection of blueprints.

例子:

# module_a.py
from flask import Blueprint

blueprint = Blueprint('module_a', __name__)

@blueprint.route('/get')
def get():
    return 'a'

# module_b.py
from flask import Blueprint

blueprint = Blueprint('module_b', __name__)

@blueprint.route('/get')
def get():
    return 'b'

# app.py
from flask import Flask
from module_a import blueprint as blueprint_a
from module_b import blueprint as blueprint_b


app = Flask(__name__)
app.register_blueprint(blueprint_a, url_prefix='/a')
app.register_blueprint(blueprint_b, url_prefix='/b')

# serves:
#  - /a/get
#  - /b/get

关于python - Flask 路由到不同模块中具有相同名称的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46152874/

相关文章:

Python正则表达式忽略日期模式

python - 如何在 Flask 中的 session 结束时运行函数?

python - 如何让 Intellij-idea 正确关闭 Flask 开发服务器?

python - Flask wtforms ValidationError 未向用户显示

找不到 Flask 终端命令

python - 如何用flask创建动态文件发送算法

flask - 主管 gunicorn flask 错误

python - 500 内部服务器错误 : Python Bottle API

python - 为什么 "B"代码没有打印所需的范围?

python - Django 初始化