将查询字符串中的十六进制传递给 Python

Passing hex in query string to Python

我有一种情况,我想将查询字符串中的十六进制值传递给用 Python 编写的服务器代码。我看到这个答案 The URL looks like (if I want b to contain 0x80):

www.example.com/page?a=10&b=%80

我在Python中做了以下步骤(我想打印并检查我是否能够得到0x80):

#!/usr/bin/python3

import cgitb
import urllib.parse
import os

cgitb.enable()

# Print necessary headers.
print("Content-Type: text/html")
print()

query = os.environ.get('QUERY_STRING')
query = urllib.parse.unquote(query)
# Not able to use print(query) -- throws error
query_print = query.encode('utf-8')
print(query_print)

我得到以下输出:

b'a=10&b=\xef\xbf\xbd' 

我做错了什么?这是我打印的方式吗?

当您尝试将某些内容转换为 utf-8 时,可能会出现一些问题,因为某些字节序列不是有效的 UTF-8 符号。例如 b'\x80'.decode() 抛出错误。当 Python encodes/decodes 一些字节序列时,你可以指定当它遇到一些无效序列时应该发生什么。 urllib.parse.unquote() 默认情况下用于此错误的方法称为 replacereplace 方法只是将无效序列中的每个字节替换为 U+FFFD,以字节为单位相当于 0xEF 0xBF 0xBD

还有其他方法,使用称为 surrogateescape 的方法,它将无效字节映射到有效的 UTF-8 符号(U+DC80 到 U+DCFF),然后在编码到字节时它可以转换这些符号回到原来的字节。这是您使用这种方法编写的代码:

#!/usr/bin/python3

import cgitb
import urllib.parse
import os

cgitb.enable()

# Print necessary headers.
print("Content-Type: text/html")
print()

query = "page?a=10&b=%80"
query = urllib.parse.unquote(query, errors="surrogateescape")
query_print = query.encode('utf-8', 'surrogateescape')
print(query_print)

encoding/decoding 错误处理的完整文档位于 Python documentation