环境安装:

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. Java连接数据库的4中方式详解

    Java连接数据库的方式有多种:根据所需要的不同数据库驱动分,分为四种: 1:1类驱动.这就是JDBC-ODBC桥的方式. 但这种方式不适合程序的重用与维护,不推荐使用.需要数据库的ODBC驱动. 2 ...

  2. ABP从入门到精通(5):使用基于JWT标准的Token访问WebApi

    项目:asp.net zero 4.2.0 .net core(1.1) 版本 我们做项目的时候可能会遇到需要提供api给app调用,ABP动态生成的WebApi提供了方便的基于JWT标准的Token ...

  3. 文本排序的王者:玩透sort命令

    本文目录: 1.1 选项说明 1.2 sort示例 1.3 深入研究sort sort是排序工具,它完美贯彻了Unix哲学:"只做一件事,并做到完美".它的排序功能极强.极完整,只 ...

  4. Hibernate级联操作解密(inverse和cascade)

    总结: Cascade:对级联操作进行限制,有如下几个参数: all : 所有情况下均进行关联操作.  none:所有情况下均不进行关联操作.这是默认值.  save-update:在执行save/u ...

  5. 总结找到后台路径的N总思路方法

    1, 穷举猜解      现如今可以暴力猜解网站后台登陆地址的软件有很多,从最早的啊D注入工具开始,一直到现在很多常用的工具(通常为SQL注入利用工具)都会带有后台登陆地址猜解的功能. 当然了,这个猜 ...

  6. LaTeX的图片插入及排版

    LaTeX中一般只直接支持插入eps(Encapsulated PostScript)格式的图形文件, 因此在图片插入latex文档之前应先设法得到图片的eps格式的文件. UNIX下的各种应用软件都 ...

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

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

  8. C++ operator bool

    雕虫小技: #include <iostream> struct A{ operator bool(){ return false; } }; int main() { A a{}; if ...

  9. 从源码分析java.lang.String.isEmpty()

    今天在写代码的时候用到了java.lang.String.isEmpty()的这个方法,之前也用过,今天突发奇想,就看了看源码,了解了解它的实现方法,总结出来,大家可以交流交流. 通常情况下,我们使用 ...

  10. [js高手之路]深入浅出webpack教程系列7-( babel-loader,css-loader,style-loader)的用法

    什么是loader呢,官方解释为文件的预处理器,通俗点说webpack在处理静态资源的时候,需要加载各种loader,比如,html文件,要用html-loader, css文件要用css-loade ...