代码改变世界

Flask连接mysql,实现页面登录

2019-09-18 17:11  hn3ya  阅读(1602)  评论(0编辑  收藏  举报
主要代码:
from flask import Flask,request,g,session,flash,redirect,url_for,render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:12345678@localhost/mydb'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class User(db.Model):
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False)
name = db.Column(db.String(20), nullable=False)
password = db.Column(db.String(30), nullable=False)
def __repr__(self):
return 'User:%s'%self.name
db.create_all()

@app.route('/login',methods=['POST','GET'])
def login():
if request.method == 'POST':
name = request.form['user']
password = request.form['passwd']
from sqlalchemy import and_#导入and_ 与查询
cursor = User.query.filter(and_(User.name==name,User.password==password)).first()#查询数据库,first()返回查询的第一个结果,如果没有返回None
if cursor is not None:
session['user'] = name
flash('Login successfully!')
return redirect(url_for('index'),302)
else:
flash('No such user!','error')
return redirect(url_for('login'),302)
else:
return render_template('login.html')

@app.route('/')
def index():
if 'user' in session:
return render_template('hello.html', name=session['user'])
else:
return redirect(url_for('login'),302)
@app.route('/logout')
def logout():
session.pop('user', None)
return redirect(url_for('login'), 302)
app.secret_key = '12345678'
if __name__ == '__main__':
app.run(host='127.0.0.1', debug=True)

页面HTML:
{% extends "layout.html" %}
{% block body %}
<form name="login" action="/login" method="post">
Username: <input type="text" name="user" /><br>
Password: <input type="password" name="passwd" /><br>
<input type="submit" value="Submit" />
</form>
{% endblock %}