Flask 로그인 및 등록(mysql,session 및 두 개의 갈고리before request 및 context processor)

24963 단어 학습 노트flask
요컨대 먼저 html을 쓰다
ral.html
<form action="/login" method="post" name="login">
        
        <h1>  h1>
        <table>
            <tr>
                <td>   :td>
                <td><input type="text" name="username">td>
            tr>
            <tr>
                <td>  :td>
                <td><input type="password" name="password">td>
            tr>
            <input type="submit" value="  ">
        table>
        <hr>
    form>
    <form action="/register" method="post" name="register">
        
        <h1>  h1>
        <table>
            <tr>
                <td>   :td>
                <td><input type="text" name="susername">td>
            tr>
            <tr>
                <td>  :td>
                <td><input type="password" name="spassword">td>
            tr>
            <input type="submit" value="  ">
        table>
        <hr>
    form>

emmmm, html 이 부분은 어렵지 않을 것이다. 어쨌든 매우 초라하게 썼기 때문이다.
로그인한 html 하나 더 주세요.
log.html
<h1>    {{ username }}h1>

emmm, 괜찮아, 이렇게 하면 차이가 많지 않아.
우리 Py를 시작하겠습니다.
from flask import Flask
from flask import Flask, render_template, redirect, url_for, flash, request,session,g
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import and_
from flask_wtf.csrf import CSRFProtect
import os

app = Flask(__name__)

app.config['SECRET_KEY'] = "afsfa"
CSRFProtect(app)
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:[email protected]:3306/userdata"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

db = SQLAlchemy(app)


class User(db.Model):
	#       。
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(128), unique=True)
    password = db.Column(db.String(128), unique=False)


@app.route('/login', methods=['POST'])
def login():
    username = request.form.get('username')
    password = request.form.get('password')
    user = User.query.filter(and_(User.username == username, User.password == password)).first()
    if user:
        session['username'] = username
        session['password'] = password
        return redirect(url_for('lsuss'))
    else:
        return '        '


@app.route('/if_login', methods=['GET'])
def lsuss():
    print(g.username)
    if g.username:
        return render_template('log.html')
    else:
        return render_template('ral.html')


@app.route('/register', methods=['POST'])
def register():
    username = request.form.get('susername')
    password = request.form.get('spassword')
    user = User(username=username, password=password)
    db.session.add(user)
    db.session.commit()
    return redirect(url_for('ral'))


@app.before_request
def test():
    username = session.get('username')
    password = session.get('password')
    g.username = None
    if username:
        user = User.query.filter(and_(User.username == username, User.password == password)).first()
        if user:
            g.username = username


@app.context_processor
def name():
    username = session.get('username')
    return {'username': username}


db.drop_all()
db.create_all()


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


코드를 다시 편집해서 주석을 쓰고 싶지 않습니다 =

좋은 웹페이지 즐겨찾기