1. 程式人生 > >使用 Python & Flask 實現 RESTful Web API

使用 Python & Flask 實現 RESTful Web API

環境安裝:

sudo pip install flask

Flask 是一個Python的微服務的框架,基於Werkzeug, 一個 WSGI 類庫。

Flask 優點:

  • Written in Python (that can be an advantage);
  • Simple to use;
  • Flexible;
  • 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

環境安裝: sudo pip install flask Flask 是一個Python的微服務的框架,基於Werkzeug, 一個 WSGI 類庫。 Flask 優點: Written in Python (that can be an advantage); Simple to use;

如何實現RESTful Web API的身份驗證

最近想拿一個小專案來試水RESTful Web API,專案只有幾個呼叫,比較簡單,但同樣需要身份驗證,如果是傳統的網站的話,那不用說,肯定是使用者名稱+密碼在登入頁獲得登入Token,並把登入Token記在Cookie和Session中作為身份標識的這種方式,但現在不同

使用靜態基類方案讓 ASP.NET Core 實現遵循 HATEOAS Restful Web API

以及 acc repo pri == single partially context 繼承 Hypermedia As The Engine Of Application State (HATEOAS) HATEOAS(Hypermedia as the engi

python+flask實現API

Flask 框架 #-*-coding:utf-8-*- #pip install flask #pip install flask-restful from flask import Flask app = Flask(__name__) @app.route('/') def i

python3版本的flask環境,使用PythonFlask實現restful服務

搭建py3版本的flask環境 錯誤做法 1. 在搭建py3的flask虛擬環境時,virtualenv --no-site-packages py3flask 報錯: virtualenv Impo

Python Django 實現restful API

最近在寫測試平臺,需要實現一個節點伺服器的api,正好在用django,準備使用djangorestframework外掛實現。 需求 實現一個介面,在呼叫時,通過傳遞的引數,直接執行對

zzWCF實現RESTFul Web Service

XML scl 新建 封裝 rest ole 字符串 factor esp http://www.cnblogs.com/KeithWang/archive/2012/02/14/2351826.html http://blog.csdn.net/qq_26054303/

Python+Flask+MysqL的web建設技術開發一個網站

用戶輸入 per IE 擴展 問題 _file__ 擁有 內容 根據 一、摘要 flask是一個很精簡,靈活的框架,對於web的開發非常的好,具有jinja2強大的模板引擎的支持。flask框架的一個擴展就是sqlalchemy, sqlalcheny是flask的一個擴展

沿用Python+Flask+Mysql的web建設技術開發網站

ref 默認 修改密碼 save esc 代碼 程序 興趣 switch 1 系統概要說明 1.1 開發目的 閑暇時光想看看電影?我要看些什麽好呢?百度推薦出來的爛片也不在其數,如果有一個真實反映影片的平臺該多好,這就是淘智寶的產生,為電影連續劇愛好人群提供一

RESTful Web API 理解

超時重傳 怎麽 get請求 希望 序號 訂單 order option rom   REST 是一種應用架構風格,不是一種標準,是面向資源架構(ROA)風格,與具體技術平臺無關,REST架構的應用未必建立在Web之上,與之對應的是傳統的Web Service 采用的面

我所理解的RESTful Web API [設計篇]

一個 nta 協議 cti 提交 李維 目前 web api 介紹 本文轉載自文章:我所理解的RESTful Web API [設計篇]。 其他參考文章有:RESTful 介紹 ppt,Restful的理解,Restful 優缺點,理解RESTful架構,RESTfu

RESTful Web API的理解與設計思路

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow 也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!        

使用apidoc 生成Restful web Api文件

在專案開發過程中,總會牽扯到介面文件的設計與編寫,之前使用的都是office工具,寫一個文件,總也是不夠漂亮和直觀。好在git上的開源大神提供了生成文件的工具,so來介紹一下! 該工具是Nodejs的模組,請務必在使用前安裝好nodejs環境! 工具名稱:apiDoc Git地址:http

如何基於 Python Flask 實現角色管理系統

基於 Python Flask Web 框架實現完整的角色管理系統,包含使用者管理、角色管理、機構管理、資源管理等。 本場 Chat 主要內容: 深度闡述使用者、角色、資源等之間的關係; Python 虛擬環境 VirtualEnv 介紹; Flask 框架的基本概念介紹; 基

通過Flask實現Restful服務

1,前言 Python的強大,已經涉及到軟體開發領域的方方面面。然而,Python入門容易,精確很難,需要深入研究。 在Web方面同樣如此,常用的Python Web框架,例如Django、Flask、Tornado等等,共計有100多種,各有優劣。本文以F

Restful Web Api Get 和 Post 請求的引數設定

1、Get請求(用HttpClient或HttpWebRequest) [HttpGet] public int Get(int id) { return id; }static void Main(s

介面文件自動生成、使用apidoc 生成Restful web Api文件(express)

專案地址為: 專案地址 這個是自動生成網頁,我們就可以擺脫excel。 一.首先是使用node安裝apiDoc npm install apidoc -g 二.在需要生成介面的添加註釋 /** * @api {post} /v1/login

python flask 簡單登陸web製作(下)

5.將前端資料傳至後端: 上一節我們完成了一個基本框架,這裡在複習下git,進入目錄滑鼠右鍵開啟git,輸入如下命名儲存、檢視。 然後我們繼續改進程式碼,修改main.py為 from flask import Flask,render_template #匯入render_tem

python flask 簡單登陸web製作(上)

剛學flask,感覺flask真的很簡潔。然後做了一個很低階的登陸頁面。就當一次小筆記,希望之後還可以補充。 1.配置環境: 首先要pip install flask配置好flask,然後我用的notepad++來編輯程式碼,用git來做版本控制。 2.基本程式碼: 然後在confi

我所理解的RESTful Web API [Web標準篇]

rtc 程序 bubuko -c 網絡資源 sci 轉換 ext led REST不是一個標準,而是一種軟件應用架構風格。基於SOAP的Web服務采用RPC架構,如果說RPC是一種面向操作的架構風格,而REST則是一種面向資源的架構風格。REST是目前業界更為推崇的構建新一