网站搭建笔记精简版---廖雪峰WebApp实战-Day9:编写API笔记

什么是web API?

如果一个URL返回的不是HTML,而是机器能直接解析的数据,这个URL就可以看成是一个Web API。

编写API有什么好处呢?

由于API就是把Web App的功能全部封装了,所以,通过API操作数据,可以极大地把前端和后端的代码隔离,使得后端代码易于测试,前端代码编写更简单。

API函数

一个api也是一个网页处理函数,因此将下列代码加到handlers.py文件中。

@get('/api/users') # 当遇到后缀名为/aip/users的网页时,执行以下代码
def api_get_users(*, page='1'):
    page_index = get_page_index(page)
    num = await User.findNumber('count(id)')
    p = Page(num, page_index)
    # 要是没有user的话,返回空
    if num == 0:
        return dict(page=p, users=())
    users = await User.findAll(orderBy='created_at desc', limit=(p.offset, p.limit))
    # 有user的话,返回所有信息,并将密码覆盖为'******'
    for u in users:
        u.passwd = '******'
    return dict(page=p, users=users)

上述函数返回的为dict,之后的response该middleware可将结果转化为json文件并返回。

API Error函数

当api调用错误的时候,系统会默认返回一个数字,这样不友好,因此提出需要将返回值设置为字符串,将其放入文件apis.py中。内容如下。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'Michael Liao'

'''
JSON API definition.
'''

import json, logging, inspect, functools
# 基础错误
class APIError(Exception):
    '''
    the base APIError which contains error(required), data(optional) and message(optional).
    '''
    def __init__(self, error, data='', message=''):
        super(APIError, self).__init__(message)
        self.error = error
        self.data = data
        self.message = message
# 输入值无效
class APIValueError(APIError):
    '''
    Indicate the input value has error or invalid. The data specifies the error field of input form.
    '''
    def __init__(self, field, message=''):
        super(APIValueError, self).__init__('value:invalid', field, message)
# 资源未发现,数据库里没有这个东西
class APIResourceNotFoundError(APIError):
    '''
    Indicate the resource was not found. The data specifies the resource name.
    '''
    def __init__(self, field, message=''):
        super(APIResourceNotFoundError, self).__init__('value:notfound', field, message)
# 没有权限
class APIPermissionError(APIError):
    '''
    Indicate the api has no permission.
    '''
    def __init__(self, message=''):
        super(APIPermissionError, self).__init__('permission:forbidden', 'permission', message)

最后在浏览器输入http://localhost:9000/api/users即可完成awesome数据库中user表查询。

参考博客
廖雪峰的官方网站
源代码

猜你喜欢

转载自blog.csdn.net/suyiwei5993/article/details/83576393