在utf-8字符串上使用python的urllib.quote_plus和'safe'参数

gop*_*uri 5 python urllib utf-8 sparql unicode-escapes

我在python代码中有一个unicode字符串:

name = u'Mayte_Martín'
Run Code Online (Sandbox Code Playgroud)

我想将它与SPARQL查询一起使用,这意味着我应该使用'utf-8'对字符串进行编码,并在其上使用urllib.quote_plus或requests.quote.但是,这两个引用函数的行为都很奇怪,因为在使用和不使用'safe'参数时可以看到.

from urllib import quote_plus
Run Code Online (Sandbox Code Playgroud)

没有'安全'的论点:

quote_plus(name.encode('utf-8'))
Output: 'Mayte_Mart%C3%ADn'
Run Code Online (Sandbox Code Playgroud)

有了'安全'的说法:

quote_plus(name.encode('utf-8'), safe=':/')
Output: 
---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-164-556248391ee1> in <module>()
----> 1 quote_plus(v, safe=':/')

/usr/lib/python2.7/urllib.pyc in quote_plus(s, safe)
   1273         s = quote(s, safe + ' ')
   1274         return s.replace(' ', '+')
-> 1275     return quote(s, safe)
   1276 
   1277 def urlencode(query, doseq=0):

/usr/lib/python2.7/urllib.pyc in quote(s, safe)
   1264         safe = always_safe + safe
   1265         _safe_quoters[cachekey] = (quoter, safe)
-> 1266     if not s.rstrip(safe):
   1267         return s
   1268     return ''.join(map(quoter, s))

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 10: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

问题似乎与rstrip功能有关.我试着做一些改变并打电话给......

quote_plus(name.encode('utf-8'), safe=u':/'.encode('utf-8'))
Run Code Online (Sandbox Code Playgroud)

但这并没有解决问题.这可能是什么问题?

gop*_*uri 11

我正在回答我自己的问题,以便它可以帮助那些面临同样问题的人.

在执行任何其他操作之前,在当前工作空间中进行以下导入时会出现此特定问题.

from __future__ import unicode_literals
Run Code Online (Sandbox Code Playgroud)

事实证明这与以下代码序列不兼容.

from urllib import quote_plus

name = u'Mayte_Martín'
quote_plus(name.encode('utf-8'), safe=':/')
Run Code Online (Sandbox Code Playgroud)

没有导入unicode_literals的相同代码工作正常.


Xia*_*iao 5

根据此bug,这里是解决方法:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from urllib import quote_plus
name = u'Mayte_Martín'
quote_plus(name.encode('utf-8'), safe=':/'.encode('utf-8'))
Run Code Online (Sandbox Code Playgroud)

您必须encode同时使用quote或quote_plus方法来utf-8