博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
网站搭建笔记精简版---廖雪峰WebApp实战-Day9:编写API笔记
阅读量:4165 次
发布时间:2019-05-26

本文共 2094 字,大约阅读时间需要 6 分钟。

什么是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表查询。

参考博客

转载地址:http://vmlxi.baihongyu.com/

你可能感兴趣的文章
Linux进程之alarm()信号传送闹钟函数
查看>>
字节转换为字符串-linux下的itoa函数和window下的spritf函数
查看>>
C++实现链表基本操作
查看>>
malloc与free
查看>>
调用malloc时发生了什么
查看>>
自己动手写内存分配函数malloc
查看>>
linux C之alarm函数
查看>>
如何自实现一个malloc函数(指定区间分配)
查看>>
sscanf中%s用法
查看>>
ps -aux中STAT列的标志位
查看>>
Linux fork() vfork()
查看>>
setsid的作用
查看>>
signal(SIGCHLD, SIG_IGN)
查看>>
vs2010如何引用相对路径
查看>>
Linux 下的KILL函数的用法
查看>>
return EXIT_SUCCESS
查看>>
linux下c程序调用reboot函数实现直接重启
查看>>
select实现延时的功能
查看>>
Linux进程间通信——使用消息队列
查看>>
Linux 消息队列命令
查看>>