zoukankan      html  css  js  c++  java
  • aiohttp简介及快速使用

    前言

    本文翻译自aiohttp官方文档,如有纰漏,欢迎指出。

    aiohttp是一个为Python提供异步HTTP 客户端/服务端编程,基于asyncio(Python用于支持异步编程的标准库)的异步库。

    核心功能:

    • 同时支持客户端使用和服务端使用。
    • 同时支持服务端WebSockets组件和客户端WebSockets组件,开箱即用呦。
    • web服务器具有中间件,信号组件和可插拔路由的功能。

    aiohttp库安装:

    pip install aiohttp

    你可能还想安装更快的cchardet库来代替chardet进行解码:

    pip install cchardet

    对于更快的客户端API DNS解析方案,aiodns是个很好的选择,极力推荐: 

    pip install aiodns

    快速开始:

    客户端例子:

    import aiohttp
    import asyncio
    import async_timeout
    
    async def fetch(session, url):
        with async_timeout.timeout(10):
            async with session.get(url) as response:
                return await response.text()
    
    async def main():
        async with aiohttp.ClientSession() as session:
            html = await fetch(session, 'http://python.org')
            print(html)
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

    服务端例子:

    from aiohttp import web
    
    async def handle(request):
        name = request.match_info.get('name', "Anonymous")
        text = "Hello, " + name
        return web.Response(text=text)
    
    app = web.Application()
    app.router.add_get('/', handle)
    app.router.add_get('/{name}', handle)
    
    web.run_app(app)

    注意:

    这篇文档的所有例子都是利用 async/await 语法来完成的,此语法介绍请看PEP 492,此语法仅Python 3.5+有效。 如果你使用的是Python 3.4, 请将await替换成yield from,将async 替换成带有 @corotine装饰器的def. 比如

    async def coro(...):
        ret = await f()

    应替换为:

    @asyncio.coroutine
    def coro(...):
       ret = yield from f()
  • 相关阅读:
    synchronized关键字原理
    http几种请求格式总结
    logback配置
    docker部署nacos单机
    Diango migrate遇到问题
    pip安装ujson报错: error:Microsoft Visual C++ 14.0 is required
    vue watch监听新增属性
    git commit message规范与约束(全局安装)
    git commit message规范与约束(项目内安装)
    pip常用方法
  • 原文地址:https://www.cnblogs.com/zycorn/p/10554121.html
Copyright © 2011-2022 走看看