1. 程式人生 > 程式設計 >Python restful框架介面開發實現

Python restful框架介面開發實現

理解

  • 每一個URL代表一種資源
  • 客戶端和服務端之間,傳遞這種資源的某種表現層,客戶端通過四個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 productiondeployment. Use a production WSGI server instead. * Debug mode: onRestarting with stat * Debugger is active! * Debugger PIN: 279-443-943 * Running on http://127.0.0.1:8891/ (Press CTRL+C toquit)

postman呼叫結果

url不帶引數

get

Python restful框架介面開發實現

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

Python restful框架介面開發實現

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

Python restful框架介面開發實現

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

Python restful框架介面開發實現

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

Python restful框架介面開發實現

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。