首页 > 解决方案 > Python Aiohttp 客户端 - 禁用编码重定向 url

问题描述

我正在使用 aiohttp 客户端向 URL 发送请求并收集重定向的 URL。

在我的例子中,重定向的 URL 中包含 Unicode 文本。我希望它保持不变。

例如,实际重定向的 URL 是example.com/förderprojekte-ev,但 aiohttp 客户端自动对其进行编码并返回我example.com/f\udcf6rderprojekte-ev

如何使 aiohttp 禁用重定向 url 的自动编码。

对于请求模块,解决方案有效,但我需要 aiohttp 的帮助。

我的代码:

async fetch(url):
    #url = 'https://www.example.com/test/123'
    async with client.get(url, allow_redirects = True ) as resp:
        html = await resp.read()
        redir_url = str(resp.url)
        #example.com/f\udcf6rderprojekte-e-v

或至少告诉我如何将\udcf6转换为ö

标签: pythonpython-requestsurlencodeaiohttp

解决方案


async def handle_redirected_url(request):
    # https://
    scheme = request.scheme
    # example.com
    host = request.host
    # /f\udcf6rderprojekte-e-v
    unencoded_path = request.raw_path
    
    unencoded_url = scheme+host+unencoded_path
    return web.json_response(status=200, data={'unencoded_url': unencoded_url)

请参阅https://docs.aiohttp.org/en/stable/web_reference.html中的请求对象属性


推荐阅读