使用 flask 實現 RESTful API


首先,安裝flask 

pip install flask

假設那你已經了解RESTful API的相關概念,如果不清楚,可以參考這篇博客Designing a RESTful Web API.

flask是一個使用Python開發的基於Werkzeug的Web框架。
flask非常適合於開發RESTful API,因為它具有以下特點:

  • 使用Python進行開發,Python簡潔易懂
  • 容易上手
  • 靈活
  • 可以部署到不同的環境
  • 支持RESTful請求分發

我一般是用curl命令進行測試,除此之外,還可以使用Chrome瀏覽器的postman擴展。

資源

首先,創建一個完整的應用,支持響應/, /articles以及/article/:id。

響應結果分別如下所示:

GET /
Welcome
 
GET /articles
List of /articles
 
GET /articles/123
You are reading 123

 路由中還可以使用類型定義:

@app.route('/articles/<articleid>')

上面的路由可以替換成下面的例子:

@app.route('/articles/<int:articleid>')
@app.route('/articles/<float:articleid>')
@app.route('/articles/<path:articleid>')

默認的類型為字符串。

請求REQUESTS

請求參數

假設需要響應一個/hello請求,使用get方法,並傳遞參數name

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

請求方法

flask支持不同的請求方法:

@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"

可以使用如下命令進行測試:

curl -X PATCH http://127.0.0.1:5000/echo

不同請求方法的響應如下:

GET /echo
ECHO: GET
 
POST /ECHO
ECHO: POST
...

請求數據和請求頭

通常使用POST方法和PATCH方法的時候,都會發送附加的數據,這些數據的格式可能如下:普通文本(plain text), JSON,XML,二進制文件或者用戶自定義格式。
Flask中使用request.headers類字典對象來獲取請求頭信息,使用request.data獲取請求數據,如果發送類型是application/json,則可以使用request.get_json()來獲取JSON數據。

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 ;)"

使用如下命令指定請求數據類型進行測試:

curl -H "Content-type: application/json" \
-X POST http://127.0.0.1:5000/messages -d '{"message":"Hello Data"}'

使用下面的curl命令來發送一個文件:

curl -H "Content-type: application/octet-stream" \
-X POST http://127.0.0.1:5000/messages --data-binary @message.bin

不同數據類型的響應結果如下所示:

POST /messages {"message": "Hello Data"}
Content-type: application/json
JSON Message: {"message": "Hello Data"}
 
POST /message <message.bin>
Content-type: application/octet-stream
Binary message written!

 

注意flask可以通過request.files獲取上傳的文件,curl可以使用-F選項模擬上傳文件的過程。

響應RESPONSES

flask使用Response類處理響應。

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

使用-i選項可以獲取響應信息:

curl -i http://127.0.0.1:5000/hello

返回的響應信息如下所示:

GET /hello
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 31
Link: http://luisrei.com
Server: Werkzeug/0.8.2 Python/2.7.1
Date: Wed, 25 Apr 2012 16:40:27 GMT
{"hello": "world", "number": 3}

mimetype指定了響應數據的類型。

上面的過程可以使用Flask提供的一個簡便方法實現:

from flask import jsonify
...
# 將下面的代碼替換成
resp = Response(js, status=200, mimetype='application/json')
# 這里的代碼
resp = jsonify(data)
resp.status_code = 200

狀態碼和錯誤處理

如果成功響應的話,狀態碼為200。對於404錯誤我們可以這樣處理:

@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()

測試上面的兩個URL,結果如下:

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"
}

默認的Flask錯誤處理可以使用@error_handler修飾器進行覆蓋或者使用下面的方法:

app.error_handler_spec[None][404] = not_found

即使API不需要自定義錯誤信息,最好還是像上面這樣做,因為flask默認返回的錯誤信息是HTML格式的。

認證

使用下面的代碼可以處理 HTTP Basic Authentication。

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

 

接下來只需要給路由增加@require_auth修飾器就可以在請求之前進行認證了:

@app.route('/secrets')
@requires_auth
def api_hello():
    return "Shhh this is top secret spy stuff!"

現在,如果沒有通過認證的話,響應如下所示:

GET /secrets
HTTP/1.0 401 UNAUTHORIZED
WWW-Authenticate: Basic realm="Example"
{
  "message": "Authenticate."
}

curl通過-u選項來指定HTTP basic authentication,使用-v選項打印請求頭:

curl -v -u "admin:secret" http://127.0.0.1:5000/secrets

響應結果如下:

GET /secrets Authorization: Basic YWRtaW46c2VjcmV0
Shhh this is top secret spy stuff!

flask使用MultiDict來存儲頭部信息,為了給客戶端展示不同的認證機制,可以給header添加更多的WWW-Autheticate。

通過設置debug=True來開啟調試信息:

app.run(debug=True)

使用Python的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"

CURL 命令參考

 

選項 作用
-X 指定HTTP請求方法,如POST,GET
-H 指定請求頭,例如Content-type:application/json
-d 指定請求數據
–data-binary 指定發送的文件
-i 顯示響應頭部信息
-u 指定認證用戶名與密碼
-v 輸出請求頭部信息


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM