七、python restful框架(python接口开发)

理解

  • 1.每一个URL代表一种资源
  • 2.客户端和服务端之间,传递这种资源的某种表现层,客户端通过四个HTTP动词
  • 对服务端资源进行操作,实现“表现层状态转化”
  • 资源:网络的具体信息,如图片、文字等
  • 表现层:"资源"是一种信息实体,它可以有多种外在表现形式。我们把"资源"具体呈现出来的形式,如,文本可以用txt格式表现,也可以用HTML格式、XML格式、JSON格式表现
  • 状态转化:访问一个网站,就代表了客户端和服务器的一个互动过程。在这个过程中,势必涉及到数据和状态的变化。
  • 4个HTTP动词:GET用来获取资源,POST用来新建资源(也可以用于更新资源),PUT用来更新资源,DELETE用来删除资源。

安装 flask restful

  • 1.cmd输入:pip install flask,安装flask
  • 2.cmd输入:pip install flask-restful,安装flask-restful

安装过程中会出现如下报错:

You are using pip version 9.0.1, however version 19.2.3 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' comm
and.

解决方法

升级pip python -m pip install --upgrade pip
注意:某些Flask版本下,引入模块时采用from flask.ext.restful import Api出错,则可以使用from flask_restful import Api

官网教程

例证

restful.py 内容:

#!/usr/bin/python3
# encoding:utf-8
from flask import Flask,request
from flask_restful import reqparse, abort, Api, Resource

#初始化app、api
app = Flask(__name__)
api = Api(app)

LISTS = [
    {'parameter': '首页'},
    {'parameter': '登录'},
    {'parameter': '后台'}
]

# /LISTS/<list_id>(url参数),判断输入的参数值列表LISTS下标越界,越界则退出
def abort_if_list_doesnt_exist(list_id):
    try:
        LISTS[list_id]
    except IndexError:
        abort(404, message="输入的值,不在范围内")
'''
add_argument('per_page', type=int, location='args') str
add_argument中通过指定参数名、参数类型、参数获取方式来获取参数对象并支持做合法性校验
第一个参数是需要获取的参数的名称
参数type: 参数指的类型, 如果参数中可能包含中文需要使用six.text_type. 或直接不指定type
参数location: 获取参数的方式,可选的有args(url中获取)、json(json类型的)、form(表单方式提交)
参数required:是否必要,默认非必要提供  required=True(必须)
参数help:针对必要的参数,如果请求时没有提供,则会返回help中相应的信息
'''
parser = reqparse.RequestParser()
#入参parameter,location='json'表示为入参为json格式
parser.add_argument('parameter',location='json')

# 路由类,函数get、post、put、delete等实现http请求方法
# url不带入参  /LISTS
class c_dictList(Resource):
    #类型get,根据列表LISTS,处理,返回一个新的列表r_lists
    def get(self):
        r_lists = []
        for listV in LISTS:
            if listV:
                new_list = {}
                #LISTS列表存的是字典,遍历时为字典listV['parameter'],可获取字典值
                new_list['parameter'] = listV['parameter']
                #LISTS为列表,index可以查出对应下标值
                new_list['url'] = 'url/'+ str(LISTS.index(listV))
                #LISTS列表中添加字典
                r_lists.append(new_list)
        return r_lists
        
    #类型post,在列表LISTS后添加一个值,并返回列表值
    def post(self):
        args = parser.parse_args()
        list_id = len(LISTS)
        #args['parameter'],入参
        LISTS.append({'parameter': args['parameter']}) 
        return LISTS, 201
    
# 路由类,函数get、post、put、delete等实现http请求方法
# url带入参  /LISTS/<list_id>
class c_dict(Resource):
    #根据输入url入参值作为LISTS的下标,返回该值
    def get(self, list_id):
        url_int = int(list_id)
        abort_if_list_doesnt_exist(url_int)
        return LISTS[url_int]
    #根据输入url入参值作为LISTS的下标,修改该值,并返回列表值
    def put(self, list_id):
        url_int = int(list_id)
        args = parser.parse_args()
        #args['parameter'],入参
        parameter = {'parameter': args['parameter']}
        LISTS[url_int] = parameter
        return LISTS, 201
    #根据输入url入参值作为LISTS的下标,删除该值
    def delete(self, list_id):
        url_int = int(list_id)
        abort_if_list_doesnt_exist(url_int)
        del LISTS[url_int]
        return '', 204
#设置资源路由api.add_resource(类名,url路径)
#url,不带入参,如:http://127.0.0.1:8891/LISTS
api.add_resource(c_dictList, '/LISTS')
#url,带入参,<list_id>为变量值,如:http://127.0.0.1:8891/LISTS/1
api.add_resource(c_dict, '/LISTS/<list_id>')

if __name__ == '__main__':
    #不设置ip、端口,默认:http://127.0.0.1:5000/
    #app.run(debug=True)
    #设置ip、端口
    app.run(host="127.0.0.1", port=8891,debug=True)

控制台运行结果:

  • Serving Flask app "123" (lazy loading) * Environment: production
    WARNING: This is a development server. Do not use it in a production
    deployment. Use a production WSGI server instead. * Debug mode: on
  • Restarting with stat * Debugger is active! * Debugger PIN: 279-443-943 * Running on http://127.0.0.1:8891/ (Press CTRL+C to
    quit)

postman调用结果

url不带参数
get

在这里插入图片描述

post,有请求入参,格式为json,入参值追加到列表后面

在这里插入图片描述

url带参数
get,根据url入参值如下图值=1,作为LISTS的下标,获取列表值

在这里插入图片描述

put ,根据url入参值如下图值=1,作为LISTS的下标,修改该列表值为请求入参值,登录改为订单

在这里插入图片描述

put ,根据url入参值如下图值=2,作为LISTS的下标,删除该值,成功返回状态204

在这里插入图片描述

猜你喜欢

转载自www.cnblogs.com/yiwenrong/p/12664306.html