如何使用aiohttp获取客户端的IP地址

How to get the IP address of a client using aiohttp

我目前正在开发一个 django 项目,我使用 aiohttp 在后端和前端之间进行通信。当从前端发出请求时,我想获取客户端的 IP 地址。查看了不同的文档,但 none 似乎准确地指出了如何使用 aiohttp 获取 IP 地址。有人帮忙!

from aiohttp import web


async def handler(request):

    ws = web.WebSocketResponse()
    await ws.prepare(request)

    try:
        async for msg in ws:
            # handle incoming messages
            # use ws.send_str() to send data back
            ...

    finally:
        task.cancel()

基于aiohttp docs,您可以从请求remote参数(request.remote)中获取客户端发起的HTTP请求的原始IP地址。