Python Flask implements restful api service and flaskrestful
Node. js is used as the backend and needs to be gradually involved in big data, so it is doomed to bypass python. Therefore, it is decided to rewrite some mature things with python. First, it is a pioneering idea to learn python through comparison; second, we have a goal and motivation, and hope to persevere.
Project Introduction
Use the python language to write a restful api service. The database uses mysql. The lightweight flask is selected as the web framework because only backend microservice is used and the ORM implementation method is used to automatically generate SQL. This choice aims to achieve a wide range of modern Internet applications targeting small and medium-sized network applications and leveraging the advantages of relational databases.
Six features of 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 ?) : The server can execute code or scripts in the context.
Restful api
The concept of restful api is not introduced. Here we will talk about the form of the Implementation Protocol:
[GET]/rs/user/{id}/key1/value1/key2/value2/.../keyn/valuen [POST]/rs/user[/{id}] [PUT]/rs/user/{id}[DELETE]/rs/user/{id}/key1/value1/key2/value2/.../keyn/valuen
Note:
- Rs indicates the resource ID;
- Section 2, user, will be resolved to the database table name;
- When the query id is null or 0, the id is ignored, that is, list query;
- Create and modify. Except for the form, the id parameters in the url are merged into the parameter set;
- Delete the same query.
Make flask support regular expressions
The default flask route does not support regular expressions, but I need to extract the complete URL for resolution. After query, it is easy to complete the task by following the steps below.
- Use the werkzeug Library: from werkzeug. routing import BaseConverter
- Definition converter:
class RegexConverter(BaseConverter): def __init__(self, map, *args): self.map = map self.regex = args[0]
- Register the converter: app. url_map.converters ['regex'] = RegexConverter
- Use regular expressions to intercept urls: @ app. route ('/rs/<regex (". * "): query_url> ', methods = ['put', 'delete', 'post', 'get'])
Several questions:
- In theory, regular expressions (. *) should match all characters except carriage return, but do not know why. question marks (?) are not recognized here (?)
- I use request. data to retrieve form data. Why can't request. form be obtained?
- '/Rs/<regex (". "): query_url> 'If a backslash ('/rs/<regex (". "): query_url>/'), request. data cannot be obtained. Why?
Parse json data
It is easy to parse json data, but I need to verify the data sent from the client. The following is a solution for parsing exceptions only once.
def check_json_format(raw_msg): try: js = json.loads(raw_msg, encoding='utf-8') except ValueError: return False, {} return True, js
URL Parsing
Parses the URL according to the established protocol, extracts the table name, and generates a set of SQL combination parameters.
@app.route('/rs/<regex(".*"):query_url>', methods=['PUT', 'DELETE', 'POST', 'GET'])def rs(query_url): (flag, params) = check_json_format(request.data) urls = query_url.split('/') url_len = len(urls) if url_len < 1 or url_len > 2 and url_len % 2 == 1: return "The params is wrong." ps = {} for i, al in enumerate(urls): if i == 0: table = al elif i == 1: idd = al elif i > 1 and i % 2 == 0: tmp = al else: ps[tmp] = al ps['table'] = table if url_len > 1: ps['id'] = idd if request.method == 'POST' or request.method == 'PUT': params = dict(params, **{'table': ps.get('table'), 'id': ps.get('id')}) if request.method == 'GET' or request.method == 'DELETE': params = ps return jsonify(params)
Complete code
git clone https://github.com/zhoutk/pyrest.gitcd restexport FLASK_APP=index.pyflask run
Summary
Today, flask is used to complete the web infrastructure. It can parse the URL correctly, extract the data submitted by the client, and combine the data we need based on different request methods. I hope it will be helpful for everyone's learning, and I hope you can support the house of helping customers more.