¿Cómo codificar una querystring en Python?


Estoy intentando codificar esta cadena antes de enviarla.

queryString = 'eventName=' + evt.fields["eventName"] + '&' + 'eventDescription=' + evt.fields["eventDescription"]; 
Author: Gringo Suave, 2011-04-10

12 answers

Necesita pasar sus parámetros a urlencode() como una asignación (dict), o una secuencia de 2-tuplas, como:

>>> import urllib
>>> f = { 'eventName' : 'myEvent', 'eventDescription' : 'cool event'}
>>> urllib.urlencode(f)
'eventName=myEvent&eventDescription=cool+event'

Python 3 o superior

Uso:

>>> urllib.parse.urlencode(f)
eventName=myEvent&eventDescription=cool+event
 413
Author: bgporter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-12 05:13:34

Python 2

Lo que estás buscando es urllib.quote_plus:

>>> urllib.quote_plus('string_of_characters_like_these:$#@=?%^Q^$')
'string_of_characters_like_these%3A%24%23%40%3D%3F%25%5EQ%5E%24'

Python 3

En Python 3, el paquete urllib se ha dividido en componentes más pequeños. Usarás urllib.parse.quote_plus (observe el módulo secundario parse)

import urllib.parse
urllib.parse.quote_plus(...)
 864
Author: Ricky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-06 17:23:35

Contexto

  • Python (versión 2.7.2)

Problema

  • Desea generar una cadena de consulta urlencoded.
  • Tiene un diccionario u objeto que contiene los pares nombre-valor.
  • Desea poder controlar el orden de salida de los pares nombre-valor.

Solución

  • urllib.urlencode
  • urllib.quote_plus

Trampas

Ejemplo

La siguiente es una solución completa, incluyendo cómo lidiar con algunos escollos.

### ********************
## 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"    : "[email protected]",
  }

### ********************
## 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
  """ 
 35
Author: dreftymac,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:26

Pruebe requests en lugar de urllib y no necesita molestarse con urlencode!

import requests
requests.get('http://youraddress.com', params=evt.fields)

EDITAR:

Si necesita pares nombre-valor ordenados o múltiples valores para un nombre, establezca parámetros como:

params=[('name1','value11'), ('name1','value12'), ('name2','value21'), ...]

En lugar de usar un diccionario.

 30
Author: Barnabas Szabolcs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-19 19:12:42
 23
Author: Janus Troelsen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-27 21:35:06

Tenga en cuenta que el urllib.urlencode no siempre hace el truco. El problema es que algunos servicios se preocupan por el orden de los argumentos, que se pierde cuando se crea el diccionario. Para tales casos, urllib.quote_plus es mejor, como sugirió Ricky.

 21
Author: user411279,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-30 20:23:23

Prueba esto:

urllib.pathname2url(stringToURLEncode)

urlencode no funcionará porque solo funciona en diccionarios. quote_plus no produjo la salida correcta.

 20
Author: Charlie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-03 21:25:49

En Python 3, esto funcionó conmigo

import urllib

urllib.parse.quote(query)
 7
Author: Mazen Aly,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-05 23:12:50

Para referencias futuras (ej: para python3)

>>> import urllib.request as req
>>> query = 'eventName=theEvent&eventDescription=testDesc'
>>> req.pathname2url(query)
>>> 'eventName%3DtheEvent%26eventDescription%3DtestDesc'
 3
Author: nickanor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-19 15:29:10

Si el urllib.analizar.urlencode () te está dando errores , luego prueba el módulo urllib3 .

La sintaxis es la siguiente:

import urllib3
urllib3.request.urlencode({"user" : "john" }) 
 1
Author: Natesh bhat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-23 05:52:34

Otra cosa que podría no haberse mencionado ya es que urllib.urlencode() codificará valores vacíos en el diccionario como la cadena None en lugar de tener ese parámetro como ausente. No se si esto es típicamente deseado o no, pero no se ajusta a mi caso de uso, por lo tanto tengo que usar quote_plus.

 0
Author: Joseph,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-09 17:46:43
 -1
Author: Arjen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-04-09 20:08:14