Initial Flask and simply getting started with the application

insert image description here
Yes, you read that right, the picture above represents Flask. So what is Flask?

Flask is a lightweight web application framework written in Python. Its WSGI toolbox uses Werkzeug, and its template engine uses Jinja2. Flask is licensed under the BSD license.

Compared with similar frameworks, the Flask framework is moreFlexible, lightweight, safe and extremely easy to use

First, configure the environment variables before getting started

Windows users can directly enter the following command in the dos window or the Terminal under pycharm:

pip install flask

Second, an example illustrating Flask'light' where?

Note: It is recommended to create a new python project

from flask import Flask

app = Flask(__name__)  # 创建一个Flask对象


@app.route('/study')  # 使用 route() 装饰器来告诉 Flask 触发函数的 URL
def study():
    return "<h1>Hello Word!</h1>"


app.run()  # 启动服务

In pycharm, just right-click to run.
insert image description here
insert image description here
Note: From the running results above, we can see that the default port of Flask is 5000, while the default port of Django is 8000, and the default port of Tornado is 8888;

You can run it with just six lines of code. Do you dare to say that it is not 'light'?

Three, simply get started with a user management system

In fact, if you know something about the Django framework, it will be very easy to learn Flask.

1. Realize simple user login

from flask import Flask, request, render_template

app = Flask(__name__)  # 创建一个Flask对象


@app.route('/login', methods=['GET', 'POST', ])  # mothods=['GET', 'POST', ] 表示既可以发送GET请求,也可以发送POST请求
def login():
    if request.method == "GET":  # 如果发送的是GET请求
        return render_template('login.html')  # 使用 render_template() 方法可以渲染模板,相当于Django中的render()
    else:
        user = request.form.get('username')  # request.form.get()表示通过post方式获取值
        pwd = request.form.get('password')
        if user == 'hpl' and pwd == '123456':
            return "<h1>恭喜您登录成功!</h1>"
        else:
            return render_template('login.html', error='用户名或密码错误!')


app.run(debug=True)  # 启动服务 debug=True 表示启动debug调式

Create a folder named templates in the root directory, the user places the template (similar to Django); and create a login.html file below, the content of which is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>欢迎来到登陆页面</title>
</head>
<body>
<h1>登录</h1>
<form action="" method="post">
    <p>
        <label for="">用户名:</label>
        <input type="text" name="username">
    </p>
    <p>
        <label for="">密码:</label>
        <input type="password" name="password">
        <span style="color:red;">{
   
   { error }}</span>
    </p>
    <button>提交</button>
</form>
</body>
</html>

Run it, the result is:

When the user name or password is wrong:
insert image description here
When the user name and password are correct:
insert image description here
2. Put the user's login information into the session

from flask import Flask, request, render_template, session

app = Flask(__name__)  # 创建一个Flask对象
app.secret_key = 'jkdfgd'  # 相当于加盐(里面的内容随便写)


@app.route('/login', methods=['GET', 'POST', ])  # mothods=['GET', 'POST', ] 表示既可以发送GET请求,也可以发送POST请求
def login():
    if request.method == "GET":  # 如果发送的是GET请求
        return render_template('login.html')  # 使用 render_template() 方法可以渲染模板,相当于Django中的render()
    else:
        user = request.form.get('username')  # request.form.get()表示通过post方式获取值
        pwd = request.form.get('password')
        # 将用户信息放入session
        session['user_information'] = user
        if user == 'hpl' and pwd == '123456':
            return "<h1>恭喜您登录成功!</h1>"
        else:
            return render_template('login.html', error='用户名或密码错误!')


app.run(debug=True)  # 启动服务 debug=True 表示启动debug调式

After logging in again, as shown in Figure
insert image description here
3 below, the basic information and detailed information of the user are displayed

from flask import Flask, request, render_template, session, redirect

USER_DICT = {
    
    
    '1': {
    
    'name': '光头强', 'age': 30, 'sex': '男', 'address': '团结屯'},
    '2': {
    
    'name': '大马猴', 'age': 25, 'sex': '男', 'address': '未知'},
    '3': {
    
    'name': '二狗子', 'age': 26, 'sex': '男', 'address': '未知'},
    '4': {
    
    'name': '李老板', 'age': 42, 'sex': '男', 'address': '大都市'},
    '5': {
    
    'name': '翠花', 'age': 18, 'sex': '女', 'address': '森林'},
}

app = Flask(__name__)  # 创建一个Flask对象
app.secret_key = 'jkdfgd'  # 相当于加盐(里面的内容随便写)


@app.route('/login', methods=['GET', 'POST', ])  # mothods=['GET', 'POST', ] 表示既可以发送GET请求,也可以发送POST请求
def login():
    if request.method == "GET":  # 如果发送的是GET请求
        return render_template('login.html')  # 使用 render_template() 方法可以渲染模板,相当于Django中的render()
    else:
        user = request.form.get('username')  # request.form.get()表示通过post方式获取值
        pwd = request.form.get('password')
        # 将用户信息放入session
        session['user_information'] = user
        if user == 'hpl' and pwd == '123456':
            return redirect('/index')  # 重定向(和Django中类似)
        else:
            return render_template('login.html', error='用户名或密码错误!')


@app.route('/index', methods=['GET', ], endpoint='index')  # 同Django中的name,用于反向解析
def index():
    user_info = session.get('user_information')
    if not user_info:
        return redirect('/login')

    return render_template('index.html', user_dict=USER_DICT)


@app.route('/detail', methods=['GET', ], endpoint='detail')
def detail():
    user_info = session.get('user_information')
    if not user_info:
        return redirect('/login')
    user_id = request.args.get('user_id')
    info = USER_DICT.get(user_id)
    return render_template('detail.html', info=info)


app.run(debug=True)  # 启动服务 debug=True 表示启动debug调式

Create index.html and detail.html files under the templates folder

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户信息</title>
</head>
<body>
<h2>用户信息</h2>
<table border="1px" cellspacing="0" cellpadding="5px">
    <thead>
    <tr>
        <th>姓名</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
    {
    
    % for k,v in user_dict.items() %}
    <tr>
        <td>{
    
    {
    
     v.name }}</td>
        <td><a href="/detail?user_id={
    
    { k }}">查看详情</a></td>
    </tr>
    {
    
    % endfor %}
    </tbody>
</table>
</body>
</html>

detail.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>信息详情展示页</title>
</head>
<body>
<h1>详情信息</h1>
<table border="1px" cellpadding="5px" cellspacing="0">
    <thead>
    <tr>
        <th>姓名</th>
        <th>年龄</th>
        <th>性别</th>
        <th>住址</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>{
    
    {
    
     info.name }}</td>
        <td>{
    
    {
    
     info.age }}</td>
        <td>{
    
    {
    
     info.sex }}</td>
        <td>{
    
    {
    
     info.address }}</td>
    </tr>
    </tbody>
</table>
</body>
</html>

The result is
insert image description here
insert image description here

4. Log out

from flask import Flask, request, render_template, session, redirect

USER_DICT = {
    
    
    '1': {
    
    'name': '光头强', 'age': 30, 'sex': '男', 'address': '团结屯'},
    '2': {
    
    'name': '大马猴', 'age': 25, 'sex': '男', 'address': '未知'},
    '3': {
    
    'name': '二狗子', 'age': 26, 'sex': '男', 'address': '未知'},
    '4': {
    
    'name': '李老板', 'age': 42, 'sex': '男', 'address': '大都市'},
    '5': {
    
    'name': '翠花', 'age': 18, 'sex': '女', 'address': '森林'},
}

app = Flask(__name__)  # 创建一个Flask对象
app.secret_key = 'jkdfgd'  # 相当于加盐(里面的内容随便写)


@app.route('/login', methods=['GET', 'POST', ])  # mothods=['GET', 'POST', ] 表示既可以发送GET请求,也可以发送POST请求
def login():
    if request.method == "GET":  # 如果发送的是GET请求
        return render_template('login.html')  # 使用 render_template() 方法可以渲染模板,相当于Django中的render()
    else:
        user = request.form.get('username')  # request.form.get()表示通过post方式获取值
        pwd = request.form.get('password')
        # 将用户信息放入session
        session['user_information'] = user
        if user == 'hpl' and pwd == '123456':
            return redirect('/index')
        else:
            return render_template('login.html', error='用户名或密码错误!')


@app.route('/index', methods=['GET', ], endpoint='index')
def index():
    user_info = session.get('user_information')
    if not user_info:
        return redirect('/login')

    return render_template('index.html', user_dict=USER_DICT)


@app.route('/detail', methods=['GET', ], endpoint='detail')
def detail():
    user_info = session.get('user_information')
    if not user_info:
        return redirect('/login')
    user_id = request.args.get('user_id')
    info = USER_DICT.get(user_id)
    return render_template('detail.html', info=info)


@app.route('/logout', methods=['GET', ])
def logout():
    del session['user_information']  # 删除session即可退出登录
    return redirect('/login')


app.run(debug=True)  # 启动服务 debug=True 表示启动debug调式

For more details, see the Flask development documentation: https://dormousehole.readthedocs.io/en/latest/

Guess you like

Origin blog.csdn.net/hpl980342791/article/details/117340370