Flask连接mysql,实现页面登录
Posted hnsya
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flask连接mysql,实现页面登录相关的知识,希望对你有一定的参考价值。
主要代码:
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 %
以上是关于Flask连接mysql,实现页面登录的主要内容,如果未能解决你的问题,请参考以下文章
怎么用flask+mysql来实现一个简单的用户注册和登陆效果的页面