from flask import Flask,request,render_template,session,Response from functools import wraps import sqlite3,os
from flask_wtf import FlaskForm from wtforms import widgets,validators from wtforms.validators import DataRequired,Regexp,DataRequired, Length, Email, EqualTo, NumberRange from wtforms.fields import (StringField, PasswordField, DateField, BooleanField,DateTimeField,TimeField, SelectField, SelectMultipleField, TextAreaField,FloatField,HiddenField, RadioField, IntegerField, DecimalField, SubmitField, IntegerRangeField)
app = Flask(__name__)
app.config["SECRET_KEY"] = "d3d3Lmx5c2hhcmsuY29t"
def UserDB(): conn = sqlite3.connect("database.db") cursor = conn.cursor() create = "create table UserDB(" \ "uid INTEGER primary key AUTOINCREMENT not null unique," \ "username char(64) not null unique," \ "password char(64) not null," \ "email char(64) not null" \ ")" cursor.execute(create) conn.commit() cursor.close() conn.close()
def RunSqlite(db,table,action,field,value): connect = sqlite3.connect(db) cursor = connect.cursor()
if action == "insert": insert = f"insert into {table}({field}) values({value});" if insert == None or len(insert) == 0: return False try: cursor.execute(insert) except Exception: return False
elif action == "update": update = f"update {table} set {value} where {field};" if update == None or len(update) == 0: return False try: cursor.execute(update) except Exception: return False
elif action == "select":
if value == "none": select = f"select {field} from {table};" else: select = f"select {field} from {table} where {value};"
try: ref = cursor.execute(select) ref_data = ref.fetchall() connect.commit() connect.close() return ref_data except Exception: return False
elif action == "delete": delete = f"delete from {table} where {field};" if delete == None or len(delete) == 0: return False try: cursor.execute(delete) except Exception: return False try: connect.commit() connect.close() return True except Exception: return False
class RegisterForm(FlaskForm): username = StringField( validators=[ DataRequired(message='用户名不能为空'), Length(min=1, max=15, message='用户名长度必须大于%(min)d且小于%(max)d') ], widget=widgets.TextInput(), render_kw={'class': 'form-control', "placeholder":"输入注册用户名"} ) email = StringField( validators=[validators.DataRequired(message='邮箱不能为空'),validators.Email(message="邮箱格式输入有误")], render_kw={'class':'form-control', "placeholder":"输入Email邮箱"} ) password = PasswordField( validators=[ validators.DataRequired(message='密码不能为空'), validators.Length(min=5, message='用户名长度必须大于%(min)d'), validators.Regexp(regex="[0-9a-zA-Z]{5,}",message='密码不允许使用特殊字符') ], widget=widgets.PasswordInput(), render_kw={'class': 'form-control', "placeholder":"输入用户密码"} ) RepeatPassword = PasswordField( validators=[ validators.DataRequired(message='密码不能为空'), validators.Length(min=5, message='密码长度必须大于%(min)d'), validators.Regexp(regex="[0-9a-zA-Z]{5,}",message='密码不允许使用特殊字符'), validators.EqualTo("password",message="两次密码输入必须一致") ], widget=widgets.PasswordInput(), render_kw={'class': 'form-control', "placeholder":"再次输入密码"} ) submit = SubmitField( label="用 户 注 册", render_kw={ "class":"btn btn-success" } )
class LoginForm(FlaskForm): username = StringField( validators=[ validators.DataRequired(message=''), validators.Length(min=4, max=15, message=''), validators.Regexp(regex="[0-9a-zA-Z]{4,15}", message='') ], widget=widgets.TextInput(), render_kw={"class":"form-control", "placeholder":"请输入用户名或电子邮件"} ) password = PasswordField( validators=[ validators.DataRequired(message=''), validators.Length(min=5, max=15,message=''), validators.Regexp(regex="[0-9a-zA-Z]{5,15}",message='') ], widget=widgets.PasswordInput(), render_kw={"class":"form-control", "placeholder":"请输入密码"} )
@app.route("/create") def create(): UserDB() return "create success"
def login_required(func): @wraps(func) def wrapper(*args, **kwargs): if session.get("username") != None and session.get("is_login") ==True: print("登陆过则继续执行原函数") return func(*args, **kwargs) else: print("没有登录则跳转到登录页面") resp = Response() resp.status_code=200 resp.data = "<script>window.location.href='/login';</script>" return resp return wrapper
@app.route("/register",methods=["GET","POST"]) def register(): form = RegisterForm(csrf_enabled = True)
if request.method == "POST": if form.validate_on_submit(): username = form.username.data password = form.RepeatPassword.data email = form.email.data print("用户: {} 邮箱: {}".format(username,email))
if RunSqlite("database.db", "UserDB", "select", "username", f"username='{username}'") == []: insert = RunSqlite("database.db", "UserDB", "insert", "username,password,email", f"'{username}','{password}','{email}'") if insert == True: return "创建完成" else: return "创建失败" else: return "用户存在"
return render_template("register.html", form=form)
@app.route("/login",methods=["GET","POST"]) def login(): form = LoginForm(csrf_enabled = True)
if request.method == "POST": username = form.username.data password = form.password.data
select = RunSqlite("database.db","UserDB","select","username,password",f"username='{username}'") if select != []: if select[0][1] == password: session["username"] = username session["is_login"] = True
print("登录完成直接跳到主页") resp = Response() resp.status_code = 200 resp.data = "<script>window.location.href='/index';</script>" return resp else: return "密码不正确" else: return "用户不存在"
return render_template("login.html", form=form)
@app.route("/modify",methods=["GET","POST"]) @login_required def modify(): if request.method == "GET": html = """ <form action="/modify" method="post"> <p>新密码: <input type="password" name="new_password"></p> <input type="submit" value="修改密码"> </form> """ return html
if request.method == "POST": username = session.get("username") new_password = request.form.get("new_password") update = RunSqlite("database.db","UserDB","update",f"username='{username}'",f"password='{new_password}'") if update == True: session.pop("username") session.pop("is_login") session.clear()
print("密码已更新,请重新登录") resp = Response() resp.status_code = 200 resp.data = "<script>window.location.href='/login';</script>" return resp else: return "密码更新失败" return "未知错误"
@app.route("/index",methods = ["GET","POST"]) @login_required def index(): username = session.get("username") return "用户 {} 您好,这是主页面".format(username)
@app.route("/get",methods = ["GET","POST"]) @login_required def get(): username = session.get("username") return "用户 {} 您好,这是子页面".format(username)
@app.route("/logout",methods = ["GET","POST"]) @login_required def logout(): username = session.get("username")
session.pop("username") session.pop("is_login") session.clear() return "用户 {} 已注销".format(username)
if __name__ == '__main__': app.run(debug=True)
|