Flask利用session實現簡單登錄退出

用的session來保存信息

在templates文件夾下添加html文件

layout.html

``` Flaskr

Flaskr

{% if not session.logged_in %} log in {% else %} log out {% endif %}
{% for message in get_flashed_messages() %}
{{ message }}
{% endfor %} {% block body %}{% endblock %}
```

login.html

``` {% extends "layout.html" %} {% block body %}

Login

{% if error %}

Error: {{ error }}{% endif %}

Username:
Password:
{% endblock %} ```

show_entries.html

``` {% extends "layout.html" %} {% block body %} {% if session.logged_in %}
Title:
Text:
{% endif %}
    {% for entry in entries %}
  • {{ entry.title }}

    {{ entry.content|safe }} {% else %}
  • Unbelievable. No entries here so far {% endfor %}
{% endblock %} ```

在static下CSS文件

style.css

body            { font-family: sans-serif; background: #eee; }
a, h1, h2       { color: #377BA8; }
h1, h2          { font-family: 'Georgia', serif; margin: 0; }
h1              { border-bottom: 2px solid #eee; }
h2              { font-size: 1.2em; }

.page           { margin: 2em auto; width: 35em; border: 5px solid #ccc;
                  padding: 0.8em; background: white; }
.entries        { list-style: none; margin: 0; padding: 0; }
.entries li     { margin: 0.8em 1.2em; }
.entries li h2  { margin-left: -1em; }
.add-entry      { font-size: 0.9em; border-bottom: 1px solid #ccc; }
.add-entry dl   { font-weight: bold; }
.metanav        { text-align: right; font-size: 0.8em; padding: 0.3em;
                  margin-bottom: 1em; background: #fafafa; }
.flash          { background: #CEE5F5; padding: 0.5em;
                  border: 1px solid #AACBE2; }
.error          { background: #F0D6D6; padding: 0.5em; }

在controller目錄下新建blog_message.py文件

其實也就是接口文件= =

#!/usr/bin/env python3
# _*_ coding: utf-8 _*_
# @Time  : 2020/3/13 11:32
# @Author: ChenZIDu
# @File  : blog_message.py

from blog.model.User import User
from blog.model.Category import Category
import os

from blog import app,db
from flask import request,render_template,flash,abort,url_for,redirect,session,Flask,g

@app.route('/')
def show_entries(): # 從數據庫查詢出文章的標題和正文。
    categorys = Category.query.all()
    return render_template('show_entries.html',entries=categorys)

@app.route('/add',methods=['POST'])
def add_entry():
    if not session.get('logged_in'):
        abort(401)      # 請求到此即中斷,不會打印下面的語句,並返回HTTP狀態碼401
    title = request.form['title']
    content = request.form['text']
    category = Category(title, content)
    db.session.add(category)
    db.session.commit()
    flash('New entry was successfully posted')
    return redirect(url_for('show_entries'))

@app.route('/login',methods=['GET','POST'])
def login():
    error = None
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        user = User.query.filter_by(username=request.form['username']).first()
        passwd = User.query.filter_by(password = request.form['password']).first()

        if user is None:
            error = 'Invalid username'
        elif password is None:
            error = 'Invalid password'
        else:
            session['logged_in'] = True
            flash('You were logged in')
            return redirect(url_for('show_entries'))    #url_for() 來針對一個特定的函數構建一個 URL
    return render_template('login.html', error=error)

@app.route('/logout')
def logout():
    session.pop('logged_in', None)
    flash('You were logged out')
    return redirect(url_for('show_entries'))

在__init__.py文件中引入模塊(要在app聲明後=.=)

from blog.controller import blog_manage

然後就可以運行試試水了~

跟隨茁壯的小草大佬

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章