简体   繁体   English

使用python中的变量作为字符串查询来传递url中的参数

[英]use a variable in python as string query to pass parameter in url

I want to use query strings to pass values through a URL. 我想使用查询字符串通过URL传递值。 For example: 例如:

http://127.0.0.1:5000/data?key=xxxx&secret=xxxx

In Python, how can I add the variables to a URL? 在Python中,如何将变量添加到URL? For example: 例如:

key = "xxxx"
secret = "xxxx"
url = "http://127.0.0.1:5000/data?key=[WHAT_GOES_HERE]&secret=[WHAT_GOES_HERE]"

The safest way is to do the following: 最安全的方法是执行以下操作:

import urllib

args = {"key": "xxxx", "secret": "yyyy"}
url = "http://127.0.0.1:5000/data?{}".format(urllib.urlencode(args))

You will want to make sure your values are url encoded. 您需要确保您的值是url编码的。

The only characters that are safe to send non-encoded are [0-9a-zA-Z] and $-_.+!*'() 唯一可以安全发送非编码的字符是[0-9a-zA-Z]和$ -_。+!*'()

Everything else needs to be encoded. 其他一切都需要编码。

For additional information read over page 2 of RFC1738 有关其他信息,请参阅RFC1738的第2页

You mean this? 你是这个意思?

key = "xxxx"
secret = "xxxx"
url = "http://127.0.0.1:5000/data?key=%s&secret=%s" % (key, secret)

concat your string and your variables: 连接你的字符串和你的变量:

key = "xxxx"
secret = "xxxx"
url = "http://127.0.0.1:5000/data?key="+key+"&secret="+secret

I think use formatter is better(when you have many parameter, this is more clear than %s): 我认为使用formatter更好(当你有很多参数时,这比%s更清晰):

>>> key = "xxxx"
>>> secret = "xxxx"
>>> url = "http://127.0.0.1:5000/data?key={key}&secret={secret}".format(key=key, secret=secret)
>>> print(url)
http://127.0.0.1:5000/data?key=xxxx&secret=xxxx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM