环境安装:

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 = {'':'john', '':'steve', '':'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"

参考:

Flask documentation

Flask snippets

Werkzeug documentation

curl manual

使用 Python & Flask 实现 RESTful Web API的更多相关文章

  1. 我所理解的RESTful Web API [Web标准篇]

    REST不是一个标准,而是一种软件应用架构风格.基于SOAP的Web服务采用RPC架构,如果说RPC是一种面向操作的架构风格,而REST则是一种面向资源的架构风格.REST是目前业界更为推崇的构建新一 ...

  2. 我所理解的RESTful Web API [设计篇]

    <我所理解的RESTful Web API [Web标准篇]>Web服务已经成为了异质系统之间的互联与集成的主要手段,在过去一段不短的时间里,Web服务几乎清一水地采用SOAP来构建.构建 ...

  3. 对RESTful Web API的理解与设计思路

    距离上一篇关于Web API的文章(如何实现RESTful Web API的身份验证)有好些时间了,在那篇文章中提到的方法是非常简单而有效的,我在实际的项目中就这么用了,代码经过一段时间的磨合,已经很 ...

  4. About Restful Web Api Something.

    这种轻量级的服务架构目前来说还是比较流行的,比如微信的公众平台的接口开发就是一个很好的案例,提到restful那么他到底是一个什么样的东西? REST(Representational State T ...

  5. 【ASP.NET MVC 学习笔记】- 19 REST和RESTful Web API

    本文参考:http://www.cnblogs.com/willick/p/3441432.html 1.目前使用Web服务的三种主流的方式是:远程过程调用(RPC),面向服务架构(SOA)以及表征性 ...

  6. RESTful Web API 理解

    REST 是一种应用架构风格,不是一种标准,是面向资源架构(ROA)风格,与具体技术平台无关,REST架构的应用未必建立在Web之上,与之对应的是传统的Web Service 采用的面向操作的RPC架 ...

  7. 个人学期总结及Python+Flask+MysqL的web建设技术过程

    一个学期即将过去,我们也迎来了2018年.这个学期,首次接触了web网站开发建设,不仅是这门课程,还有另外一门用idea的gradle框架来制作网页. 很显然,用python语言的flask框架更加简 ...

  8. RESTful Web API 实践

    REST 概念来源 网络应用程序,分为前端和后端两个部分.当前的发展趋势,就是前端设备层出不穷(手机.平板.桌面电脑.其他专用设备...). 因此,必须有一种统一的机制,方便不同的前端设备与后端进行通 ...

  9. Python+Flask+MysqL的web建设技术过程

    一.前言(个人学期总结) 个人总结一下这学期对于Python+Flask+MysqL的web建设技术过程的学习体会,Flask小辣椒框架相对于其他框架而言,更加稳定,不会有莫名其妙的错误,容错性强,运 ...

随机推荐

  1. Relationship between frequency domain and spatial domain in digital images

    今天又复习了一遍<<Digital Image Processing>>的第四章,为了加深对频域的理解,我自己用PS画了一张图.如下: 然后做FFT,得到频谱图如下: 从左到右 ...

  2. Mac配置eclipse+pydev+Python遇到的问题

    最近在研究Python,作为一名新手在配置环境的时候遇到各种问题:高手可略过~ 1.eclipse官网上下载最新的OS版本,并成功安装eclipse 2.安装JDK,eclipse这些都是要安装JDK ...

  3. STL简单的介绍

    我们要知道C++的含义:C语言 + 类 + 模板  (STL就是典型的代表) STL是Standard Template Library的简称,中文名是标准模库.从根本上说,STL是一些“容器”的集合 ...

  4. random模块函数分析(一)

    random是python产生伪随机数的模块,随机种子默认为系统时钟.下面分析模块中的方法: 1.random.randint(start,stop): 这是一个产生整数随机数的函数,参数start代 ...

  5. Ubuntu16.04+CUDA8.0+CUNN5.1+caffe+tensorflow+Theano

    title: Ubuntu 16.04+CUDA8.0+CUNN5.1+caffe+tensorflow+Theano categories: 深度学习 tags: [深度学习框架搭建] --- 前言 ...

  6. oracle字段由中文前缀加数字,数字自动增长的实现

    table中有一个字段,id,它是由Yunsha_000001的规则组成的. 每当插入一条数据的时候,自动生成的id是自动增加的,如何实现数字部分的自动增长? select  'Yunsha_'||l ...

  7. C++栈和堆的生长方向

    C++内存区域分为5个区域.分别是堆,栈,自由存储区,全局/静态存储区和常量存储区. 栈:由编译器在需要的时候分配,在不需要的时候自动清除的变量存储区.里面通常是局部变量,函数参数等. 堆:由new分 ...

  8. linux中文件I/O操作(系统I/O)

    我们都知道linux下所有设备都是以文件存在的,所以当我们需要用到这些设备的时候,首先就需要打开它们,下面我们来详细了解一下文件I/O操作. 用到的文件I/O有以下几个操作:打开文件.读文件.写文件. ...

  9. 车牌识别OCR—易泊时代智慧城市解决方案模块

    牌识别(License Plate Recognition,LPR) 是视频图像识别技术在智能交通领域中的一个模块.车牌识别运用OCR技术,将视频流或图片中的汽车牌照从复杂的应用场景中提取并识别出来, ...

  10. 一、Nginx安装手册

    1 nginx安装环境 nginx是C语言开发,建议在linux上运行,本教程使用Centos6.5作为安装环境. gcc 安装nginx需要先将官网下载的源码进行编译,编译依赖gcc环境,如果没有g ...