简体   繁体   中英

Python - special characters reading from URL parameter

I am reading URL parameter from the below 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. the original string is [apple + banana] . I need output as [apple + banana] .

Can anyone suggest where I am doing wrong??

You probably need to use %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. 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 '/'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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