【Flask】Flask中关于url_for()

概述

在Flask开发中总会遇到一些坑,下面是本身踩到的关于url_for()的坑shell

url_for()函数是用于构建指定函数的URL。

url_for操做对象是函数,而不是route里的路径。flask

若是route和函数名不同而致使使用url_for()错误,千万不要去route找错误。 
例以下面的代码:app

from flask import Flask, url_for
app = Flask(\__name__)

@app.route('/')
def index():
    pass

@app.route('/login')
def LOGIN():
    pass

with app.test_request_context():
    print(url_for('index'))
    print(url_for('login'))

print(url_for('index'))没有报错,就是一个反斜杠;print(url_for('login'))报错,抛出BuildError异常:函数

/ 
Traceback (most recent call last): 
File “<\pyshell#12>”, line 3, in 
print(url_for(‘login’)) 
File “C:\Python35\lib\site-packages\flask\helpers.py”, line 332, in url_for 
return appctx.app.handle_url_build_error(error, endpoint, values) 
File “C:\Python35\lib\site-packages\flask\app.py”, line 1811, in handle_url_build_error 
reraise(exc_type, exc_value, tb) 
File “C:\Python35\lib\site-packages\flask_compat.py”, line 33, in reraise 
raise value 
File “C:\Python35\lib\site-packages\flask\helpers.py”, line 322, in url_for 
force_external=external) 
File “C:\Python35\lib\site-packages\werkzeug\routing.py”, line 1758, in build 
raise BuildError(endpoint, values, method, self) 
werkzeug.routing.BuildError: Could not build url for endpoint ‘login’. Did you mean ‘index’ instead?

把login修改成LOGIN:ui

with app.test_request_context():
    print(url_for('index'))
    print(url_for('LOGIN'))

打印正常:url

/ 
/login

参数

url_for()也能够附带一些参数,好比想要完整的URL,能够设置_external为Ture:spa

url_for('.static',_external=True,filename='pic/test.png')

这样返回的url是http://localhost/static/pic/test.png.net

    • endpoint 
      URL的端点(即函数的名字)
    • values 
      URL的变量参数
    • _external 
      若是设置为True,则生成一个绝对路径URL
    • _scheme 
      一个字符串指定所需的URL方案。_external参数必须设置为True,否则会抛出ValueError。
    • _anchor 
      若是设置了这个则给URL添加一个mao
    • _method 
      若是设置这个则显示地调用这个HTTP方法

转自:https://blog.csdn.net/yannanxiu/article/details/52287870code

相关文章
相关标签/搜索