使用python web做Restful 風格,很簡單,採用Flask框架輕鬆實現一個RESTful的服務。 Restful相關介紹請查看:https://www.ibm.com/developerworks/library/ws-restful/index.html 1. 環境搭建 首先需要準備環 ...
使用python web做Restful 風格,很簡單,採用Flask框架輕鬆實現一個RESTful的服務。
Restful相關介紹請查看:https://www.ibm.com/developerworks/library/ws-restful/index.html
1. 環境搭建
首先需要準備環境
need virtualenv python的沙盒環境--virtualenv
這裡使用 virtualenv 來創建一個Python環境,用來運行我們稍後的restful服務端。
need flask
1.1 安裝
1.1.1 pip
下載地址:https://pypi.python.org/pypi/pip/
下載 pip tar.gz
解壓 tar -xzvf
進入目錄安裝 python setup.py install 即可使用
1.1.2 virtualenv
pip install virtualenv 直接下載安裝
或者 進入 https://pypi.python.org/pypi/virtualenv 下載 tar包 和pip安裝類似
1.1.3 flask
pip install flask 直接下載安裝
或者 https://pypi.python.org/pypi/Flask/0.12.2#downloads 下載tar包 解壓安裝
手動裝需要(install會自動安裝,如果linux虛擬機未聯網,根據提示缺什麼,去安裝什麼):
click >=2.0:https://pypi.python.org/simple/click/
itsdangerous >=0.21:https://pypi.python.org/simple/itsdangerous/
jinja2 >= 2.4:https://pypi.python.org/simple/jinja2/
werkzeug>=0.7:https://pypi.python.org/simple/werkzeug/
2. 環境測試
2.1 創建虛擬環境
選擇一個合適的路徑下
我選擇的是 /var/flask 當然可以隨意選擇一個目錄
virtualenv web ,做一個名為web的python環境
目錄如:
2.2 新建app.py
在bin中新建app.py
app.route 的用法和Springmvc 的controller requestmapping很類似,詳細請查看:http://www.guadong.net/article/2eHheDFm.html
#環境測試 from flask import Flask app = Flask(__name__) @app.route('/') def index(): return "Hello, Python Flask!" if __name__ == '__main__': app.run(debug=True)
2.3 執行訪問
執行 python app.py
本地訪問(可以新開一個ssh進行測試,也可以用IP地址 用瀏覽器測試)
這裡採用linux內部訪問:curl -i http://localhost:5000
訪問得到了Hello, Python Flask!
說明環境搭建成功success!。
3. 正式幹活
這裡還是使用Person對象來做Restful的演示,參考:SpringMVC 構建Restful風格 及問題處理
/persons GET 得所有person
/person/{id} GET 得到id的person
/person POST 新增person
/person/{id} PUT 更新id的person
/person/{id} DELETE 刪除id的person
新建person.py
編碼:
#coding=utf-8
引入需要的模塊:
from flask import Flask,jsonify,abort,make_response,request
模擬資料庫數據:
#模擬資料庫 person 屬性 id name age done url persons = [ { 'id': 1, 'name': u'loveincode', 'age': 20, 'done': False, 'url':u'loveincode.cnblogs.com' }, { 'id': 2, 'name': u'strive', 'age': 18, 'done': False, 'url':u'loveincode.cnblogs.com' } ]
3.1 GET persons
代碼設計:
@app.route('/restful/persons', methods=['GET']) def get_persons(): return jsonify({'persons': persons})
先執行:python person.py
test:curl -i http://localhost:5000/restful/persons
3.2 GET person
@app.route('/restful/person/<int:id>', methods=['GET']) def get_person(id): person = filter(lambda t: t['id'] == id, persons) if len(person) == 0: abort(404) return jsonify({'person': person[0]})
先執行:python person.py
test:curl -i http://localhost:5000/restful/person/2
錯誤404 後面一起講。
3.3 POST
@app.route('/restful/person', methods=['POST']) def create_person(): if not request.json or not 'name' in request.json: abort(400) person = { 'id': persons[-1]['id'] + 1, 'name': request.json['name'], #如果沒有提交age參數預設為20 'age': request.json.get('age', 20), #同理如果沒提交url,url也是預設值 'url': request.json.get('url', "預設URL loveincode.cnblogs.com"), #該參數初始化FALSE 'done': False } persons.append(person) return jsonify({'person': person}), 201
先執行:python person.py
test:提供三個測試
curl -i -H "Content-Type: application/json" -X POST -d '{"name":"new loveincode"}' http://localhost:5000/restful/person
curl -i -H "Content-Type: application/json" -X POST -d '{"name":"new loveincode","age":23}' http://localhost:5000/restful/person
curl -i -H "Content-Type: application/json" -X POST -d '{"name":"new loveincode","age":23,"url":"1234"}' http://localhost:5000/restful/person
驗證最後一個 ,先post 再看所有 添加成功
3.4 PUT
@app.route('/restful/person/<int:id>', methods=['PUT']) def update_person(id): person = filter(lambda t: t['id'] == id, persons) if len(person) == 0: abort(404) if not request.json: abort(400) if 'name' in request.json and type(request.json['name']) != unicode: abort(400) if 'age' in request.json and type(request.json['age']) is not int: abort(400) if 'url' in request.json and type(request.json['url']) != unicode: abort(400) if 'done' in request.json and type(request.json['done']) is not bool: abort(400) person[0]['name'] = request.json.get('name', person[0]['name']) person[0]['age'] = request.json.get('age', person[0]['age']) person[0]['url'] = request.json.get('url', person[0]['url']) person[0]['done'] = request.json.get('done', person[0]['done']) return jsonify({'person': person[0]})
先執行:python person.py
test:
curl -i -H "Content-Type: application/json" -X PUT -d '{"done":true}' http://localhost:5000/restful/person/2
curl -i -H "Content-Type: application/json" -X PUT -d '{"name":"update","age":30}' http://localhost:5000/restful/person/2
3.5 DELETE
@app.route('/restful/person/<int:id>', methods=['DELETE']) def delete_person(id): person = filter(lambda t: t['id'] == id, persons) if len(person) == 0: abort(404) persons.remove(person[0]) return jsonify({'result': True})
先執行:python person.py
test:
curl -i -X DELETE http://localhost:5000/restful/person/2
3.6 Error 處理
對400 和 404 進行錯誤json封裝,一個友好的錯誤提示
@app.errorhandler(404) def not_found(error): return make_response(jsonify({'error': 'Not found'}), 404) @app.errorhandler(400) def not_found(error): return make_response(jsonify({'error': 'Request Error'}), 400)
github地址:https://github.com/loveincode/python-restful-web
參考:http://www.cnblogs.com/vovlie/p/4178077.html