简体   繁体   中英

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. For example:

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

In Python, how can I add the variables to a 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.

The only characters that are safe to send non-encoded are [0-9a-zA-Z] and $-_.+!*'()

Everything else needs to be encoded.

For additional information read over page 2 of RFC1738

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):

>>> 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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