¿Cómo codificar por ciento los parámetros de URL en Python?


Si lo hago

url = "http://example.com?p=" + urllib.quote(query)
  1. No codifica / a %2F (rompe la normalización OAuth)
  2. No maneja Unicode (lanza una excepción)

¿Hay una biblioteca mejor?

Author: Aminah Nuraini, 2009-11-08

4 answers

De los documentos :

urllib.quote(string[, safe])

Reemplazar caracteres especiales en cadena usando el escape % xx. Letras, dígitos, y los personajes_.- 'nunca son citar. Por defecto, esta función es destinado a citar la sección de ruta de la URL.El parámetro seguro opcional especifica caracteres adicionales que no debe ser citado - su valor predeterminado el valor es '/'

Eso significa que pasar "for safe" resolverá tu primer problema:

>>> urllib.quote('/test')
'/test'
>>> urllib.quote('/test', safe='')
'%2Ftest'

Acerca de el segundo problema, hay un informe de error al respecto aquí. Aparentemente fue arreglado en python 3. Puede solucionarlo codificando como utf8 de la siguiente manera:

>>> query = urllib.quote(u"Müller".encode('utf8'))
>>> print urllib.unquote(query).decode('utf8')
Müller

Por cierto, echa un vistazo a urlencode

Tenga en cuenta que urllib.quote se trasladó a {[4] } en Python3

 314
Author: Nadia Alramli,
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-08-21 14:50:10

En Python 3, urllib.quote se ha movido a urllib.parse.quote y maneja unicode por defecto.

>>> from urllib.parse import quote
>>> quote('/test')
'/test'
>>> quote('/test', safe='')
'%2Ftest'
>>> quote('/El Niño/')
'/El%20Ni%C3%B1o/'
 129
Author: Paolo Moretti,
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-11-29 11:52:51

Mi respuesta es similar a la respuesta de Paolo.

Creo que el módulo requests es mucho mejor. Se basa en urllib3. Puedes probar esto:

>>> from requests.utils import quote
>>> quote('/test')
'/test'
>>> quote('/test', safe='')
'%2Ftest'
 35
Author: Aminah Nuraini,
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
2016-04-23 06:08:31

Si estás usando django, puedes usar urlquote:

>>> from django.utils.http import urlquote
>>> urlquote(u"Müller")
u'M%C3%BCller'
 10
Author: Rick Westera,
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-10-27 19:40:21