使用Python & Flask 实现RESTful Web API的实例


Posted in Python onSeptember 19, 2017

环境安装:

sudo pip install flask

Flask 是一个Python的微服务的框架,基于Werkzeug, 一个 WSGI 类库。

Flask 优点:

Written in Python (that can be an advantage);
Simple to use;
Flexible;
Multiple good deployment options;
RESTful request dispatching

RESOURCES

一个响应 /articles 和 /articles/:id的 API 服务:

from flask import Flask, url_for
app = Flask(__name__)

@app.route('/')
def api_root():
 return 'Welcome'

@app.route('/articles')
def api_articles():
 return 'List of ' + url_for('api_articles')

@app.route('/articles/<articleid>')
def api_article(articleid):
 return 'You are reading ' + articleid

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

请求:

curl http://127.0.0.1:5000/

响应:

GET /
Welcome

GET /articles
List of /articles

GET /articles/123
You are reading 123

REQUESTS

GET Parameters

from flask import request

@app.route('/hello')
def api_hello():
 if 'name' in request.args:
  return 'Hello ' + request.args['name']
 else:
  return 'Hello John Doe'

请求:

GET /hello
Hello John Doe

GET /hello?name=Luis
Hello Luis

Request Methods (HTTP Verbs)

@app.route('/echo', methods = ['GET', 'POST', 'PATCH', 'PUT', 'DELETE'])
def api_echo():
 if request.method == 'GET':
  return "ECHO: GET\n"

 elif request.method == 'POST':
  return "ECHO: POST\n"

 elif request.method == 'PATCH':
  return "ECHO: PACTH\n"

 elif request.method == 'PUT':
  return "ECHO: PUT\n"

 elif request.method == 'DELETE':
  return "ECHO: DELETE"

请求指定request type:

curl -X PATCH http://127.0.0.1:5000/echo
GET /echo
ECHO: GET

POST /ECHO
ECHO: POST

Request Data & Headers

from flask import json

@app.route('/messages', methods = ['POST'])
def api_message():

 if request.headers['Content-Type'] == 'text/plain':
  return "Text Message: " + request.data

 elif request.headers['Content-Type'] == 'application/json':
  return "JSON Message: " + json.dumps(request.json)

 elif request.headers['Content-Type'] == 'application/octet-stream':
  f = open('./binary', 'wb')
  f.write(request.data)
    f.close()
  return "Binary message written!"

 else:
  return "415 Unsupported Media Type ;)"

请求指定content type:

curl -H "Content-type: application/json" \
-X POST http://127.0.0.1:5000/messages -d '{"message":"Hello Data"}'

curl -H "Content-type: application/octet-stream" \
-X POST http://127.0.0.1:5000/messages --data-binary @message.bin

RESPONSES

from flask import Response

@app.route('/hello', methods = ['GET'])
def api_hello():
 data = {
  'hello' : 'world',
  'number' : 3
 }
 js = json.dumps(data)

 resp = Response(js, status=200, mimetype='application/json')
 resp.headers['Link'] = 'http://luisrei.com'

 return resp

查看response HTTP headers:

curl -i http://127.0.0.1:5000/hello

优化代码:

from flask import jsonify

使用

resp = jsonify(data)
resp.status_code = 200

替换

resp = Response(js, status=200, mimetype='application/json')

Status Codes & Errors

@app.errorhandler(404)
def not_found(error=None):
 message = {
   'status': 404,
   'message': 'Not Found: ' + request.url,
 }
 resp = jsonify(message)
 resp.status_code = 404

 return resp

@app.route('/users/<userid>', methods = ['GET'])
def api_users(userid):
 users = {'1':'john', '2':'steve', '3':'bill'}
 
 if userid in users:
  return jsonify({userid:users[userid]})
 else:
  return not_found()

请求:

GET /users/2
HTTP/1.0 200 OK
{
"2": "steve"
}

GET /users/4
HTTP/1.0 404 NOT FOUND
{
"status": 404,
"message": "Not Found: http://127.0.0.1:5000/users/4"
}

AUTHORIZATION

from functools import wraps

def check_auth(username, password):
 return username == 'admin' and password == 'secret'

def authenticate():
 message = {'message': "Authenticate."}
 resp = jsonify(message)

 resp.status_code = 401
 resp.headers['WWW-Authenticate'] = 'Basic realm="Example"'

 return resp

def requires_auth(f):
 @wraps(f)
 def decorated(*args, **kwargs):
  auth = request.authorization
  if not auth: 
   return authenticate()

  elif not check_auth(auth.username, auth.password):
   return authenticate()
  return f(*args, **kwargs)

 return decorated

replacing the check_auth function and using the requires_auth decorator:

@app.route('/secrets')
@requires_auth
def api_hello():
return "Shhh this is top secret spy stuff!"
HTTP basic authentication:

curl -v -u "admin:secret" http://127.0.0.1:5000/secrets

SIMPLE DEBUG & LOGGING

Debug:

app.run(debug=True)
Logging:

import logging
file_handler = logging.FileHandler('app.log')
app.logger.addHandler(file_handler)
app.logger.setLevel(logging.INFO)

@app.route('/hello', methods = ['GET'])
def api_hello():
 app.logger.info('informing')
 app.logger.warning('warning')
 app.logger.error('screaming bloody murder!')
 
 return "check your logs\n"

以上这篇使用Python & Flask 实现RESTful Web API的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python3基础之基本运算符概述
Aug 13 Python
Python中列表list以及list与数组array的相互转换实现方法
Sep 22 Python
Python实现监控Nginx配置文件的不同并发送邮件报警功能示例
Feb 26 Python
django模板加载静态文件的方法步骤
Mar 01 Python
Python 虚拟空间的使用代码详解
Jun 10 Python
Python绘制热力图示例
Sep 27 Python
Python读取VOC中的xml目标框实例
Mar 10 Python
python 在右键菜单中加入复制目标文件的有效存放路径(单斜杠或者双反斜杠)
Apr 08 Python
Python实现删除某列中含有空值的行的示例代码
Jul 20 Python
如何利用Python动态模拟太阳系运转
Sep 04 Python
Python Pandas常用函数方法总结
Jun 15 Python
python index() 与 rindex() 方法的使用示例详解
Dec 24 Python
python基本语法练习实例
Sep 19 #Python
基于python3 类的属性、方法、封装、继承实例讲解
Sep 19 #Python
浅谈python中列表、字符串、字典的常用操作
Sep 19 #Python
Python 文件操作的详解及实例
Sep 18 #Python
python Socket之客户端和服务端握手详解
Sep 18 #Python
Python基于time模块求程序运行时间的方法
Sep 18 #Python
Python使用当前时间、随机数产生一个唯一数字的方法
Sep 18 #Python
You might like
常用的PHP数据库操作方法(MYSQL版)
2011/06/08 PHP
php定时计划任务的实现方法详解
2013/06/06 PHP
php的socket编程详解
2016/11/20 PHP
PHP使用mysqli操作MySQL数据库的简单方法
2017/02/04 PHP
Yii2框架自定义类统一处理url操作示例
2019/05/25 PHP
PHP代码覆盖率统计详解
2020/07/22 PHP
javascript中的undefined 与 null 的区别  补充篇
2010/03/17 Javascript
使用jquery局部刷新(jquery.load)从数据库取出数据
2014/01/22 Javascript
详解JavaScript中undefined与null的区别
2014/03/29 Javascript
jQuery实现简单的间隔向上滚动效果
2015/03/09 Javascript
jQuery实现仿微软首页感应鼠标变化滑动窗口效果
2015/10/08 Javascript
详解webpack+vue-cli项目打包技巧
2017/06/17 Javascript
JS基于递归实现网页版计算器的方法分析
2017/12/20 Javascript
高性能的javascript之加载顺序与执行原理篇
2018/01/14 Javascript
Vue组件之自定义事件的功能图解
2018/02/01 Javascript
vue实现一拉到底的滑动验证
2019/07/25 Javascript
解决layer.confirm快速点击会重复触发事件的问题
2019/09/23 Javascript
python中的多重继承实例讲解
2014/09/28 Python
python实现分析apache和nginx日志文件并输出访客ip列表的方法
2015/04/04 Python
python+selenium开发环境搭建图文教程
2017/08/11 Python
Python实现的本地文件搜索功能示例【测试可用】
2018/05/30 Python
浅谈Python traceback的优雅处理
2018/08/31 Python
浅析python的Lambda表达式
2019/02/27 Python
python opencv将图片转为灰度图的方法示例
2019/07/31 Python
用canvas实现图片滤镜效果附演示
2013/11/05 HTML / CSS
味多美官网:蛋糕订购,100%使用天然奶油
2017/11/10 全球购物
德国拖鞋网站:German Slippers
2019/11/08 全球购物
纯净、自信、100%的羊绒服装:360Cashmere
2021/02/20 全球购物
副总经理工作职责
2013/11/28 职场文书
后勤人员岗位职责
2013/12/17 职场文书
个人职业生涯规划书1500字
2013/12/31 职场文书
单位提档介绍信
2014/01/17 职场文书
捐款倡议书
2014/04/14 职场文书
2014法制宣传日活动总结范文
2014/11/01 职场文书
人事专员岗位职责
2015/02/03 职场文书
教师听课学习心得体会
2016/01/15 职场文书