Python Flask implements restful api service and flaskrestful

Source: Internet
Author: User

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:

  1. Client-Server: Separate the Server from the Client.
  2. Stateless (Stateless): each client request must contain complete information. In other words, each request is independent.
  3. Cacheable: the server must specify which requests can be cached.
  4. Layered System: the communication between the server and the client must be standardized. Server changes do not affect the client.
  5. Uniform Interface (unified Interface): the communication methods between the client and the server must be unified.
  6. 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:

  1. Rs indicates the resource ID;
  2. Section 2, user, will be resolved to the database table name;
  3. When the query id is null or 0, the id is ignored, that is, list query;
  4. Create and modify. Except for the form, the id parameters in the url are merged into the parameter set;
  5. 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.

  1. Use the werkzeug Library: from werkzeug. routing import BaseConverter
  2. Definition converter:
class RegexConverter(BaseConverter):  def __init__(self, map, *args):    self.map = map    self.regex = args[0]
  1. Register the converter: app. url_map.converters ['regex'] = RegexConverter
  2. Use regular expressions to intercept urls: @ app. route ('/rs/<regex (". * "): query_url> ', methods = ['put', 'delete', 'post', 'get'])

Several questions:

  1. In theory, regular expressions (. *) should match all characters except carriage return, but do not know why. question marks (?) are not recognized here (?)
  2. I use request. data to retrieve form data. Why can't request. form be obtained?
  3. '/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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.