from flask import Flask,render_template,request,redirect,url_for,session
from flask_sqlalchemy import SQLAlchemy
import config
app = Flask(__name__)
app.config.from_object("config")
db=SQLAlchemy(app)
class User(db.Model):
__tablename__ = "user"
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
username = db.Column(db.String(20),nullable=False)
password = db.Column(db.String(20),nullable=False)
nickname = db.Column(db.String(20))
#db.create_all()
@app.route('/')
def vi():
return render_template("base.html")
@app.route('/first')
def first():
return render_template("first.html")
@app.route("/login",methods=["GET","POST"])
def login():
if request.method == "GET":
return render_template("login.html")
else:
usern = request.form.get("usern")
passw = request.form.get("userp")
user = User.query.filter(User.username==usern).first()
if user:
if user.password == passw:
session["user"] = usern
# session.permanent = True
return redirect(url_for("first"))
else:
return "密码错误,请重新输入!"
else:
return "用户名不存在!"
@app.route("/regist",methods=["GET","POST"])
def regist():
if request.method == "GET":
return render_template("regist.html")
else:
usern1 = request.form.get("newn")
passw1 = request.form.get("newp")
user = User.query.filter(User.username==usern1).first()
if user:
return "用户名已存在!"
else:
user = User(username = usern1,password = passw1)
db.session.add(user)
db.session.commit()
return redirect(url_for("login"))
@app.context_processor
def context():
usern=session.get("user")
if usern:
return{'username':usern}
else:
return {}
@app.route('/clear')
def clear():
session.clear()
return redirect(url_for('first'))
if __name__ == '__main__':
app.run(debug=True)
import os
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:@127.0.0.1:3306/mis_db?charset=utf8'
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.urandom(24)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}{% endblock %}宋茜后援团</title>
<link href="../static/css/vv.css" rel="stylesheet" type="text/css">
<script src="{{url_for("static",filename="js/change.js")}}"> </script>
{% block head %}{% endblock %}
</head>
<body id="myBody">
<nav class="nav">
<a href="{{ url_for("first")}}">首页</a>
<a href="">下载</a>
<input type="text" name="search">
<button type="submit">搜索</button>
{% if username %}
<a href="#">{{ username }}</a>
<a href="{{ url_for('clear') }}">注销</a>
{% else %}
<a href="{{ url_for("login")}}">登录</a>
<a href="{{ url_for("regist")}}">注册</a>
{% endif %}
<img id="on_off" onclick="change()" src="{{ url_for("static",filename="images/on.jpg") }}" width="30px">
</nav>
{% block main %}{% endblock %}
<div class="box">
<a href="" class="nav"><span>关于我们</span></a>
<a href="" class="nav"><span>意见反馈</span></a>
<a href="" class="nav"><span>安全保障</span></a>
</div>
</body>
</html>