Flask - Flask special decorative and structural work mode (FBV, CBV)

table of Contents

  • Flask - Flask special decorators and construction work mode
    • @app.errorhandler()
    • @app.before_request
    • @app.after_request
    • FBV and CBV

Flask - Flask special decorators and construction work mode

@app.errorhandler()

Role: redefinition error returned!

app.errorhandler @ (404 )
     DEF error404 (A):
         return f " page you want to view, was the monster ate} A {! "

@app.before_request

Action: entering function is decorated prior to the request (request) to enter the visual function, it is possible to do something before the request to enter the visual functions, such as session authentication and the like.

from flask import Flask
from flask import request
from flask import redirect
from flask import session

app = Flask(__name__)  # type:Flask
app.secret_key = "DragonFire"


@app.before_request
def is_login():
    if request.path == "/login":
        return None

    if not session.get("user"):
        return redirect("/login")


@app.route("/login")
def login():
    return "Login"


@app.route("/index")
def index():
    return "Index"


@app.route("/home")
def home():
    return "Login"


app.run("0.0.0.0", 5000)

@ App.before_request also a decorator, he decorated the function will be executed before the request to enter view function

request.path is to read the current url address if it is / login allows direct you through the return None can be understood by release

Is there a user if not, prove not logged in calibration session, so relentless redirect ( "/ login") Jump login page

There is also a mention to @ app.before_first_request it is very similar to the @ app.before_request or say exactly the same, except that it will only be executed once

@app.after_request

Role: to respond after the response (response)

@app.after_request
def foot_log(environ):
    if request.path != "/login":
        print("有客人访问了",request.path)
    return environ

FBV and CBV

  • FBV route and view

  •   @app.route("/login")
      def login():
  • CBV:
  •   from flask import views
      class Login(views.MethodView):
          def get(self):
              pass
    
          def post(self):
              pass
    
      app.add_url_rule("/login",endpoint=None,view_func=Login.as_view(name="login"))

  

Guess you like

Origin www.cnblogs.com/lw1095950124/p/10956394.html