简体   繁体   English

Python-从URL参数读取特殊字符

[英]Python - special characters reading from URL parameter

I am reading URL parameter from the below URL 我正在从下面的URL中读取URL参数

http://exaple.com/api/v1/get_example/?fruits_name=[apple%20+%20banana]

fruits = urllib.unquote(request.GET.get('fruits_name', None)).decode('utf8')
    print fruits

my output is: [apple banana] in between apple and banana I am getting three spaces but not + symbol in my output. 我的输出是: [apple banana]在苹果和香蕉之间,我的输出中得到三个空格,但没有+符号。 the original string is [apple + banana] . 原始字符串是[apple + banana] I need output as [apple + banana] . 我需要输出为[apple + banana]

Can anyone suggest where I am doing wrong?? 谁能建议我做错了什么?

You probably need to use %2B 您可能需要使用%2B

Ex: 例如:

http://exaple.com/api/v1/get_example/?fruits_name=[apple%20%2B%20banana]

Reference 参考

You could split query string on your own to preserve the plus sign: 您可以自行拆分查询字符串以保留加号:

from urllib.parse import urlparse, unquote

u = 'http://exaple.com/api/v1/get_example/?fruits_name=[apple%20+%20banana]'

o = urlparse(u)
qs = unquote(o.query)

queryDict = {k: v for (k, v) in [x.split("=", 1) for x in qs.split("&")]}
print(queryDict)

Prints: 打印:

{'fruits_name': '[apple + banana]'}

Replace special characters in string using the %xx escape. 使用%xx转义符替换字符串中的特殊字符。 Letters, digits, and the characters '_.-' are never quoted. 字母,数字和字符“ _.-”都不会被引用。 By default, this function is intended for quoting the path section of the URL.The optional safe parameter specifies additional characters that should not be quoted — its default value is '/' 默认情况下,此函数用于引用URL的路径部分。可选的safe参数指定不应引用的其他字符-其默认值为'/'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM