Summary of Common Definition Methods of flask Framework Routing

  • 2021-07-26 08:02:20
  • OfStack

This paper describes the common definition of flask framework routing with examples. Share it for your reference, as follows:

Various ways to define routes

Request mode qualification

Use the methods parameter to specify acceptable request methods, which can be multiple


@app.route('/',methods=['GET'])
def hello():
  return '<h1>hello world</h1>'

Route lookup mode

The same 1 route points to two different functions, which are matched from top to bottom in the matching process


@app.route('/')
def hello():
  return '<h1>hello world</h1>'
@app.route('/')
def hello_2017():
  return '<h1>hello 2017</h1>'

So the result of the above route/output is the result of the hello function

Example of passing parameters to routes

Sometimes we need to map the same class 1 URL to the same view function, for example, use the same view function to display personal information of different users.

The parameters passed by route are treated as string by default, and int is specified here. The contents in angle brackets are dynamic, and the type may not be specified


@app.route('/user/<int:id>')
def hello_itheima(id):
  return 'hello itcast %d' %id

Redirect redirect Sample


from flask import redirect
@app.route('/')
def hello_itheima():
  return redirect('http://www.itcast.cn')

Returns JSON


from flask import Flask,json
@app.route('/json')
def do_json():
  hello = {"name":"stranger", "say":"hello"}
  return json.dumps(hello)

Returning a status code example

There are two ways to return status codes in Python:

-Direct return
You can customize the return status code, and you can realize the status code that does not conform to http protocol, for example: error=666, errmsg= 'Query database exception'. Its function is to realize the convenience of data interaction between front and back ends
-abort method
-Only http compliant exception status codes will be thrown for manual exception throwing


@app.route('/')
def hello_itheima():
  return 'hello itcast',666

Example of regular routing

In the development of web, there may be a scenario of restricting user access rules, so it is necessary to use regular matching, restricting access and optimizing access at this time

Import Converter Package


from werkzeug.routing import BaseConverter

Customize the converter and implement it


#  Custom converter 
class Regex_url(BaseConverter):
  def __init__(self,url_map,*args):
    super(Regex_url,self).__init__(url_map)
    self.regex = args[0]
app = Flask(__name__)
#  Add a custom converter class to the converter dictionary 
app.url_map.converters['re'] = Regex_url
@app.route('/user/<re("[a-z]{3}"):id>')
def hello_itheima(id):
  return 'hello %s' %id

Bring several converters with you


DEFAULT_CONVERTERS = {
  'default':     UnicodeConverter,
  'string':      UnicodeConverter,
  'any':       AnyConverter,
  'path':       PathConverter,
  'int':       IntegerConverter,
  'float':      FloatConverter,
  'uuid':       UUIDConverter,
}

I hope this article is helpful to the Python programming based on flask framework.


Related articles: