简体   繁体   English

使用Flask在Python模块中碰撞命名空间

[英]Colliding Namespace in Python Module with Flask

I have my app in my_module.py, and I have request handlers in posts/. 我在my_module.py中有我的应用程序,并且在posts /中有请求处理程序。 Inside of posts are several different python files. 帖子内部是几个不同的python文件。

My app structure looks like this: 我的应用程序结构如下所示:

./
    my_module.py
    posts/
        __init__.py
        post1.py
        post2.py
        post3.py

And so in post1, post2, and post3, there are 2 functions: add and delete. 因此在post1,post2和post3中,有两个功能:添加和删除。

In my_module, I import post1-3 like so: 在my_module中,我像这样导入post1-3:

import posts.post1
import posts.post2
import posts.post3

I have routes in my_module that point to the add and delete functions as view_functions like so: 我在my_module中有一些路由,这些路由指向添加和删除函数,例如view_functions,如下所示:

app.add_url_rule('/post1_add', methods=['POST'], view_func=posts.post1.add)
app.add_url_rule('/post1_delete', methods=['POST'], view_func=posts.post1.delete)

app.add_url_rule('/post2_add', methods=['POST'], view_func=posts.post2.add)
app.add_url_rule('/post2_delete', methods=['POST'], view_func=posts.post2.delete)

app.add_url_rule('/post3_add', methods=['POST'], view_func=posts.post3.add)
app.add_url_rule('/post3_delete', methods=['POST'], view_func=posts.post3.delete)

For some reason, when I make a post request to any of the URLs I've added above, they all point make their request to the members of the last URL that was added. 出于某种原因,当我对上面添加的任何URL发出发布请求时,它们都会指向最后添加的URL的成员发出请求。 Which in this case is posts.post3. 在这种情况下是posts.post3。

When I change the member function names to be unique, as in post1_add , the app correctly makes a request using its view_function. 当我将成员函数名称更改为唯一时,例如post1_add ,应用程序将使用其view_function正确发出请求。

What causes this? 是什么原因造成的?

add_url_rule uses the __name__ as the default endpoint name, endpoint names must uniquely identify the endpoint to some extent. add_url_rule使用__name__作为默认端点名称,端点名称必须在某种程度上唯一标识端点。

pass an endpoint name to add_url_rule like: 将端点名称传递给add_url_rule例如:

app.add_url_rule('/posts1_add', methods['POST'], 'posts1_add', posts.post1.add)

But for this design pattern you should probably be using Blueprints I think. 但是对于这种设计模式,您可能应该使用我认为的蓝图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM