← 返回首页
Python3基础教程(八十二)
发表时间:2022-05-14 10:48:23
aiohttp

asyncio实现了TCP、UDP、SSL等协议,aiohttp则是基于asyncio实现的HTTP框架。

1.aiohttp

aiohttp是一个为Python提供异步HTTP 客户端/服务端编程,基于asyncio(Python用于支持异步编程的标准库)的异步库。asyncio可以实现单线程并发IO操作,其实现了TCP、UDP、SSL等协议,aiohttp就是基于asyncio实现的http框架。

安装aiohttp:

pip3 install aiohttp

2.实例

aiohttp客户端程序,实现爬取百度首页的内容。

# -*- coding: utf-8 -*-
# @Time : 2022/5/17 9:12
# @File : aiohttp_client.py
# @Software : PyCharm

import aiohttp
import asyncio


# 创建获取网页的函数,传递参数为session和一个url
async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()


async def main():
    # 创建session并把session和需要获取网页的url作为参数传递给协程函数fetch
    # 协程函数把网页文本下载下来
    async with aiohttp.ClientSession() as session:
        html = await fetch(session, "http://www.baidu.com")
        print(html)

asyncio.run(main())

aiohttp服务器端程序,然后编写一个HTTP服务器,分别处理以下URL:

/ - 首页返回'<h1>Index</h1>';

/hello/{name} - 根据URL参数返回文本hello, %s!。

from aiohttp import web


async def handle(request):
    # 从请求获取name的属性信息,如果没有则取'Anonymous'
    name = request.match_info.get('name', "Anonymous")
    print(request.match_info)
    # print(request)
    print(name)
    if name == 'Anonymous' :
      text = "<h1>index</h1>"
    else:
      text = "<html><head><meta charset='utf-8'></head><p>Hello," + name+"!</p></html>"
    # 把text作为相应返回,如果访问的为/则返回 "Hello, Anonymous"
    # 如果访问为/{name}则返回对应的 "Hello,{name}"
    return web.Response(body=text.encode('utf-8'),content_type='text/html',charset="utf-8")


app = web.Application()
# 添加两个路由访问/和访问/{name}都去调用函数handle
# 如果使用/访问则默认用户为Anonymous如果使用/{name}访问则用户为对应的{name}
app.add_routes([web.get('/', handle), web.get('/{name}', handle)])

if __name__ == '__main__':
    web.run_app(app)

运行结果:

地址栏输入: http://127.0.0.1:8080/

地址栏输入: http://127.0.0.1:8080/张三