03-06flask藍圖、jinja2

hello.py 啟動頁面。

# hello.py 啟動頁面。

import redis
from flask import Flask
from flask_script import Manager
from flask_session import Session

from app.views import blue     # 導入app文件夾下views.py文件中的blue變量
app = Flask(__name__)
# 第二步: 管理藍圖
app.register_blueprint(blueprint=blue)    # =blue是上面導入的那個

# 加密,加密復雜程度和設值有關
app.secret_key = '1234567890'
# 配置session信息
# from flask_session import Session
app.config['SESSION_TYPE'] = 'redis'
app.config['SESSION_REDIS'] = redis.Redis(host='127.0.0.1', port=6379)
Session(app)

manage = Manager(app)

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

views.py 內(nèi)容頁面

#  views.py  內(nèi)容頁面
from flask import render_template, make_response, \
    request, session, Blueprint, redirect, \
    url_for

from utils.functions import is_login  

# 藍圖,管理路由地址
# 第一步: 生成藍圖對象
blue = Blueprint('first', __name__)

@blue.route('/')
def hello():
    return 'hello world'

@blue.route('/make_res/')
def make_res():
    # make_response('響應內(nèi)容', 響應狀態(tài)碼)創(chuàng)建響應對象
    # return make_response('hello flask day02', 200)
    # return make_response('<h2>今天天氣不好</h2>')
    index = render_template('index.html')
    return make_response(index, 200)

@blue.route('/register/', methods=['GET', 'POST'])
def register():
    print(request.method)
    if request.method == 'GET':
        return render_template('register.html')
    if request.method == 'POST':
        # 模擬注冊功能
        # 1. 獲取頁面中傳遞的參數(shù)
        username = request.form.get('username')
        password = request.form.get('password')
        password2 = request.form.get('password2')
        # 模擬注冊
        if username == 'coco' and password == password2 \
           and password == '123456':
            # 返回登錄頁面
            return redirect(url_for('first.login'))
            # return render_template('login.html')
        else:
            return render_template('register.html')

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

    if request.method == 'POST':
        # 1.獲取參數(shù)
        username = request.form.get('username')
        password = request.form.get('password')
        # 2.模擬登陸
        if username == 'coco' and password == '123456':
            # 向cookie中設置參數(shù)
            res = make_response(render_template('index.html'))
            # 設置cookie
            res.set_cookie('token', '12345678', max_age=3000)
            return res
        else:
            return render_template('login.html')

@blue.route('/logout/')
def my_logout():
    # 注銷
    res = make_response(render_template('login.html'))
    res.delete_cookie('token')
    return res

@blue.route('/index/')
def index():
    # 登陸過后能看到index.html頁面, 沒有登錄跳轉(zhuǎn)到登錄頁面
    token = request.cookies.get('token')
    if token == '12345678':
        # 判斷登陸成功了
        return render_template('index.html')
    else:
        # 判斷登陸失敗了
        return render_template('login.html')

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

    if request.method == 'POST':
        # 解析參數(shù)
        username = request.form.get('username')
        password = request.form.get('password')
        if username == 'coco' and password == '123456':
            # 向session會話中設置鍵值對
            session['login_status'] = 1
            # session['name'] = 'coco'
            # session['pwd'] = '123456'
            return render_template('index.html')
        else:
            return render_template('session_login.html')

@blue.route('/session_index/')
@is_login
def session_index():
    # if 'login_status' in session:
        return render_template('index.html')
    # else:
    #     return render_template('session_login.html')

@blue.route('/xindex/')
@is_login
def xindex():
    # 登錄過后能夠訪問index.html頁面
    # 沒有登錄不讓訪問,跳轉(zhuǎn)到session_login.html頁面
    return render_template('index.html')

@blue.route('/session_logout/')
def session_my_logout():
    # 注銷
    del session['login_status']
    return render_template('session_login.html')

@blue.route('/redirect_func/')
def redirect_func():
    # 跳轉(zhuǎn)到登錄頁面
    # return render_template('login.html')
    # return redirect('/login/')
    # url_for('藍圖的第一個參數(shù).跳轉(zhuǎn)的函數(shù)名')
    # print(url_for('first.login'))
    # return redirect(url_for('first.login'))
    # return redirect('/s_id/1/')
    return redirect(url_for('first.s_id', id=100))   
  #上       重定向   打開頁面

@blue.route('/s_id/<int:id>/')       
def s_id(id):              #int:id  s_id(id):  % id 三個id的名字必須一樣
    return 's_id: %s' % id
#  下午模板內(nèi)容

@blue.route('/student/')
def stu():
    stus_score = [90, 89, 100, 99, 87, 67]
    content_h2 = '<h2>千鋒真棒!</h2>'
    return render_template('stu.html',
                           scores=stus_score,       # 返回變量到html文件
                           content_h2=content_h2)   # 返回變量到html文件

html文件的繼承

# 1 base.html  父頁面
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>
        <!--jinja2-->
        {% block title %}  # 父類開接口,在子類中寫內(nèi)容填充
        {% endblock %}
    </title>
    {% block css %}
    {% endblock %}

    {% block js %}
    {% endblock %}
</head>
<body>
    {% block content %}     
    {% endblock %}  
</body>
</html>
# 2.base_min.html  父頁面初始化
{% extends 'base.html' %}     # 繼承base.html
{% block js %}        # 填父類中名為js的接口
    <!--初始化引入jquery.js文件-->
    <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
{% endblock %}    #內(nèi)容到此為止
# 3. stu.html  最終顯示的網(wǎng)頁
{% extends 'base_main.html' %}
{% block title %}
    學生列表頁面
{% endblock %}

{% block css %}
    <!--第一種寫法-->
    <!--<link rel="stylesheet" href="/static/css/style.css">-->
    <!--第二種寫法-->
    <link rel="stylesheet"
          href="{{ url_for('static', filename='css/style.css') }}">

{% endblock %}

{% block js %}
    {{ super() }}        # 加上這個,js文件兩個可以同時生效。這里的script和2.xx.html兩個地方的js
    <script src="2q3weftrfe.js"></script>
{% endblock %}

{% block content %}
    <!--過濾器-->
    <p> {{ content_h2 | safe }} </p>    # 將字符串顯示為標簽內(nèi)容
    <p>{{ 'Python' | length }}</p>           # 顯示字符串長度
    <p>{{ 'Python' | upper }}</p>            # 大寫
    <p>{{ 'Python' | lower }}</p>                # 小寫
    <p>{{ 'python' | upper | length }}</p>  # 兩個連接的顯示最后一個的內(nèi)容
    <p>{{ 'Python' | reverse }}</p>         # 倒序
    <p>{{ content_h2 | striptags }}</p>   # 去掉字符串標簽符顯示內(nèi)容

    <!--解析變量使用 {{ 變量名 }}-->
    <p> {{ scores }} </p>     # scores是py文件中傳過來的變量

    <!--解析標簽,extends,block,for-->
    {# {{ 注釋內(nèi)容 }} #}   # 這個表示注釋,內(nèi)容寫在中間
    <ul>
        {% for a in scores %}  
            {{ loop.revindex0 }}       # 顯示a的序號,倒著顯示,最小為0
             {{ loop.index }}           # 顯示a的序號,從1開始
            {{ loop.first }}             # 第一個顯示為True
            {{ loop.last }}              # 最后一個顯示為True
            <li {% if loop.index == 1 %} style="color:yellow;" {% endif %}>
                {{ a }}
            </li>
        {% else %}            # 如果for循環(huán)中scores沒內(nèi)容,顯示下面的標簽
            <li>沒有學生成績數(shù)據(jù)</li>
        {% endfor %}         # for循環(huán)的結(jié)束處
    </ul>
    <table>
        <thead>
            <th>姓名</th>
            <th>年齡</th>
        </thead>
        <tbody>
            <tr>
                <td>張三</td>
                <td>28</td>
            </tr>
            <tr>
                <td>李四</td>
                <td>29</td>
            </tr>
        </tbody>
    </table>
{% endblock %}
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容