Deploying Restful web and pythonrestful in python
Using python web for Restful style is simple. Using the Flask framework, you can easily implement a RESTful service.
For more information about Restful, see: https://www.ibm.com/developerworks/library/ws-restful/index.html
1. Establish the environment
First, prepare the environment
NeedVirtualenvPython sandbox environment -- virtualenv
Here we use virtualenv to create a Python environment to run our restful server later.
NeedFlask
1.1 install 1.1.1 pip
: Https://pypi.python.org/pypi/pip/
Download pip tar.gz
Decompress tar-xzvf
Go to the directory to install python setup. py install.
1.1.2 virtualenv
Pip install virtualenv directly download and install
Or go to the https://pypi.python.org/pypi/virtualenv to download the tar package and pip install something similar
1.1.3 flask
Pip install flask directly download and install
Or download the tar package for https://pypi.python.org/pypi/Flask/0.12.2#downloads unzip Installation
Manual installation is required (install will be automatically installed. If the linux virtual machine is not connected to the Internet, follow the prompts to install what is missing ):
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. test environment 2.1 create a virtual environment
Select a proper path
I chose/var/flask. Of course, I can select a directory at will.
Virtualenv web is a python Environment named web
Directory:
2.2 create app. py
Create app. py in bin
The usage of app. route is similar to the controller requestmapping of Springmvc. For details, see: http://www.guadong.net/article/2eHheDFm.html
# Environment test from flask import Flaskapp = Flask (_ name _) @ app. route ('/') def index (): return "Hello, Python Flask! "If _ name _ = '_ main _': app. run (debug = True)
2.3 perform access
Run python app. py
Local access (you can open a new ssh for testing, or use a browser to test the IP address)
Linux internal access: curl-I http: // localhost: 5000
Hello, Python Flask!
The success environment is successfully set up !.
3. Formal work
Here we will use the Person object for Restful demonstration. For details, refer to SpringMVC to build a Restful style and solve problems.
/Persons GET all persons
/Person/{id} GET the person with the id
/Person POST add person
/Person/{id} PUT updates the person id
/Person/{id} DELETE the person of the id
Create person. py
Encoding:
#coding=utf-8
Introduce required modules:
from flask import Flask,jsonify,abort,make_response,request
Simulate database data:
# Simulate database person attribute id name age done urlpersons = [{'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
Code Design:
@app.route('/restful/persons', methods=['GET'])def get_persons(): return jsonify({'persons': persons})
Run python person. py first.
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]})
Run python person. py first.
Test: curl-I http: // localhost: 5000/restful/person/2
Error 404 will be discussed later.
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'], # If the age parameter is not submitted, the default value is 20 'age': request. json. get ('age', 20), # Similarly, if no url is submitted, the url is also the default value 'url': request. json. get ('url', "Default url loveincode.cnblogs.com"), # this parameter is initialized to FALSE 'done': False} persons. append (person) return jsonify ({'person ': person}), 201
Run python person. py first.
Test: provides three tests.
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
Verify the last one. First post and then view all added successfully.
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]})
Run python person. py first.
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})
Run python person. py first.
Test:
Curl-I-X DELETE http: // localhost: 5000/restful/person/2
3.6 Error handling
Json encapsulation of errors 400 and 404, a friendly error prompt
@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 address: https://github.com/loveincode/python-restful-web
Reference: http://www.cnblogs.com/vovlie/p/4178077.html