从Flask路径中的URL获取变量 [英] Get a variable from the URL in a Flask route

查看:803
本文介绍了从Flask路径中的URL获取变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多以登陆页开头的网址,并以唯一的ID结尾。我需要能够从URL中获取id,以便将其他系统的一些数据传递给我的Flask应用程序。

I have a number of URLs that start with landingpage and end with a unique id. I need to be able to get the id from the URL, so that I can pass some data from another system to my Flask app. How can I get this value?

http://localhost/landingpageA
http://localhost/landingpageB
http://localhost/landingpageC


推荐答案

在文档的快速入门中得到了解答。您应该检查一下,它介绍了许多Flask的核心概念。其他的文档也是一个很好的资源。

This is answered right in the quickstart of the docs. You should check it out, it introduces many of the core concepts of Flask. The rest of the docs are a great resource too.

您需要一个变量url,通过指定< name> code>,并在视图函数中接受 name

You want a variable url, which you create by specifying a <name> in the url and accepting name in the view function.

@app.route('/landingpage<id>')
def landing_page(id):
    ...

# /landingpageA

更典型的情况是URL的部分用 / 分隔。 p>

More typically the parts of a URL are separated with /.

@app.route('/landingpage/<id>')
def landing_page(id):
    ...

# /landingpage/A

您也可以通过该值作为查询字符串的一部分,以及从请求中获取,但如果总是需要的话,最好使用类似上面的变量。

You could also pass the value as part of the query string, and get it from the request, although if it's always required it's better to use the variable like above.

from flask import request

@app.route('/landingpage')
def landing_page():
    id = request.args['id']
    ...

# /landingpage?id=A

这篇关于从Flask路径中的URL获取变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆