Reputation: 97
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]"
Upvotes: 4
Views: 18689
Reputation: 131978
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
Upvotes: 6
Reputation: 1808
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
Upvotes: 1
Reputation: 1417
concat your string and your variables:
key = "xxxx"
secret = "xxxx"
url = "http://127.0.0.1:5000/data?key="+key+"&secret="+secret
Upvotes: 2
Reputation: 8978
You mean this?
key = "xxxx"
secret = "xxxx"
url = "http://127.0.0.1:5000/data?key=%s&secret=%s" % (key, secret)
Upvotes: 4