Flask connection mysql, implement page login

主要代码:
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 'the User: S%'% the self.name
db.create_all ()

@ app.route ( '/ Login', Methods = [ 'the POST', 'the GET'])
DEF Login ():
IF request.method == ' the POST ':
name = Request.Form [' User ']
password = Request.Form [' the passwd ']
from SQLAlchemy # import and_ introduced and_ query
cursor = User.query.filter (and_ (User.name == name, User . .password == password)) first ( ) # query the database, first () returns the first result of a query, if there is no return None
IF iS not the Cursor None:
the session [ 'the User'] = name
Flash ( 'the Login successfully! ')
return the redirect (the url_for (' index '), 302)
the else:
Flash ('! SUCH User No ',' 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 %}


Guess you like

Origin www.cnblogs.com/hnsya/p/11543756.html