[英]Flask use URL variable in function
在flask的函数中可以使用URL变量吗? 我进行了广泛的搜索,但没有任何明智的选择。
如果我在html模板中显示pathVariable
,它将显示我输入的内容。
from flask import Flask, request
app = Flask(__name__)
@app.route('/<pathVariable>/')
def test(pathVariable=pathVariable):
test = pathVariable
path = request.path
script_root = request.script_root
base_url = request.base_url
url = request.url
url_root = request.url_root
url_rule = request.url_rule
print ("test is: %s" %path)
print ("path is: %s" %path)
print ("script_root is: %s" %script_root)
print ("base_url is: %s" %base_url)
print ("url is: %s" %url)
print ("url_root is: %s" %url_root)
print ("url_rule is: %s" %url_rule)
return render_template('/example.html', pathVariable=pathVariable)
if __name__ == '__main__':
app.run()
例如,如果我输入:
127.0.0.1:5000/tryone和127.0.0.1:5000/trytwo的pathVariable
将呈现为tryone
或trytwo
HTML模板内。
但是在test
函数中,我得到的打印输出是:
test is: /favicon.ico/
path is: /favicon.ico/
script_root is:
base_url is: http://http://127.0.0.1:5000/favicon.ico/
url is: http://http://127.0.0.1:5000/favicon.ico/
url_root is: http://http://127.0.0.1:5000/
url_rule is: /<pathVariable >/
我有什么办法可以在test
函数中获取tryone
或trytwo
? 我有一本字典,其中包含与这些变量中的每一个相关的列表,它们确定必须将哪些变量返回(呈现)回html模板。
您正在函数中定义pathVariable
,这似乎是问题所在。 将您的代码更改为此:
from flask import Flask, request
app = Flask(__name__)
@app.route('/<pathVariable>/')
def test(pathVariable):
test = pathVariable
path = request.path
script_root = request.script_root
base_url = request.base_url
url = request.url
url_root = request.url_root
url_rule = request.url_rule
print ("test is: %s" %path)
print ("path is: %s" %path)
print ("script_root is: %s" %script_root)
print ("base_url is: %s" %base_url)
print ("url is: %s" %url)
print ("url_root is: %s" %url_root)
print ("url_rule is: %s" %url_rule)
return render_template('/example.html', pathVariable=pathVariable)
if __name__ == '__main__':
app.run()
打印出来
127.0.0.1 - - [28/Jan/2016 13:49:02] "GET /trytwo HTTP/1.1" 301 -
test is: /trytwo/
path is: /trytwo/
script_root is:
base_url is: http://localhost:5000/trytwo/
url is: http://localhost:5000/trytwo/
url_root is: http://localhost:5000/
url_rule is: /<pathVariable>/
127.0.0.1 - - [28/Jan/2016 13:49:02] "GET /trytwo/ HTTP/1.1" 500 -
test is: /favicon.ico/
path is: /favicon.ico/
script_root is:
base_url is: http://localhost:5000/favicon.ico/
url is: http://localhost:5000/favicon.ico/
url_root is: http://localhost:5000/
url_rule is: /<pathVariable>/
127.0.0.1 - - [28/Jan/2016 13:49:02] "GET /favicon.ico/ HTTP/1.1" 500 -
此外,所有网页都会尝试为该网站找到收藏夹图标,因此显示代码的异常并非罕见。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.