Flask Restful Small Demo, flaskrestful
Refer:
Http://www.pythondoc.com/flask-restful/first.html
What is Rest?
- Client-Server: Separate the Server from the Client.
- Stateless (Stateless): each client request must contain complete information. In other words, each request is independent.
- Cacheable: the server must specify which requests can be cached.
- Layered System: the communication between the server and the client must be standardized. Server changes do not affect the client.
- Uniform Interface (unified Interface): the communication methods between the client and the server must be unified.
- Code on demand (on-demand Code execution ?) : Can the server execute code or script in the context?
GET |
Obtain Resource Information |
POST |
Create a new resource |
PUT |
Update Resources |
DELETE |
Delete Resource |
Use flask to create a small Demo. If you have installed 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)
Enter python test1.py In the CMD command
Http: // 127.0.0.1: 5000 is displayed. Enter it in the browser. This is a simple flask application and the access is successful.
Use flask to create a small service. First, get the get method.
The database here is not used for the time being. You can use the Python list to add, delete, modify, and query data.
GET Query
#-*-Coding: UTF-8-*-from flask import Flask, jsonifyapp = Flask (_ name _) persons = [{'id': 1, 'name ': 'zhang san', 'address': 'henan province '}, {'id': 2, 'name': 'lis', 'address': 'hubei province'}] @ app. route ('/api/list/personss', methods = ['get']) def Get_tasks (): results = jsonify ({'person': persons }) return results if _ name __= = '_ main _': app. run (debug = True)
A json serialization is slightly used.
Obtain a column of data by 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)
Submit data using the POST method
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
Then I used the Flask view function to define all the routes. Of course this works, but it doesn't always feel like that.
The Resource base class is provided by flask.
Tired. Repeat.