python3 利用flask_restful包写restful接口

1、需要安装的模块

pip install flask
pip install flask-restful
 

2、一个最小的接口像这样:

# coding=utf-8

from flask import Flask
import flask_restful


app = Flask(__name__)
api = flask_restful.Api(app)

class HelloWorld(flask_restful.Resource):
    def get(self):
        return {'hello': 'world'}

api.add_resource(HelloWorld, '/')

if __name__ == '__main__':
    app.run(host='0.0.0.0')


3、资源丰富的路由—- put 、get

启动服务

扫描二维码关注公众号,回复: 5423805 查看本文章

# coding=utf-8

from flask import Flask,request

import flask_restful
from flask_restful import Resource

app = Flask(__name__)
api = flask_restful.Api(app)

todos={}

class HelloWorld(flask_restful.Resource):
    def get(self):
        return {'hello': 'world'}


class TodoSimple(Resource):
        def get(self, todo_id):
            return {todo_id: todos[todo_id]}

        def put(self, todo_id):
            todos[todo_id] = request.form['data']
            return {todo_id: todos[todo_id]}

# api.add_resource(HelloWorld, '/')
api.add_resource(TodoSimple, '/<string:todo_id>')
if __name__ == '__main__':
    app.run(host='0.0.0.0')

发送数据和取数据

# encoding: utf-8
import requests
import re
import time
time1=time.time()

from requests import put, get

html=put('http://localhost:5000/todo1', data={'data': 'Remember the milk'}).json()
print html

get_html=get('http://localhost:5000/todo1').json()
print get_html

结果

"D:\Program Files\Python27\python.exe" D:/PycharmProjects/learn2017/阿里巴巴接口调用.py
{u'todo1': u'Remember the milk'}
{u'todo1': u'Remember the milk'}

Process finished with exit code 0

4、端点

很多时候在一个 API 中,你的资源可以通过多个 URLs 访问。你可以把多个 URLs 传给 Api 对象的 Api.add_resource() 方法。每一个 URL 都能访问到你的 Resource

api.add_resource(HelloWorld,
    '/',
    '/hello')

你也可以为你的资源方法指定 endpoint 参数。

api.add_resource(Todo,
    '/todo/<int:todo_id>', endpoint='todo_ep')
 

猜你喜欢

转载自blog.csdn.net/yournevermore/article/details/88039364