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

14,607

Solution 1

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

Solution 2

You mean this?

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

Solution 3

concat your string and your variables:

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

Solution 4

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
Share:
14,607
xy254
Author by

xy254

Updated on June 07, 2022

Comments

  • xy254
    xy254 almost 2 years

    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]"
    
  • sberry
    sberry about 9 years
    Think about what the query string looks like when key = abc&foo=1. The query string should always be encoded.
  • xy254
    xy254 about 9 years
    after receiving url, how could you decode the args?
  • The_Lost_Avatar
    The_Lost_Avatar over 8 years
    By doing an args{key} you can get it