【Flask】Flask中关于url_for()的坑

本文探讨了在 Flask 开发过程中使用 url_for 函数时常见的问题,特别是当函数名与路由名称不一致时可能导致的错误,并提供了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

概述

在Flask开发中总会遇到一些坑,下面是自己踩到的关于url_for()的坑,是在使用flask的单元测试时遇到的。

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

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

如果route和函数名不一样而导致使用url_for()错误,千万不要去route找错误。 
例如下面的代码:

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'))
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

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:

with app.test_request_context():
    print(url_for('index'))
    print(url_for('LOGIN'))
 
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

打印正常:


/login

参数

url_for()也可以附带一些参数,比如想要完整的URL,可以设置_external为Ture:

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

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

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

参考资料:http://dormousehole.readthedocs.io/en/latest/api.html#flask.url_for

from :http://blog.youkuaiyun.com/yannanxiu/article/details/52287870

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值