Flash learning record 04 - redirection, custom converter, exception throw and capture

There is a proverb called "learning is like sailing against the current. If you don't advance, you will retreat", but in this highly convoluted environment of the Internet, I feel that you can advance if you don't retreat.

It is also a kind of progress to be able to keep the knowledge you have learned before. Let's review flash with Xiao Meng and see if you have forgotten it?

Today's core knowledge is as follows:

  • Via redirect and url_for routing redirection

  • Customize a list routing converter

  • Exception throwing and catching

Route redirection

Method 1: redirect directly returns to the front end

Let's first look at the source code parameters of redirect. They are very simple and have three values. The first two are to set the url and status code of the jump. The code defaults to 302. The last one is to limit the return object of the response

Let's write a demo and have a look

from flask import Flask
from werkzeug.routing import redirect

app = Flask(__name__)


@app.route('/')
def index():
    return '<h1>Start learning flask</h1>'


@app.route('/index')
def welcome():
    return redirect('/index/123')


@app.route('/index/<username>')
def get_user(username):
    return '<h1>Start learning flask Come on, mine{}</h1>'.format(username)


if __name__ == '__main__':
    app.run(debug=True)

The browser can see / index and successfully jump to / index/123 with code 302;

Method 2: Add URL to redirect_ For method, jump according to the defined method name, and pass parameters

redirect can jump or pass parameters. Why add a URL_ What about for?

If the original route is changed, the route to be redirect ed must be modified manually. Otherwise, the route will not be found and a 404 error will be reported.

Let's write a demo and access get through the route corresponding to welcome_ User can access the latest route even if the route changes

from flask import Flask, url_for
from werkzeug.routing import redirect

app = Flask(__name__)


@app.route('/')
def index():
    return '<h1>Start learning flask</h1>'


@app.route('/index')
def welcome():
    return redirect(url_for('get_user', username='1234'))


@app.route('/index/<username>')
def get_user(username):
    return '<h1>Start learning flask Come on, mine{}</h1>'.format(username)


if __name__ == '__main__':
    app.run(debug=True)

When the routing address is not modified, view the returned information

After modifying the route, the url_for automatically accesses the new route, and the returned information is consistent with the previous one

After modifying the route, redirect will not access the new route address, and 404 Not Found appears

Custom converter

Requirement: define a list routing converter to process the parameters when the routing parameters are list data types, such as:

Transfer parameters[1,2,3,4]--Parameters returned directly from the backend

The input parameter is'1,2,3,4'--Parameters entered by the user browser

Output parameters[1,2,3,4]--Parameters displayed on the page 

Analysis: by default, the parameter is of string type. You need to convert the passed parameter to string, judge whether it conforms to the rule, and then convert it back to the list

We have learned that the common routing converters are int / float / string (default), so let's look at the default converters through the source code?

Let's look at its inheritance through the int converter

It is found that the baseconverter class is inherited in the end. Then we inherit this class and write a list routing converter

from flask import Flask, url_for
from werkzeug.routing import redirect, BaseConverter

app = Flask(__name__)


class ListConverter(BaseConverter):
    def __init__(self, url_map, *args):
        # Route url unchanged
        super(ListConverter, self).__init__(url_map)
        # regex rule customization
        self.regex = args[0]

    # Process the url parameter before calling the view function
    def to_python(self, value):
        return value.split(',')

    # The incoming url parameters are processed before matching the route
    def to_url(self, value):
        result = ','.join([str(i) for i in value])
        # print(result)
        return result


# Configure the self-defined decorator into the routing default decorator
app.url_map.converters["list"] = ListConverter


@app.route('/')
def index():
    return 'Start learning flask'


@app.route('/wel')
def welcome():
    return redirect(url_for('get_user', username=[1, 3, 5, 7]))


@app.route('/index/<list("(\d+,+?)+\d+$"):username>')
def get_user(username):
    return "See if the input is a list:{}".format(username)


if __name__ == '__main__':
    app.run(debug=True)

Two methods in the source code are used here, to_python and to_url

The main functions of these two methods are like the comments in the code above. Let's see the effect below

The above example will the redirect and URL mentioned in this section_ for,to_python,to_url and regular expression are covered. If necessary, you can practice it yourself

When I hit this example, I encountered several resistance. One is when rewriting BaseConverter, and the other is when regular expression coverage. I need to practice more later

Recommend an address to practice regular expressions online: https://c.runoob.com/front-end/854/

Exception throwing and catching

1. Throw an exception through the abort method

from flask import Flask,abort

app = Flask(__name__)

@app.route('/')
def index():
    return 'Start learning flask'
    
if __name__ == '__main__':
    app.run(debug=True)

Once the abort method is started, it will abort the request and return the error message corresponding to the status code

The default prompt of the system is really ugly. We can catch exceptions and return new prompt information through the errorhandler decorator

from flask import Flask, url_for, abort

app = Flask(__name__)

@app.route('/')
def index():
    abort(404)
    return 'Start learning flask'


# Catch 404 error and return prompt information
@app.errorhandler(404)
def pagenotfound(e):
    return 'Eh, where's the page? Did you sneak to Menghuo to learn?'


if __name__ == '__main__':
    app.run(debug=True)


You can see that the page has caught 404 exceptions and returned our customized prompt information

This time I share here, the writing cycle of this section is relatively long. The content learned on Sunday was typed again on the company's computer with the help of memory, and then wrote this article, but it was typed again by hand, which made me more impressed

Welcome to official account adorable WeChat, and share more dry cargo regularly.

Tags: Python Back-end Flask

Posted on Thu, 28 Oct 2021 05:20:34 -0400 by afatkidrunnin