[Python Web] Flask super practical basic knowledge summary (with code)

insert image description here
Flask is a lightweight web application framework written in Python. It is a simple and easy-to-use framework suitable for building small to medium-sized web applications. Flask provides basic web development functions, such as routing, request processing, template rendering, file uploading, etc.

The following is some basic syntax of Flask

1. Static file processing

folder directory

image-20230430155831782

  • app.py
from flask import Flask, render_template
# 静态文件处理
# static_folder:静态文件所在文件夹
# static_url_path:静态文件url文件夹路径
app = Flask(__name__, static_folder='static', static_url_path="/yy/yy")

@app.route('/')
def hello_world():
    return  render_template('test.html')

if __name__ == '__main__':
    app.run()
  • test.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<img src="{
     
     { url_for("static",filename='/2345_image_file_copy_2.jpg')}}">
<img src="/yy/yy/2345_image_file_copy_2.jpg">
</body>
</html>
  • result:

<img src="{ { url_for("static",filename='/2345_image_file_copy_2.jpg')}}">, this way is convenient to manage
insert image description here

2. Configuration files in Flask

2.1 The way based on global variables

  • configs/settings.py
from datetime import timedelta

flask_ENV='development'
SECRET_KEY = '_5#y2L"F4Q8zxec]/'
SQLALCHEMY_DATABASE_URI = 'XXXX'
UPLOAD_FOLDER = "XXX"
PERMANENT_SESSION_LIFETIME = timedelta(days=7)


#导入其它配置文件的配置,如果同名会将这里的覆盖掉
try:
    from .localsettings import *
except ImportError:
    pass   
  • app.py
from flask import Flask

app = Flask(__name__)
#从配置文件中导入文件
app.config.from_object("configs.settings")

@app.route('/')
def hello_world():
    #读取参数app.config.get() 或者 current_app.config.get()
    return app.config.get('UPLOAD_FOLDER')

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

2.2 Class-based approach

  • configs/settings.py
from datetime import timedelta

#公共配置,被其它类继承
class BaseSettings(object):
    SECRET_KEY = '_5#y2L"F4Q8zxec]/'

class DevSetting(BaseSettings):
    flask_ENV = 'development'
    DEBUG=True
    HOST:"xx.xx.xx.xx"
    SQLALCHEMY_DATABASE_URI = 'XXXX'
    UPLOAD_FOLDER = "Dev_Path"

class ProdSettings():
    HOST: 'xx.xx.xx.xx'
    SQLALCHEMY_DATABASE_URI = 'XXXX'
    UPLOAD_FOLDER = "Pro_Path"
    PERMANENT_SESSION_LIFETIME = timedelta(days=7)
  • app.py
from flask import Flask

app = Flask(__name__)
app.config.from_object("configs.settings.DevSettings")

@app.route('/')
def hello_world():
    #读取参数app.config.get() 或者 current_app.config.get()
    return app.config.get('UPLOAD_FOLDER')

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

3. Routing and Views

3.1 Route writing

  • general writing
@app.route('/login')
def login():
return render_template('login.html')
  • dynamic routing
@app.route('/login/<name>')
def login(name):
    print(type(name))
    return render_template('test.html')
@app.route('/login/<int:age>')
def login(age):
    print(type(age))
    return render_template('test.html')

3.2 View writing method

  • view function
@app.route('/login')
def login():
    return render_template('login.html')
  • view class
from flask import Flask,render_template,views
app = Flask(__name__)

def decorator1(func):
    def inner(*args,**kwargs):
        print('before1')
        result = func(*args,**kwargs)
        print('after1')
        return result
    return inner

def decorator2(func):
    def inner(*args,**kwargs):
        print('before2')
        result = func(*args,**kwargs)
        print('after2')
        return result
    return inner

class UserView(views.MethodView):
    #允许的请求类型
    methods = ['GET',"POST"]
    #装饰器,这里加了两个装饰器
    decorators = [decorator1,decorator2]
    # 执行GET请求
    def get(self):
        print('get')
        return 'get'
    # 执行POST请求
    def post(self):
        print('post')
        return 'post'
    
# 第一个参数为路由路径,第二个相当于endpoint="user"
app.add_url_rule('/user', view_func=UserView.as_view('user')) 

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

Results of the:

image-20230430164105769

4. Template parameter passing and global methods

4.1 Template parameter passing

The incoming parameters can be of various types or methods, such as the following func is a method

  • app.py
from flask import Flask,render_template
app = Flask(__name__)

def func(name):
    return '你好,' + name

@app.route('/test')
def index():
    info = ["奇幻","智能建造小硕","公众号"]
    return render_template('test.html',info=info,f=func)

if __name__ == '__main__':
    app.run()
  • test.html

    Flask uses Jinja2 template syntax

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>作者:{
   
   { info[0] }}</h1><br>
<h1>{
   
   { info[2] }}:{
   
   { info[1] }}</h1><br>
<h1>{
   
   { f("欢迎关注~") }}</h1>
</body>
</html>

result:
insert image description here

4.2 Global template method definition

It can be used directly in the template without passing it into the method as a parameter.

Note: The global template method defined in the blueprint can only be used within the scope of the blueprint template

#全局方法
#可以不用再响应函数中传,直接在HTML中把global的函数名写上即可
@app.template_global() #  {
    
    { func1("XXX") }}
def func1(arg):
    "xxx"
    return  arg

#过滤器
#过滤器的本质就是函数。有时候我们不仅仅只是需要输出变量的值,我们还需要修改变量的显示,甚至格式化、运算等等,这就用到了过滤器。 
#过滤器的使用方式为:变量名 | 过滤器。 过滤器名写在变量名后面,中间用 | 分隔。
#第一个参数是你要过滤的那个值(自身),Flask内有很多自带的过滤器
@app.template_filter() # {
    
    { "arg1"|func2(arg2) }}
def func2(arg1,arg2):
    "..."
    return XXX 

5. Decorator

5.1 Decorator Syntax

#自定义一个用户验证的装饰器
def auth(func):
    @wraps(func)
    def inner(*args,**kwargs):
        if 'username' in session:
            logsuccessmsg = f"登录成功{
      
      session['username']}"
            flash(logsuccessmsg)
            return func(*args,**kwargs) 
        # flash和它的名字一样,是闪现,意思就是我们的消息只会显示一次,当我们再次刷新也面的时候,它就不存在了,而正是这点,它经常被用来显示一些提示消息,比如登陆之后,显示欢迎信息等。
    else:
        flash("登录失败!")
        return redirect(url_for("login"))
    return  inner

#使用用户验证路由,判断是否登录,登录才能进入首页,否则进入登录页面
@app.route('/')
@app.route('/index')
@auth #相当于: auth(index())
def index():
    return render_template("index.html", account_name=session["username"],books=Books.query.all())

5.2 Other decorators

from flask import Flask,render_template,request

app = Flask(__name__)

@app.before_request #在请求执行之前执行
def before_request1():
    if request.path == '/login':
        return   
    print('before_request1')
    # return 'XXX' ,如果有return,这返回return的值,后面的不执行,可以作为用户验证

@app.after_request 
def after_request1(response):
    print('after_request1')
    return response # 一定要有return,为请求执行返回的结果

# 处理异常,接受参数,可以重定向到指定页面
@app.errorhandler(Exception)
def error(e):
    print("error")
    return redirect("/")

@app.route('/index')
def index():
    print('index')
    return render_template('index.html')

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

Flask is a flexible and easy-to-use framework that helps us quickly build web applications. If you want to learn more about Flask's functions and usage, please refer to the official Flask documentation.
https://dormousehole.readthedocs.io/en/2.1.2/index.html

Hope that helps! If you like it, just give it a thumbs up!

Guess you like

Origin blog.csdn.net/QH2107/article/details/130450305