Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIHugging Face LMArena Human Preference 140K

python 异步http服务器

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Geminigemini-2.5-pro-preview-05-06’s answer.
  1. User

    python 异步http服务器

  2. Assistant

    当然!下面是一个使用 Python 的 asyncio 和 aiohttp 库实现的简单异步 HTTP 服务器示例。


    使用 aiohttp 实现异步 HTTP 服务器

    安装依赖

    pip install aiohttp
    

    代码示例

    from aiohttp import web
    import asyncio
    
    async def handle(request):
        name = request.rel_url.query.get('name', 'world')
        text = f"Hello, {name}!"
        return web.Response(text=text)
    
    async def init_app():
        app = web.Application()
        app.router.add_get('/', handle)
        return app
    
    if __name__ == '__main__':
        app = asyncio.run(init_app())
        web.run_app(app, host='0.0.0.0', port=8080)
    

    说明

    • 这个服务器监听 8080 端口。
    • 访问 http://localhost:8080/?name=ChatGPT 会返回 Hello, ChatGPT!。
    • 使用 aiohttp,请求处理是异步的,适合高并发场景。

    如果你想用更底层的 asyncio 自己写一个简单的异步 HTTP 服务器,也可以,示例如下:

    纯 asyncio 实现简单异步 HTTP 服务器

    import asyncio
    
    async def handle_client(reader, writer):
        data = await reader.read(1024)
        message = data.decode()
        addr = writer.get_extra_info('peername')
    
        print(f"Received {message!r} from {addr!r}")
    
        response = (
            "HTTP/1.1 200 OK\r\n"
            "Content-Type: text/plain; charset=utf-8\r\n"
            "Content-Length: 13\r\n"
            "\r\n"
            "Hello, world!"
        )
        writer.write(response.encode())
        await writer.drain()
        writer.close()
        await writer.wait_closed()
    
    async def main():
        server = await asyncio.start_server(handle_client, '0.0.0.0', 8080)
        addrs = ', '.join(str(sock.getsockname()) for sock in server.sockets)
        print(f'Serving on {addrs}')
    
        async with server:
            await server.serve_forever()
    
    if __name__ == '__main__':
        asyncio.run(main())
    

    如果你有更具体的需求(比如路由、POST 请求、JSON 处理等),可以告诉我,我帮你写更详细的示例。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.