Using url_for according to drawings

Does url_for according to drawings?

 /flaskapp /runserver.py (from server import app; app.run(debug=True)) /server /__init__.py (app = Flask(__name__)) /pages /__init__.py ('pages' blueprint) /users /__init__.py ('users' blueprint) 

in server/__init__.py :

 from server.pages import pages from server.users import users app = Flask(__name__) app.register_blueprint(pages) app.register_blueprint(users) 

in server/pages/__init__.py :

 pages = Blueprint('pages', __name__) @pages.route('/') def index(): return '<h1>Index</h1>' 

in server/users/__init__.py :

 users = Blueprint('users', __name__) @users.route('/login') def login(): ... return redirect(url_for('pages.index')) ^^^^^^^^^^^^^^^^^^^^^^ 

Calling url_for raises a BuildError: ('pages.index', {}, None) How can I get to 'pages.index' ?

(I tried to import the module, but that did not work)

+6
source share
2 answers

Short answer: Yes

Long (ish) Answer:

As far as I can tell, you organize your application the way you need.

I recreated your setup (albeit in a single file), which you can check here. This code works on my machine.

https://gist.github.com/enlore/80bf02346d6cabcba5b1

In the bulb, you can access a specific view function with a relative endpoint ( .login ) from the ownership drawing or through the absolute ( user.login ) anywhere.

My money you have a typo in the name of the view function.

As Mark Hildreth noted in the comments, a great way to debug your problem would be to look at your URL map.

 >>> from app import app >>> app.url_map Map([<Rule '/login' (HEAD, OPTIONS, GET) -> user.login>, <Rule '/' (HEAD, OPTIONS, GET) -> pages.index>, <Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>]) >>> 
+3
source

If you use url_value_preprocessor , make sure you set url_defaults otherwise url_for will not have enough values ​​to create the url and you will get this rather confusing error message.

Example.

 @bp.url_value_preprocessor def get_project(endpoint, values): project_name = values.pop('project_name') g.project = Project.query.filter_by(name=project_name).first_or_404() @bp.url_defaults def add_project(endpoint, values): if 'project_name' in values or not g.project: return values['project_name'] = g.project.name 
+2
source

Source: https://habr.com/ru/post/955340/


All Articles