Python Flask Tutorial Learning 02

The book continues from the above Python Flask tutorial learning 01

Flask Tutorial

Flask session

Unlike Cookie, Session (session) data is stored on the server. A session is the time interval during which a client logs on to a server and logs off from the server. Data that needs to be saved for this session is stored in a temporary directory on the server.

from flask import render_template
from flask import make_response
from flask import Flask,session,redirect,url_for,escape,request
app=Flask(__name__)
#为每个客户端的会话分配会话ID。
#会话数据存储在cookie的顶部,服务器以加密方式对其进行签名。
#对于此加密,Flask应用程序需要一个定义的SECRET_KEY。(随便写)
app.secret_key='fkdjsafjdkfdlkjfadskjfadskljdsfklj'

@app.route('/')
def index():
    if 'username' in session:
        username=session['username']
        return '登录用户名是:'+username+'<br>'+\
                "<b><a href='/logout'>点击这里注销</a></b>"
    return "您暂未登录,<br><a href='/login'></b>"+\
            "点击这里登录</b></a>"
@app.route('/login',methods=['GET','POST'])
def login():
    if request.method=='POST':
        #设置会话变量
        session['username']=request.form['username']
        return redirect(url_for('index'))
    return '''
    <form action="" method="post">
        <p><input type="text" name="username"/></p>
        <p><input type="submit" value="登录"/></p>
    </form>
    '''
@app.route('/logout')
def logout():
    #释放会话变量
    session.pop('username',None)
    return redirect(url_for('index'))
if __name__ == '__main__':
    app.run(debug=True)

http://127.0.0.1:5000/
insert image description here
insert image description here
insert image description here
insert image description here

Flask message flash

from flask import Flask, flash, redirect, render_template, request, url_for
app = Flask(__name__)
app.secret_key = 'random string'
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/login', methods = ['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] != 'admin' or request.form['password'] != 'admin':
            error = 'Invalid username or password. Please try again!'
        #如果登录成功,则会在索引模板上刷新成功消息。
        else:
            '''
            flash(message, category)
            message 参数是要闪现的实际消息。
            category 参数是可选的。它可以是“error”,“info”或“warning”。
            '''
            flash('You were successfully logged in')
            return redirect(url_for('index'))
    #如果出现错误,则会重新显示登录模板,并显示错误消息。
    return render_template('login.html', error = error)

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

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <form method = "post" action = "http://localhost:5000/login">
        <table>
            <tr>
                <td>Username</td>
                <td><input type = 'username' name = 'username'></td>
            </tr>
            <tr>
                <td>Password</td>
                <td><input type = 'password' name = 'password'></td>
            </tr>
            <tr>
                <td><input type = "submit" value = "Submit"></td>
            </tr>
        </table>
    </form>
    {% if error %}
        <p><strong>Error</strong>: {
   
   { error }}</p>
    {% endif %}
</body>
</html>

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Index</title>
</head>
<body>
    <!-- 
    为了从会话中删除消息,模板调用 get_flashed_messages(with_categories, category_filter)。
    两个参数都是可选的。
    如果接收到的消息具有类别,
    则第一个参数是元组。第二个参数仅用于显示特定消息。
    -->
    {% with messages = get_flashed_messages() %}
         {% if messages %}
               {% for message in messages %}
                    <p>{
   
   { message }}</p>
               {% endfor %}
         {% endif %}
    {% endwith %}
<h3>Welcome!</h3>
<a href = "{
     
     { url_for('login') }}">login</a>
</body>
</html>

insert image description here
Click the login link (the user name and password are set in the program, the example is admin) and it will be
insert image description here
displayed after submission
insert image description here

Flask file upload

Create a new folder uploadto save the successfully uploaded files

from flask import Flask,render_template,request
'''
目标文件的名称可以是硬编码的,
也可以从 ​request.files[file] ​对象的​ filename ​属性中获取。
但是,建议使用 ​secure_filename()​ 函数获取它的安全版本。
'''
from werkzeug.utils import secure_filename
import os

app=Flask(__name__)
#定义上传文件夹的路径
#app.config['MAX_CONTENT_LENGTH'] 指定要上传的文件的最大大小(以字节为单位)
app.config['UPLOAD_FOLDER']='upload/'

@app.route('/upload')
def upload_file():
    return render_template('upload.html')
@app.route('/uploader',methods=['GET','POST'])
def uploader():
    if request.method=='POST':
        f=request.files['file']
        print(request.files)
        #secure_filename获取中文文件名需自行百度解决,不难
        f.save(os.path.join(app.config['UPLOAD_FOLDER'],secure_filename(f.filename)))
        return 'file uploaded successfully'
    else:
        return render_template('upload.html')
if __name__ == '__main__':
    app.run(debug=True)

upload.html

<html>
<head>
  <title>File Upload</title>
</head>
<body>
    <form action="http://localhost:5000/uploader" method="POST" enctype="multipart/form-data">
        <input type="file" name="file"  />
        <input type="submit" value="提交" />
    </form>
</body>
</html>

http://localhost:5000/upload
insert image description here
I chose a picture and submitted it
to note that when using secure_filenameto get the Chinese file name, the Chinese will be omitted. There are many blogs on the Internet that have written solutions, so I won’t make any changes
insert image description here

It shows that the submission is successful
insert image description here
and the uploaded file is saved in uploadthe folder
insert image description here

Flask extensions/find extensions

insert image description here
The extension of Flask is usually named Flask-Fooor find the address of the Flask extensionFoo-Flask
by pipinstalling it . This blog is here first . The next blog will learn more about several extensions.


Guess you like

Origin blog.csdn.net/weixin_46322367/article/details/127555500