Flask framework-(view advanced)

Flask framework-(view advanced)

1. Class View

Introduction:
The advantage of the class view is that it supports inheritance, but the class view cannot be the same as the function view. After writing the
class view, you need to register through app.add_url_rule(url_rule,view_func).

1-1. Standard view

Introduction: The
standard view is inherited from flask.views.View, and the dispatch_request method must be implemented in the subclass. This method is similar to the view function. It also returns an object based on Response or its subclass.

Code example:

from flask.views import View
class PersonalView(View):
	def dispatch_request(self):
		return "测试页"
		
# 类视图通过add_url_rule⽅法和url做映射

app.add_url_rule('/users/',view_func=PersonalView.as_view('personalvi
ew'))

1-2. View based on scheduling method

Introduction:
Flask also provides us with another type of view flask.views.MethodView, which executes different functions for each HTTP method (mapped to the corresponding method of the same name).

Code example:

class LoginView(views.MethodView):
# 当客户端通过get⽅法进⾏访问的时候执⾏的函数
	def get(self):
		return render_template("login.html")

# 当客户端通过post⽅法进⾏访问的时候执⾏的函数
	def post(self):
		email = request.form.get("email")
		password = request.form.get("password")
		if email == '[email protected]' and password == '111111':
			return "登录成功!"
		else:
			return "⽤户名或密码错误!"

# 通过add_url_rule添加类视图和url的映射,并且在as_view⽅法中指定该url的名称,⽅便url_for函数调⽤

app.add_url_rule('/myuser/',view_func=LoginView.as_view('loginview')
)

One of the drawbacks of using class views is that it is more difficult to decorate with decorators, as sometimes when permission verification is required

Code example:

from flask import session
def login_required(func):
	def wrapper(*args,**kwargs):
		if not session.get("user_id"):
			return 'auth failure'
		return func(*args,**kwargs)
	return wrapper

After the decorator is written, you can define a property called decorators in the class view, and then store the decorator. This decorator will be executed every time this class of view is called in the future.

Code example:

class UserView(views.MethodView):
	decorators = [user_required]
	...

2. Blueprints and subdomains

2-1. Blueprint

Introduction:
The URL and view functions we wrote before are all in the same file. If the item is larger, this is obviously not a reasonable structure. The blueprint can elegantly help us achieve this requirement.

Code example:

from flask import Blueprint
bp = Blueprint('user',__name__,url_prefix='/user/')
@bp.route('/')
def index():
	return "⽤户⾸⻚"
	
@bp.route('profile/')
def profile():
	return "个⼈简介"

Then in the main program, we app.register_blueprint()register this blueprint into the url mapping through the method, and look at the implementation of the main app.

Code example:

from flask import Flask
import user
app = Flask(__name__)
app.register_blueprint(user.bp)
if __name__ == '__main__':
    app.run(host='0.0.0.0',port=9000)

Later visits to /user/ and /user/profile/ are all view
functions in the executed user.py file , thus achieving the modularization of the project.

The above is a brief introduction to the blueprint, but there are still other areas to pay attention to when using the blueprint, that is, how to find static files and template files in the blueprint, and how the url_for function reverses the url.

2-1-1. Find static files

Introduction:
By default, no static file path is set. Jinja2 will look for static files in the static folder of the project. You can also set other paths. When the blueprint is initialized, the Blueprint constructor has a parameter static_folder that can specify the path of the static file

Code example:

bp = Blueprint('admin',__name__,url_prefix='/admin',template_folder='templates')

There is a little difference between template files and static files. After the above code is written, if you render a template return render_template('admin.html'), Flask will search for the admin.html file in the templates folder under the project root directory by default. If it finds it, it will return directly. If it is not found, Then go to the templates folder in the directory where the blueprint file is located.

2-1-2. url_forGenerate URL

Introduction:
with url url_for generated blueprint, the format is: 蓝图名称+.+视图函数名称. For example, to get the url of the index view function under the blueprint of admin

Code example:

url_for('admin.index')

The blueprint name is the first parameter passed in when creating the blueprint

bp = Blueprint('admin',__name__,url_prefix='/admin',template_folder='templates')

2-2. Subdomain

Introduction:
Subdomains are used in many websites. For example, if a website is called xxx.com, then we can define a subdomain cms.xxx.com as the URL of the cms management system. The realization of subdomains is generally realized through blueprints. In the previous chapter, when we created the blueprint, we added a url_prefix=/user as the url prefix, so that we can access the url under user through /user/. However, it is not necessary to use subdomains. In addition, SERVER_NAME needs to be configured, for
example app.config[SERVER_NAME]='example.com:9000'. And when registering the blueprint, you also need to add a subdomain parameter, which is the name of the subdomain.

Code example:

from flask import Blueprint
bp = Blueprint('admin',__name__,subdomain='admin')
@bp.route('/')
def admin():
    return 'Admin Page'

This is not much different, let’s look at the implementation of the main app

Code example:

from flask import Flask
import admin
# 配置`SERVER_NAME`
app.config['SERVER_NAME'] = 'example.com:8000'
# 注册蓝图,指定了subdomain
app.register_blueprint(admin.bp)
if __name__ == '__main__':
    app.run(host='0.0.0.0',port=8000,debug=True)

tips: After
writing the above two files, the subdomain name admin.example.com:8000 cannot be accessed normally, because we did not add domain name resolution in the host file, you can add a line of 127.0.0.1 admin.example at the end. com, you can access it. In addition, the subdomain cannot appear on 127.0.0.1, nor can it appear on localhost.

Guess you like

Origin blog.csdn.net/weixin_45550881/article/details/105627990