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

启动服务

# 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')
 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值