Python使用async,await,aiohttp未收到响应

问题描述 投票:1回答:1

我正在编写一个可篡改SOAP请求的代理,并使用aiohttp Web应用程序和aiohttp将其发送到目的地以进行异步POST。

我的请求方法定义如下:

async def proxy(request):
    headers = dict(request.headers)
    headers.pop('access-token')

    async with ClientSession(connector=TCPConnector(ssl=False)) as session:
        result = await session.post(
            ACTION,
            data=await request.content.read(),
            headers=request.headers
        )
        retorno = await result.read()

    return web.Response(
        body=retorno,
        status=result.status
    )

这很好用; async read来自来源,async await来自目的地。

但是我需要对该消息做一些改动,如下:

async def proxy(request):
    headers = dict(request.headers)
    headers.pop('access-token')

    async with ClientSession(connector=TCPConnector(ssl=False)) as session:
        data = await request.content.read()
        data = data.replace(b'###USER###', AUTH_USER)
        data = data.replace(b'###PASSWORD###', AUTH_PASSWORD)
        result = await session.post(
            ACTION,
            data=data,
            headers=request.headers
        )
        retorno = await result.read()

    return web.Response(
        body=retorno,
        status=result.status
    )

[这只是停止并且永远在result = await session.post方法中等待。没有收到回应。

有什么想法吗?

python asynchronous proxy async-await aiohttp
1个回答
0
投票

哦,天哪,既la脚又羞愧,但由于测试不当,我最初对我的问题的回答是错误的。

解决方案比我想象的要简单和晦涩得多。

由于我替换了所有标头(试图不对请求进行太多调整,所以我也替换了Content-Length标头。这导致服务器一直等待直到消息结束。

调整消息之前,仅使用headers.pop('Content-Length')并发送了来自发件人的所有标头。

它像一种魅力。

---------原始(错误)答案----------

刚想出来。

在对SoapUI模拟服务进行测试之后,检查请求是否正确。

远程API对我来说是一种未知的技术,但是,即使aiohttp.streams.StreamReader如此返回它,我也不能在数据字段中推送字节数组。

只需将其解码为utf8,一切正常!

async def proxy(request):
    headers = dict(request.headers)
    headers.pop('access-token')

    async with ClientSession(connector=TCPConnector(ssl=False)) as session:
        data = await request.content.read()
        data = data.replace(b'###USER###', USER)
        data = data.replace(b'###PASSWORD###', PASSWORD)
        result = await session.post(
            ACTION,
            data=data.decode('utf8'),
            headers=request.headers
        )
        retorno = await result.read()

    return web.Response(
        body=retorno,
        status=result.status
    )

谢谢大家!

© www.soinside.com 2019 - 2024. All rights reserved.