Flask框架(一)—— Flask简介

Flask框架介绍

一、Flask简介

Flask是一个基于Python开发并且依赖jinja2模板和Werkzeug WSGI服务的一个微型框架,对于Werkzeug本质是Socket服务端,其用于接收http请求并对请求进行预处理,然后触发Flask框架,开发人员基于Flask框架提供的功能对请求进行相应的处理,并返回给用户,如果要返回给用户复杂的内容时,需要借助jinja2模板来实现对模板的处理,即:将模板和数据进行渲染,将渲染后的字符串返回给用户浏览器。

“微”(micro) 并不表示你需要把整个 Web 应用塞进单个 Python 文件(虽然确实可以 ),也不意味着 Flask 在功能上有所欠缺。微框架中的“微”意味着 Flask 旨在保持核心简单而易于扩展。Flask 不会替你做出太多决策——比如使用何种数据库。而那些 Flask 所选择的——比如使用何种模板引擎——则很容易替换。除此之外的一切都由可由你掌握。如此,Flask 可以与您珠联璧合。

默认情况下,Flask 不包含数据库抽象层、表单验证,或是其它任何已有多种库可以胜任的功能。然而,Flask 支持用扩展来给应用添加这些功能,如同是 Flask 本身实现的一样。众多的扩展提供了数据库集成、表单验证、上传处理、各种各样的开放认证技术等功能。Flask 也许是“微小”的,但它已准备好在需求繁杂的生产环境中投入使用

二、flask安装与使用

1、安装

pip3 install flask

2、使用

from flask import Flask

# 实例化产生一个Flask对象
app = Flask(__name__)

# 将 '/'和视图函数hello_workd的对应关系添加到路由中
@app.route('/')
def func():
    return 'hello world!'

if __name__ == '__main__':
    app.run()  # 最终调用了run_simple()

3、简单案例——flask实现用户登录

(1)main.py

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

app = Flask(__name__)

app.debug = True

app.secret_key = 'asdfghjkl'    # session必须要写上secret_key,session加密所用的盐

USER_INFO = {
    1: {'name': '张三', 'age': 18, 'gender': '男', 'text': "张三详情"},
    2: {'name': '李四', 'age': 44, 'gender': '女', 'text': "李四详情"},
    3: {'name': '王五', 'age': 23, 'gender': '女', 'text': "王五详情"},
}

# 登录认证装饰器
def login_auth(func):
    def inner(*args, **kwargs):
        if not session.get('name'):
            return redirect('/login')

    return inner


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')

    else:
        name = request.form.get('name')
        pwd = request.form.get('pwd')
        if name == 'wl' and pwd == '123':
            session['user'] = name
            return render_template('user_info.html', user_info=USER_INFO)
        else:
            return render_template('login.html', error='用户名或密码错误')


@app.route('/userdetail/<int:id>', methods=['GET'])
@login_auth
def userdetail(id):
    user = USER_INFO.get(id)	
    if user:
        return render_template('userdetail.html', user=user)
    else:
        return '该用户不存在'


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

(2)templates

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form method="post">
    <p>用户名:<input type="text" name="name"></p>
    <p>密码:<input type="password" name="pwd"></p>
    <input type="submit"><span>{{error}}</span>
</form>
</body>
</html>

user_info.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户信息</title>
</head>
<body>
<table border="1px">
    <thead>
    <tr>
        <th>id</th>
        <th>姓名</th>
        <th>详情</th>
    </tr>
    </thead>
    <tbody>
        <!-- 这里的items要加括号,否则报错 -->
    {% for k,v in user_info.items() %}
    <tr>
        <td>{{k}}</td>
        <td>{{v.name}}</td>
        <td><a href="/userdetail/{{k}}">查看详情</a></td>
    </tr>
    {% endfor %}

    </tbody>
</table>
</body>
</html>

userdetail.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>详情</title>
</head>
<body>
<table border="1px">
    <thead>
    <tr>
        <th>姓名</th>
        <th>年龄</th>
        <th>信息</th>

    </tr>
    </thead>
    <tbody>
    <tr>
        <td>{{user.name}}</td>
        <td>{{user.age}}</td>
        <td>{{user.text}}</td>
    </tr>

    </tbody>
</table>
</body>
</html>
原文地址:https://www.cnblogs.com/linagcheng/p/10396063.html