如果一个URL返回的不是HTML,而是机器能直接解析的数据,这个URL就可以看成是一个Web API。
在handlers.py中添加API处理函数:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re, time, json, logging, hashlib, base64, asyncio
from coroweb import get, post
from models import User, Comment, Blog, next_id
# 参数aiohttp.web.request实例,包含了所有浏览器发送过来的HTTP协议里面的信息
@get('/')
async def index(request):
summary = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
blogs = [
Blog(id='1', name='Test Blog', summary=summary, created_at=time.time()-120),
Blog(id='2', name='Write Sth', summary=summary, created_at=time.time()-3600),
Blog(id='3', name='Learn Swift', summary=summary, created_at=time.time()-7200)
]
return {'__template__': 'blogs.html', 'blogs': blogs}
@get('/api/users')
async def api_get_users():
users = await User.findAll(orderBy='created_at desc')
for u in users:
u.passwd = '******'
return dict(users=users)
输入API网址: