使用Python & Flask 實(shí)現(xiàn)RESTful Web API的實(shí)例
環(huán)境安裝:
sudo pip install flask
Flask 是一個(gè)Python的微服務(wù)的框架,基于Werkzeug, 一個(gè) WSGI 類庫(kù)。
Flask 優(yōu)點(diǎn):
Written in Python (that can be an advantage);
Simple to use;
Flexible;
Multiple good deployment options;
RESTful request dispatching
RESOURCES
一個(gè)響應(yīng) /articles 和 /articles/:id的 API 服務(wù):
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()
請(qǐng)求:
curl http://127.0.0.1:5000/
響應(yīng):
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'
請(qǐng)求:
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"
請(qǐng)求指定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 ;)"
請(qǐng)求指定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
優(yōu)化代碼:
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()
請(qǐng)求:
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 實(shí)現(xiàn)RESTful Web API的實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- python模塊restful使用方法實(shí)例
- Python利用Django如何寫restful api接口詳解
- 在Python的框架中為MySQL實(shí)現(xiàn)restful接口的教程
- Python restful框架接口開發(fā)實(shí)現(xiàn)
- Python實(shí)現(xiàn)Restful API的例子
- Python中Flask-RESTful編寫API接口(小白入門)
- Python進(jìn)行Restful?API開發(fā)實(shí)例詳解
- python用post訪問restful服務(wù)接口的方法
- python Flask實(shí)現(xiàn)restful api service
- 探索?Python?Restful?接口測(cè)試的奧秘
相關(guān)文章
14個(gè)用Python實(shí)現(xiàn)的Excel常用操作總結(jié)
自從學(xué)了Python后就逼迫自己不用Excel,所有操作用Python實(shí)現(xiàn)。目的是鞏固Python,與增強(qiáng)數(shù)據(jù)處理能力。本文為大家總結(jié)了14個(gè)用Python實(shí)現(xiàn)的Excel常用操作,需要的可以參考一下2022-06-06python深度學(xué)習(xí)標(biāo)準(zhǔn)庫(kù)使用argparse調(diào)參
這篇文章主要為大家介紹了python深度學(xué)習(xí)標(biāo)準(zhǔn)庫(kù)使用argparse調(diào)參實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06Python自動(dòng)化辦公之生成PDF報(bào)告詳解
因?yàn)楣ぷ餍枰?jīng)常需要生成很多的PDF報(bào)告給客戶查看產(chǎn)品效果以及過程的講解,每次都需要按照一定的格式的編寫文檔并生成PDF報(bào)告,這樣重復(fù)性的工作實(shí)在太累。本文就來用Python實(shí)現(xiàn)自動(dòng)生成PDF報(bào)告吧2023-03-03探索Python函數(shù)調(diào)用為何加速代碼執(zhí)行原理
Python 作為一種解釋型語言,其執(zhí)行速度相對(duì)于編譯型語言可能會(huì)較慢,然而,在Python中,通常觀察到代碼在函數(shù)中運(yùn)行得更快的現(xiàn)象,這個(gè)現(xiàn)象主要是由于函數(shù)調(diào)用的內(nèi)部?jī)?yōu)化和解釋器的工作方式導(dǎo)致的,本文將深入探討這個(gè)現(xiàn)象,并通過詳細(xì)的示例代碼進(jìn)行解釋2024-01-01手把手教你pip配置國(guó)內(nèi)鏡像源(最新詳盡版)
pip是一個(gè)現(xiàn)代的,通用的Python包管理工具,提供了對(duì)Python包的查找、下載、安裝、卸載的功能,下面這篇文章主要給大家介紹了關(guān)于pip配置國(guó)內(nèi)鏡像源的相關(guān)資料,需要的朋友可以參考下2023-02-02python爬蟲的數(shù)據(jù)庫(kù)連接問題【推薦】
這篇文章主要介紹了python爬蟲的數(shù)據(jù)庫(kù)連接問題,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-06-06Python Pandas學(xué)習(xí)之?dāng)?shù)據(jù)離散化與合并詳解
Pandas是python的一個(gè)數(shù)據(jù)分析包,該工具是為解決數(shù)據(jù)分析任務(wù)而創(chuàng)建的。本文將通過示例詳細(xì)為大家介紹一下Pandas的數(shù)據(jù)離散化與合并,需要的可以參考一下2022-02-02