分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 代码编程

aiohttp

发布时间:2023-09-06 01:21责任编辑:傅花花关键词:http

asyncio可实现单线程并发IO操作。如果把asyncio用在服务器端,例如web服务器,由于HTTP连接就是IO操作,因此可以用单线程+协程实现多用户的高并发支持。

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

编写一个HTTP服务器,分别处理以下URL:

   /  首页返回b‘<h1>Index</h1>‘

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

代码如下:

import asynciofrom aiohttp import webasync def index(request): ???await asyncio.sleep(1) ???return web.Response(body=b‘<h1>Index</h1>‘,content_type=‘text/html‘)async def hello(request): ???await ?asyncio.sleep(1) ???text = ‘<h1>hello, %s!</h1>‘ % request.match_info[‘name‘] ???return web.Response(body=text.encode(‘utf-8‘),content_type=‘text/html‘)async def init(loop): ???app = web.Application(loop=loop) ???app.router.add_route(‘GET‘,‘/‘,index) ???app.router.add_route(‘GET‘,‘/hello/{name}‘,hello) ???#创建一个TCP服务 ???srv = await loop.create_server(app.make_handler(),‘127.0.0.1‘,8000) ???print(‘Server started at http://127.0.0.1:8000...‘) ???return srvloop = asyncio.get_event_loop()loop.run_until_complete(init(loop))loop.run_forever()

aiohttp

原文地址:http://www.cnblogs.com/1zhangwenjing/p/7749463.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved