python flask restful api 统计分析_flask_restful API 模块化示例

一、执行文件run.py

# -*- coding: utf-8 -*-

from exception.handler_exception import HandlerException as handler

from flask_restful import Api

app = Flask(__name__)

api = Api(app)

import app.api.route as route

route.initRoute(api)

if __name__ == '__main__':

"""这个handler处理Api异常"""

#handler.handlerException(handler,app)

#app.run(debug=True)

二、api管理 route.py

from app.api.resource.TestreSource import *

def initRoute(api):

api.add_resource(Test, '/testapi',endpoint='testapi')

api.add_resource(CheckTeacher_age, '/CheckTeacher',endpoint='CheckTeacher')

api.add_resource(CheckTeacher_name, '/CheckTeacher_name/get',endpoint='CheckTeacher_name')

三、api接口文件一TestreSource.py

from flask_restful import Resource

class Test(Resource):

def get(self):

data=[{

"clientSn":2617484,

"sessionTime":"2018-06-21 02:00:00",

"contractSn":50217661

}]

return data

def post(self):

return {'hello': '梅西'}

CheckTeacher_age、CheckTeacher_name文件:

# -*- coding: utf-8 -*-

from flask_restful import Resource,marshal,fields

from app.tools.responseEntity import *

from flask import request

# 对对象进行格式化,只返回前端需要的数据

menu_fields = {

"id": fields.String,

"name": fields.String,

"bolg_url": fields.String

}

class CheckTeacher_age(Resource):

@classmethod

def get(cls):

stu= {

"id": "007",

"name": "霍元甲",

"bolg_url": "http://xiaojingjing.iteye.com"

}

return stu

def post(slef):

id=request.json.get('id')

name=request.json.get('name')

stu={

"id":id,

"name":name

}

data=marshal(stu,menu_fields)

return fullResponse(data=data,code=200,msg="查询成功")

class CheckTeacher_name(Resource):

def get(slef):

#get请求方式,获取rul里面的参数id

id = request.args["id"]

print("url中的id值为:",id)

name = "C罗"

stu={

"id":id,

"name":name

}

code="300"

msg="get获取url参数id成功,id为:%s"%id

return fullResponse(data=stu,code=code,msg=msg)

def post(slef):

id=request.json.get('id')

name=request.json.get('name')

stu={

"id":id,

"name":name

}

data=marshal(stu,menu_fields)

return fullResponse(data=data,code=200,msg="查询成功")

格式化接口返回内容文件

# -*- coding: UTF-8 -*-

from flask import jsonify

def fullResponse(data='', msg='', code=0):

if msg == '':

return jsonify({'code': code, 'data': data})

elif data == '':

return jsonify({'code': code, 'msg': msg})

else:

return jsonify({'code': code, 'msg': msg, 'data': data})

def statusResponse(msg, code=0):

return jsonify({'code': code, 'msg': msg})

请求示例:

url:/CheckTeacher_name/get?id=568 Get

{

"id":123,

"name":"小明"

}

出参:

{

"code": "300",

"data": {

"id": "568",

"name": "C罗"

},

"msg": "get获取url参数id成功,id为:568"

}

rul:/CheckTeacher_age get

出参:

{

"code": 0,

"data": {

"bolg_url": "http://xiaojingjing.iteye.com",

"id": "007",

"name": "霍元甲"

}

}

rul:/CheckTeacher_age post

入参:

{

"id":123,

"name":"小明"

}

出参:

{

"code": 200,

"data": {

"bolg_url": null,

"id": "123",

"name": "小明"

},

"msg": "查询成功"

}

你可能感兴趣的:(python,flask,restful,api,统计分析)