簡體   English   中英

Python 使用異步、等待、aiohttp 未收到響應

[英]Python no response received using async, await, aiohttp

我正在編寫一個代理來篡改 SOAP 請求,並使用 aiohttp web Application 和 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方法。 沒有收到回應。

有任何想法嗎?

哦,天哪,這既蹩腳又可恥,但由於測試不當,我對問題的最初回答是錯誤的。

解決方案比我想象的要簡單和模糊得多。

因為我要替換所有的標頭(盡量不要過多地調整請求),所以我也替換了 Content-Length header。 這導致服務器一直等待到消息的末尾。

在調整消息之前,只需使用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
    )

謝謝你們!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM