使用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 相关文章推荐
python操作gmail实例
Jan 14 Python
Python输出PowerPoint(ppt)文件中全部文字信息的方法
Apr 28 Python
Python的Flask框架应用程序实现使用QQ账号登录的方法
Jun 07 Python
Python实现SMTP发送邮件详细教程
Mar 02 Python
在java中如何定义一个抽象属性示例详解
Aug 18 Python
用Python shell简化开发
Aug 08 Python
Python多图片合并PDF的方法
Jan 03 Python
Python操作列表常用方法实例小结【创建、遍历、统计、切片等】
Oct 25 Python
如何在python开发工具PyCharm中搭建QtPy环境(教程详解)
Feb 04 Python
PyCharm刷新项目(文件)目录的实现
Feb 14 Python
python opencv角点检测连线功能的实现代码
Nov 24 Python
python 自定义异常和主动抛出异常(raise)的操作
Dec 11 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』PHP截断函数mb_substr()使用介绍
2013/04/22 PHP
php查找任何页面上的所有链接的方法
2013/12/03 PHP
PHP多线程编程之管道通信实例分析
2015/03/07 PHP
PHP+HTML+JavaScript+Css实现简单爬虫开发
2016/03/28 PHP
php求数组全排列,元素所有组合的方法
2016/05/05 PHP
PHP基于GD2函数库实现验证码功能示例
2019/01/27 PHP
Javascript开发包大全整理
2006/12/22 Javascript
用jQuery简化JavaScript开发分析
2009/02/19 Javascript
JS 的应用开发初探(mootools)
2009/12/19 Javascript
基于jquery的划词搜索实现(备忘)
2010/09/14 Javascript
jQuery时间插件jquery.clock.js用法实例(5个示例)
2016/01/14 Javascript
从零开始学习Node.js系列教程之基于connect和express框架的多页面实现数学运算示例
2017/04/13 Javascript
nodejs入门教程六:express模块用法示例
2017/04/24 NodeJs
Node.js如何使用Diffie-Hellman密钥交换算法详解
2017/09/05 Javascript
JS中移除非数字最多保留一位小数
2018/05/09 Javascript
浅谈Vue.js路由管理器 Vue Router
2018/08/16 Javascript
JS使用正则表达式实现常用的表单验证功能分析
2020/04/30 Javascript
vue中watch和computed的区别与使用方法
2020/08/23 Javascript
解决vue项目axios每次请求session不一致的问题
2020/10/24 Javascript
Python基于matplotlib绘制栈式直方图的方法示例
2017/08/09 Python
python中print()函数的“,”与java中System.out.print()函数中的“+”功能详解
2017/11/24 Python
Python AES加密实例解析
2018/01/18 Python
python使用Flask操作mysql实现登录功能
2018/05/14 Python
Python如何实现定时器功能
2020/05/28 Python
Python logging模块handlers用法详解
2020/08/14 Python
python中的插入排序的简单用法
2021/01/19 Python
专业幼师实习生自我鉴定范文
2013/12/08 职场文书
公司募捐倡议书
2014/05/14 职场文书
监察建议书格式
2014/05/19 职场文书
小学德育工作经验交流材料
2014/05/22 职场文书
民族学专业求职信
2014/07/28 职场文书
客房领班岗位职责
2015/02/11 职场文书
铁人纪念馆观后感
2015/06/16 职场文书
2016三八妇女节校园广播稿
2015/12/17 职场文书
导游词之潮音寺
2019/09/26 职场文书
SQL Server数据定义——模式与基本表操作
2021/04/05 SQL Server