Flask Restful Small Demo,flaskrestful

來源:互聯網
上載者:User

Flask Restful Small Demo,flaskrestful

參考:

http://www.pythondoc.com/flask-restful/first.html

什麼是Rest

  • Client-Server:伺服器端與用戶端分離。
  • Stateless(無狀態):每次用戶端請求必需包含完整的資訊,換句話說,每一次請求都是獨立的。
  • Cacheable(可緩衝):伺服器端必需指定哪些請求是可以緩衝的。
  • Layered System(分層結構):伺服器端與用戶端通訊必需標準化,伺服器的變更並不會影響用戶端。
  • Uniform Interface(統一介面):用戶端與伺服器端的通訊方法必需是統一的。
  • Code on demand(按需執行代碼?):伺服器端可以在上下文中執行代碼或者指令碼?
 
GET 
擷取資源的資訊
POST
建立新資源  
PUT 
更新資源
DELETE
刪除資源 

那麼先用flask 建立一個小小的Demo,假使你已經安裝了flask   window –cmd- pip install flask

from flask import Flaskapp=Flask(__name__)@app.route("/")def index():    return "hello everybody"    if __name__=='__main__':    app.run(debug=True)

在CMD命令中輸入  python test1.py

會彈出 http://127.0.0.1:5000 。在瀏覽器中輸入即可,這是一個簡單的flask  應用就訪問成功。

先用flask 建立一個小服務,首先是get方法擷取

這裡的資料庫暫時不用,直接用Python的列表就行資料的增刪改查

GET查詢

# -*- coding: utf-8 -*-from flask import Flask,jsonifyapp=Flask(__name__)persons=[{'id':1,'name':'張三','address':'河南省'},{'id':2,'name':'李斯','address':'湖北省'}]@app.route('/api/list/personss',methods=['GET'])def Get_tasks():    results=jsonify({'person':persons})    return results    if __name__=='__main__':    app.run(debug=True)

稍微用了一個JSON序列化

通過ID擷取某一列資料

# -*- coding: utf-8 -*-from flask import Flask,jsonifyapp=Flask(__name__)@app.route('/api/list/person/<int:ids>',methods=['get'])def get_tasks_id(ids):    return 'st'if __name__=='__main__':    app.run(debug=True)

再通過POST方法進行提交資料

from flask import request@app.route('/todo/api/v1.0/tasks', methods=['POST'])def create_task():    if not request.json or not 'title' in request.json:        abort(400)    task = {        'id': tasks[-1]['id'] + 1,        'title': request.json['title'],        'description': request.json.get('description', ""),        'done': False    }    tasks.append(task)    return jsonify({'task': task}), 201

然後我卻使用了 Flask 的視圖函數來定義所有的路由。當然這也行,但是總感覺不是 那麼一回事。

Resource 基礎類是flask提供的。

好累。再敘。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.