编写Web App骨架
为了搭建一个高效的网站,网站的IO处理要检查在asyncio(异步io)的基础上,我们可以用aiohttp写一个基本的服务器应用app.py存放在www目录:
app.py
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import logging; logging.basicConfig(level=logging.INFO)import asynciofrom aiohttp import web# 定义服务器响应请求的返回为"Awesome Website"async def index(request): return web.Response(body=b'<h1>Awesome Website</h1>',content_type='text/html')# 建立服务器应用,持续监听本地9000端口的http请求,对首页"/"进行响应def init(): app = web.Application() app.router.add_get('/',index) web.run_app(app,host='127.0.0.1',port=9000)if __name__ == '__main__': init() |
使用aiohttp搭建服务器端,当用户服务根目录"/"时调用的响应函数是index返回'<h1>Awesome Website</h1>'
注意:返回需要加参数代表type为http否则访问的时候是下载当前页面也不是在页面显示
|
1
|
content_type='text/html' |
使用aiohttp创建服务器参考:https://www.cnblogs.com/minseo/p/15513434.html
在www目录下运行这个 app.py, 服务器将在9000端口持续监听 http 请求,并异步对首页 / 进行响应:
|
1
2
3
|
C:/Python37/python.exe d:/awesome-python3-webapp/www/app.py======== Running on http://127.0.0.1:9000 ========(Press CTRL+C to quit) |
打开浏览器输入地址 http://127.0.0.1:9000 进行测试,如果返回我们设定好的Awesome Website字符串,就说明我们网站服务器应用的框架已经搭好了。

服务器端输出日志信息


浙公网安备 33010602011771号