七、python restful框架(python接口開發)


理解

  • 1.每一個URL代表一種資源
  • 2.客戶端和服務端之間,傳遞這種資源的某種表現層,客戶端通過四個HTTP動詞
  • 對服務端資源進行操作,實現“表現層狀態轉化”
  • 資源:網絡的具體信息,如圖片、文字等
  • 表現層:"資源"是一種信息實體,它可以有多種外在表現形式。我們把"資源"具體呈現出來的形式,如,文本可以用txt格式表現,也可以用HTML格式、XML格式、JSON格式表現
  • 狀態轉化:訪問一個網站,就代表了客戶端和服務器的一個互動過程。在這個過程中,勢必涉及到數據和狀態的變化。
  • 4個HTTP動詞:GET用來獲取資源,POST用來新建資源(也可以用於更新資源),PUT用來更新資源,DELETE用來刪除資源。

安裝 flask restful

  • 1.cmd輸入:pip install flask,安裝flask
  • 2.cmd輸入:pip install flask-restful,安裝flask-restful

安裝過程中會出現如下報錯:

You are using pip version 9.0.1, however version 19.2.3 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' comm
and.

解決方法

升級pip python -m pip install --upgrade pip
注意:某些Flask版本下,引入模塊時采用from flask.ext.restful import Api出錯,則可以使用from flask_restful import Api

官網教程

例證

restful.py 內容:

#!/usr/bin/python3
# encoding:utf-8
from flask import Flask,request
from flask_restful import reqparse, abort, Api, Resource

#初始化app、api
app = Flask(__name__)
api = Api(app)

LISTS = [
    {'parameter': '首頁'},
    {'parameter': '登錄'},
    {'parameter': '后台'}
]

# /LISTS/<list_id>(url參數),判斷輸入的參數值列表LISTS下標越界,越界則退出
def abort_if_list_doesnt_exist(list_id):
    try:
        LISTS[list_id]
    except IndexError:
        abort(404, message="輸入的值,不在范圍內")
'''
add_argument('per_page', type=int, location='args') str
add_argument中通過指定參數名、參數類型、參數獲取方式來獲取參數對象並支持做合法性校驗
第一個參數是需要獲取的參數的名稱
參數type: 參數指的類型, 如果參數中可能包含中文需要使用six.text_type. 或直接不指定type
參數location: 獲取參數的方式,可選的有args(url中獲取)、json(json類型的)、form(表單方式提交)
參數required:是否必要,默認非必要提供  required=True(必須)
參數help:針對必要的參數,如果請求時沒有提供,則會返回help中相應的信息
'''
parser = reqparse.RequestParser()
#入參parameter,location='json'表示為入參為json格式
parser.add_argument('parameter',location='json')

# 路由類,函數get、post、put、delete等實現http請求方法
# url不帶入參  /LISTS
class c_dictList(Resource):
    #類型get,根據列表LISTS,處理,返回一個新的列表r_lists
    def get(self):
        r_lists = []
        for listV in LISTS:
            if listV:
                new_list = {}
                #LISTS列表存的是字典,遍歷時為字典listV['parameter'],可獲取字典值
                new_list['parameter'] = listV['parameter']
                #LISTS為列表,index可以查出對應下標值
                new_list['url'] = 'url/'+ str(LISTS.index(listV))
                #LISTS列表中添加字典
                r_lists.append(new_list)
        return r_lists
        
    #類型post,在列表LISTS后添加一個值,並返回列表值
    def post(self):
        args = parser.parse_args()
        list_id = len(LISTS)
        #args['parameter'],入參
        LISTS.append({'parameter': args['parameter']}) 
        return LISTS, 201
    
# 路由類,函數get、post、put、delete等實現http請求方法
# url帶入參  /LISTS/<list_id>
class c_dict(Resource):
    #根據輸入url入參值作為LISTS的下標,返回該值
    def get(self, list_id):
        url_int = int(list_id)
        abort_if_list_doesnt_exist(url_int)
        return LISTS[url_int]
    #根據輸入url入參值作為LISTS的下標,修改該值,並返回列表值
    def put(self, list_id):
        url_int = int(list_id)
        args = parser.parse_args()
        #args['parameter'],入參
        parameter = {'parameter': args['parameter']}
        LISTS[url_int] = parameter
        return LISTS, 201
    #根據輸入url入參值作為LISTS的下標,刪除該值
    def delete(self, list_id):
        url_int = int(list_id)
        abort_if_list_doesnt_exist(url_int)
        del LISTS[url_int]
        return '', 204
#設置資源路由api.add_resource(類名,url路徑)
#url,不帶入參,如:http://127.0.0.1:8891/LISTS
api.add_resource(c_dictList, '/LISTS')
#url,帶入參,<list_id>為變量值,如:http://127.0.0.1:8891/LISTS/1
api.add_resource(c_dict, '/LISTS/<list_id>')

if __name__ == '__main__':
    #不設置ip、端口,默認:http://127.0.0.1:5000/
    #app.run(debug=True)
    #設置ip、端口
    app.run(host="127.0.0.1", port=8891,debug=True)

控制台運行結果:

  • Serving Flask app "123" (lazy loading) * Environment: production
    WARNING: This is a development server. Do not use it in a production
    deployment. Use a production WSGI server instead. * Debug mode: on
  • Restarting with stat * Debugger is active! * Debugger PIN: 279-443-943 * Running on http://127.0.0.1:8891/ (Press CTRL+C to
    quit)

postman調用結果

url不帶參數
get

在這里插入圖片描述

post,有請求入參,格式為json,入參值追加到列表后面

在這里插入圖片描述

url帶參數
get,根據url入參值如下圖值=1,作為LISTS的下標,獲取列表值

在這里插入圖片描述

put ,根據url入參值如下圖值=1,作為LISTS的下標,修改該列表值為請求入參值,登錄改為訂單

在這里插入圖片描述

put ,根據url入參值如下圖值=2,作為LISTS的下標,刪除該值,成功返回狀態204

在這里插入圖片描述


免責聲明!

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



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