www文件夹下app.py:
# -*- coding: utf-8 -*-
import logging; logging.basicConfig(level=logging.INFO)
import asyncio, os, json, time
from datetime import datetime
from aiohttp import web
# 主页
def index(request): # 参数aiohttp.web.request实例,包含了所有浏览器发送过来的HTTP协议里面的信息
return web.Response(body=b'<h1>Day01 of My WebAPP</h1>') # 构造一个HTTP响应
# 协程,不能直接运行,需要把协程加入到事件循环(loop),由后者在适当的时候调用
@asyncio.coroutine
def init(loop):
app = web.Application(loop=loop) # 创建Web服务器,即aiohttp.web.Application类的实例,作用是处理URL、HTTP协议
app.router.add_route('GET', '/', index) # 将URL(HTTP方法、路径)与对应的处理函数绑定
srv = yield from loop.create_server(app.make_handler(), '192.168.179.140', 9000) # 用协程创建TCP服务(这里写的是我的虚拟机地址,为了本机也能访问)
logging.info('Server started at http://192.168.179.140:9000...')
return srv
loop = asyncio.get_event_loop() # 创建一个事件循环
loop.run_until_complete(init(loop)) # 将协程注册到事件循环,并启动事件循环
loop.run_forever() # run_forever会一直运行,直到stop在协程中被调用
运行:
$ python3 app.py
INFO:root:Server started at http://192.168.179.140:9000...
本机打开浏览器,输入192.168.179.140:9000,浏览器页面:
服务器可以看到返回的INFO:
INFO:aiohttp.access:192.168.179.1 - - [07/Nov/2017:03:31:57 +0000] "GET / HTTP/1.1" 200 177 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"