python - 在 Flask 中使用 app.add_url_rule 的默认值

标签 python flask

我正在使用以下设置 url 端点:

ma​​nager.py

from xxx import ContactAPI
from xxx.models import Contact

# self.app is my Flask app
# self.session is SQLAlchemy Session

api_name = 'contact'
instance_endpoint = '/%s/<int:instid>' % api_name
methods = ['GET']

api_view = ContactAPI.as_view(api_name, self.session,
                              Contact, app)

self.app.add_url_rule(instance_endpoint, methods=methods, 
                      defaults={'instid': None},
                      view_func=api_view)

并覆盖我的 ContactAPI 类中的 get():

views.py

from flask.views import MethodView

class ContactAPI(MethodView):

    def __init__(self, session, model, app, *args, **kwargs):
        super(ContactAPI, self).__init__(*args, **kwargs)

    def get(self, instid):
        print instid

当我点击 URL /contact/1 时,我将 instid 打印为 None

当我从 manager.py 中删除 defaults={'instid': None}, 行时,我将 instid 打印为 1。

为什么我调用 add_url_rule 时的默认行会覆盖我在 URL 中输入的内容?

最佳答案

事实证明我在使用 defaults 时需要注册两个端点.

因为 {'instid': None}传递到 get()在我作为 kwarg 的 ContactAPI View 中,我需要告诉 Flask 设置 instid当 URL /contact 时变为 None被击中。

当我点击 /contact/1 , 我需要使用 <int:instid> .为此,我需要删除 defaults kwarg 在我调用add_url_rule() .

ma​​nager.py

from xxx import ContactAPI
from xxx.models import Contact

# self.app is my Flask app
# self.session is SQLAlchemy Session

api_name = 'contact'
instance_endpoint = '/%s/<int:instid>' % api_name
collection_endpoint = '/%s' % api_name

methods = ['GET']

api_view = ContactAPI.as_view(api_name, self.session,
                              Contact, app)

self.app.add_url_rule(instance_endpoint, methods=methods, 
                      view_func=api_view)

self.app.add_url_rule(collection_endpoint, methods=methods, 
                      defaults={'instid': None},
                      view_func=api_view)

相关的 Werkzeug 文档:http://werkzeug.pocoo.org/docs/routing/#werkzeug.routing.Rule

感谢asdf在 #flask IRC channel 中指出这一点。

关于python - 在 Flask 中使用 app.add_url_rule 的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15421193/

相关文章:

python - Base64解码直到没有Base64

python - 如何将python文件编译为exe文件?

python - 使用 Flask 蓝图解决此循环导入错误的正确方法是什么?

python - 如何在两个不同的内存位置创建 int 1 ?

python - 如何在类里面实现理解

python - 将 Azure Web 应用连接到 Azure Redis 缓存

python - Python脚本之间的通信

python - SQLAlchemy 查询查找按 parent 和祖 parent 过滤的孙子

python - 诗歌在 macOS 12 上的哪里存储 virtualenvs?

javascript - Flask ajax 请求后不要重新加载网页