简体   繁体   中英

Colliding Namespace in Python Module with Flask

I have my app in my_module.py, and I have request handlers in posts/. Inside of posts are several different python files.

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.

In my_module, I import post1-3 like so:

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:

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. Which in this case is 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.

What causes this?

add_url_rule uses the __name__ as the default endpoint name, endpoint names must uniquely identify the endpoint to some extent.

pass an endpoint name to add_url_rule like:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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