4 flask URL s and Views

 
Reference video tutorial:   
 
** Separate front-end and back-end of RESTFul API for Python Flask advanced programming (next)   **
URL s and Views

Mapping URL s to functions

From the previous helloworld.py file, we have seen that a URL is mapped to an execution function using the @app.route decorator. @ In the app.route decorator, you can specify rules for URLs for more detailed mapping, such as mapping a URL for article details now, where the URL for article details is/article/id/, and the ID may be 1, 2, 3...

   @app.route('/article/<id>/')
   def article(id):
       return '%s article detail' % id

Where <id>, angle brackets are fixed, and the syntax is <variable_name>, variable_ The default data type for name is string. Write <converter:variable_if you need to specify a type Name>, where converter is the type name, can have the following:

  • string: Default data type that accepts text without any slash'\/'.

  • int: Accepts integers.

  • float: Accepts floating point types.

  • path: similar to string, but accepts slashes.

  • uuid: Only uuid strings are accepted.

  • any: Multiple paths can be specified, as illustrated by one example:

    @app.route('/<any(article,blog):url_path>/')
    def item(url_path):
        return url_path
  

In the example above, item can accept two URLs, one is / article/, the other is / blog/. And be sure to pass url_path parameter, of course this URL_ The path name is arbitrary.

If you don't want to customize subpaths to pass parameters, you can also pass parameters through traditional?= A parameter is passed in the form: /article?id=xxx, in which case the value of the ID can be obtained by request.args.get('id'). If it is a post method, it can be obtained by request.form.get('id').

Construct URL (url_for)

Usually we can execute a function through a URL. If, on the other hand, we know a function, how do we get this URL? Url_ The for function can help us do this. Url_ The for() function receives two or more parameters, receives the function name as the first parameter, receives the named parameter of the corresponding URL rule, and if other parameters occur, is added to the back of the URL as a query parameter.

There are two reasons why you choose to spell URLs directly in your code by building URLs:

  1. If you modify the URL in the future, but do not modify the function name corresponding to the URL, you will not have to replace the URL everywhere.
  2. Url_ The for() function escapes special characters and Unicode data, which we don't need to do ourselves.

Here is an example to illustrate:

    from flask import Flask,url_for
    app = Flask(__name__)

    @app.route('/article/<id>/')
    def article(id):
        return '%s article detail' % id

    # This line of code can generate a request context in interactive mode. Instead of running this project with `app.run()', you can run the following code directly.
    # There will also be a `flask'context
    with app.test_request_context():
        print url_for('article',id='1')
        print url_for('article',id='2',next='/')

The results after execution are as follows:
> /article/1/
> /article/2/?next=%2F

Custom URL Converter

Just as we were mapping URL s, we saw that Flask has several built-in converters for data types, such as int/string. If Flask's built-in converter does not meet your needs, you can customize the converter at this time. To customize the converter, the following conditions need to be met:

  1. Converter is a class and must inherit from werkzeug.routing.BaseConverter.
  2. In the converter class, implement to_ The Python (self, value) method, whose return value is passed to the view function as an argument.
  3. In the converter class, implement to_ The URL (self, values) method, the return value of which will call url_for function generates the required URL form.

For example, for an official example, Reddit can easily view posts from multiple communities at the same time by separating their names with a plus sign (+) in the URL. For example, visit " www.reddit.com/r/flask+lisp/ "While you can view posts from both flask and lisp communities at the same time, now we customize a converter to do this:

#coding: utf-8
from flask import Flask,url_for
from werkzeug.routing import BaseConverter

class ListConverter(BaseConverter):
    def __init__(self,url_map,separator='+'):
        super(ListConverter,self).__init__(url_map)
        self.separator = separator

    def to_python(self, value):
        return value.split(self.separator)

    def to_url(self, values):
        return self.separator.join(BaseConverter.to_url(self,value) for value in values)  

app.url_map.converters['list'] = ListConverter

@app.route('/community1/<list:page_names>')
def community1(page_names):
    return '%s+%s' % tuple(page_names)

@app.route('/community2/<list('|'):page_names>/')
def community2(page_names):
    return "%s|%s" % tuple(page_names)

Commtyu1 uses the default + sign to connect, while the second uses | to connect.

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


app = Flask(__name__)

# A url contains a variable with a mobile phone number, and the string format of the variable must be restricted to match the format of the mobile phone number
class TelephoneConveter(BaseConverter):
    regex = r'1[85734]\d{9}'

# Users are accessing/posts/a+b/
class ListConverter(BaseConverter):
    def to_python(self, value):
        return value.split('+')

    def to_url(self, value):
        return "+".join(value)
        # return "hello"

app.url_map.converters['tel'] = TelephoneConveter
app.url_map.converters['list'] = ListConverter

@app.route('/')
def hello_world():
    print('='*30)
    print(url_for('posts',boards=['a','b']))
    print('='*30)
    return 'Hello World!'

@app.route('/user/<string:user_id>/')
def user_profile(user_id):
    return 'The one you entered user_id For:%s' % user_id

@app.route('/telephone/<tel:my_tel>/')
def my_tel(my_tel):
    return 'Your mobile number is:%s' % my_tel

@app.route('/posts/<list:boards>/')
def posts(boards):
    print(boards)
    return "Your submission is:%s" % boards

# http://127.0.0.1:8888/posts/aaa+bbb/
# Your submission is: ['aaa','bbb']


if __name__ == '__main__':
    app.run(host='0.0.0.0',port=8888,debug=True)

URL Unique

Flask's URL rules are based on Werkzeug's routing module. The idea of this module is based on the idea of Apache and earlier HTTP servers, which wanted to guarantee elegant and unique URLs.

For instance:

 @app.route('/projects/')
 def projects():
     return 'project page'

In the example above, accessing a URL with no slash at the end is redirected to a URL with a slash. This helps prevent search engines from searching the same page twice.

Take another example:

 @app.route('/about')
 def about():
     return 'about page'

In the example above, accessing a slashed URL (/about/) results in a 404 ("Not Found") error.

Specify HTTP Method

GET and POST requests:

There are many request modes in network requests, such as GET, POST, DELETE, PUT requests, etc. The most common are GET and POST requests.

  1. GET request: Only resources will be acquired on the server, and the state of the server will not be changed. GET requests are recommended for this type of request.
  2. POST request: Some data or files will be submitted to the server. In general, POST requests affect the state of the server, so POST requests are recommended.
  3. About parameter passing:
  • GET request: Put parameters in url, pass? Passed as xx=xxx. Because the parameters are placed in the url, if you have good vision, you can see the parameters you pass to the server at a glance. That's not very safe.
  • POST request: Put parameters in Form Data. The parameters are put into Form Data to avoid the risk of being sneaked in, but if someone wants to peek at your password, they can actually be packaged. Because POST requests can submit some data to the server, such as sending files, this increases the risk. So POST requests are actually more insecure for experienced hackers.
  1. In Flask, the route method, which by default will only request this url by GET, should pass a method parameter if you want to set your own request method.

In @app.route(), you can pass in a keyword parameter, methods, to specify the HTTP methods supported by this method. By default, only GET requests are responded to. Take the following example:

@app.route('/login/',methods=['GET','POST'])
def login():
    return 'login'

The above decorators will enable login's URL s to support both GET and POST.

Page Jump and Redirection

Redirection is divided into permanent redirection and temporary redirection. What you see on a page is that the browser automatically jumps from one page to another. For example, a user visits a page that requires permission, but the user is not currently logged in, so we should redirect him to the logon page.

  • Permanent redirection: The status code of http is 301, mostly used for old web addresses. To ensure users'access to a new web address, the most classic one is the Jingdong Web site. When you enter www.jingdong.com, it will be redirected to www.jd.com, because the jingdong.com web address has been abandoned and changed to jd.com, so a permanent redirection should be used in this case.
  • Transient redirection: The http status code is 302, indicating a temporary jump to the page. For example, if you visit an address that requires permission, you should redirect to the login page if the current user is not logged in. In this case, you should use temporary redirection.

In flask, redirection is achieved through the function flask.redirect(location,code=302), where location indicates the URL to redirect to and should match the url_mentioned earlier The for() function is used, and code indicates which redirection to use. The default is 302, or temporary redirection, which can be modified to 301 to achieve permanent redirection.

Here's an example of how to use redirection in flask:

 from flask import Flask,url_for,redirect

 app = Flask(__name__)
 app.debug = True

 @app.route('/login/',methods=['GET','POST'])
 def login():
     return 'login page'

 @app.route('/profile/',methods=['GET','POST'])
 def profile():
     name = request.args.get('name')

     if not name:
     # If there is no name, it means no login, redirect to the login page
         return redirect(url_for('login'))
     else:
         return name

Tags: IT

Posted on Tue, 09 Nov 2021 04:36:14 -0500 by Dia:NL