4

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

4 Answers 4

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

after receiving url, how could you decode the args?
By doing an args{key} you can get it
4

You mean this?

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

1 Comment

Think about what the query string looks like when key = abc&foo=1. The query string should always be encoded.
2

concat your string and your variables:

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.