python小技巧大应用--实测aiohttp可正常运行的写法
2022/2/10 20:20:21
本文主要是介绍python小技巧大应用--实测aiohttp可正常运行的写法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
这两天在学习某大神写的关于aiohttp文章,使用其代码进行测试,不管怎样都运行不成功,用了两天时间查了不少资料,最终得到了满意的结果.现在与大家一起分享
(也许是我的环境与大神的环境有出入,我的开发环境python3.7.4)
1)在test-web项目中新建个test_aiohttpServer.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ' a test aiohttp server ' __author__ = 'TianJiang Gui' import asyncio from aiohttp import web async def handle(request): name = request.match_info.get('name', "Anonymous") text = "Hello, " + name return web.Response(text=text) async def index(request): await asyncio.sleep(0.5) return web.Response(body=b'<h1>Index</h1>', content_type='text/html') async def hello(request): await asyncio.sleep(0.5) text = '<h1>hello, %s!</h1>' % request.match_info['name'] return web.Response(body=text.encode('utf-8'), content_type='text/html') if __name__ == '__main__': app = web.Application() app.add_routes([web.get('/', index), web.get('/{name}', handle), web.get('/hello/{name}', hello)]) web.run_app(app,host='127.0.0.1',port=8100)
2)测试运行
2.1)pycharm中运行
2.2)打开浏览器测试运行
1)测试根路径
2)测试带参数
3)要注意的开发细节
如果要返回body页面内容一定要带上 content_type='text/html'
否则就会成为下载页面,如图:
最后,希望我的付出对大家有所帮助! :)
这篇关于python小技巧大应用--实测aiohttp可正常运行的写法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-04Python外包有哪些常见的主要库-icode9专业技术文章分享
- 2024-10-02基于深度学习的钢铁缺陷检测系统(yolov8、注意力机制、PyQt5界面、Python)
- 2024-10-01怎么用python搭建一个系统-icode9专业技术文章分享
- 2024-09-30Python基础入门教程
- 2024-09-30获取参数学习:Python中的基础教程
- 2024-09-30Python编程基础详解
- 2024-09-29点击加载学习:Python编程基础教程
- 2024-09-29数据科学五大Python前端库:第二部分
- 2024-09-27使用python 将ETH账户的资产打散
- 2024-09-26Python编程基础