How to urlencode a querystring in Python?

后端 未结 13 1722
猫巷女王i
猫巷女王i 2020-11-22 11:19

I am trying to urlencode this string before I submit.

queryString = \'eventName=\' + evt.fields[\"eventName\"] + \'&\' + \'eventDescription=\' + evt.fie         


        
相关标签:
13条回答
  • 2020-11-22 11:50

    Context

    • Python (version 2.7.2 )

    Problem

    • You want to generate a urlencoded query string.
    • You have a dictionary or object containing the name-value pairs.
    • You want to be able to control the output ordering of the name-value pairs.

    Solution

    • urllib.urlencode
    • urllib.quote_plus

    Pitfalls

    • dictionary output arbitrary ordering of name-value pairs
      • (see also: Why is python ordering my dictionary like so?)
      • (see also: Why is the order in dictionaries and sets arbitrary?)
    • handling cases when you DO NOT care about the ordering of the name-value pairs
    • handling cases when you DO care about the ordering of the name-value pairs
    • handling cases where a single name needs to appear more than once in the set of all name-value pairs

    Example

    The following is a complete solution, including how to deal with some pitfalls.

    ### ********************
    ## init python (version 2.7.2 )
    import urllib
    
    ### ********************
    ## first setup a dictionary of name-value pairs
    dict_name_value_pairs = {
      "bravo"   : "True != False",
      "alpha"   : "http://www.example.com",
      "charlie" : "hello world",
      "delta"   : "1234567 !@#$%^&*",
      "echo"    : "user@example.com",
      }
    
    ### ********************
    ## setup an exact ordering for the name-value pairs
    ary_ordered_names = []
    ary_ordered_names.append('alpha')
    ary_ordered_names.append('bravo')
    ary_ordered_names.append('charlie')
    ary_ordered_names.append('delta')
    ary_ordered_names.append('echo')
    
    ### ********************
    ## show the output results
    if('NO we DO NOT care about the ordering of name-value pairs'):
      queryString  = urllib.urlencode(dict_name_value_pairs)
      print queryString 
      """
      echo=user%40example.com&bravo=True+%21%3D+False&delta=1234567+%21%40%23%24%25%5E%26%2A&charlie=hello+world&alpha=http%3A%2F%2Fwww.example.com
      """
    
    if('YES we DO care about the ordering of name-value pairs'):
      queryString  = "&".join( [ item+'='+urllib.quote_plus(dict_name_value_pairs[item]) for item in ary_ordered_names ] )
      print queryString
      """
      alpha=http%3A%2F%2Fwww.example.com&bravo=True+%21%3D+False&charlie=hello+world&delta=1234567+%21%40%23%24%25%5E%26%2A&echo=user%40example.com
      """ 
    
    0 讨论(0)
提交回复
热议问题