《Flask web开发》笔记4:数据库
一、实现功能:通过web表单生成登录界面、当输入的用户名不在后台数据库里时,加进去;在时,显示Happy see you again样式;
1.数据库引擎:MySQL (安装没有要求路径,我是用之前的没动)
2.数据库框架: Flask-SQLAlchemy(书上推荐,直接pip install Flask-SQLAlchemy 就行)
二、 Flask-SQLAlchemy建一个简单的表:
aa.py:
# coding: utf-8 from flask import Flask from flask_script import Manager from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root@localhost/yxctest' #MySQL数据库UILmysql://username:password@hostname/database app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True#实时更新 db = SQLAlchemy(app) #实例化db manager = Manager(app) class User(db.Model): __tablename__ = 'users' #表名 id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(320), unique=True) password = db.Column(db.String(32), nullable=False) def __repr__(self): return '<User %r>' % self.username if __name__ == '__main__': manager.run()
然后在doc输入 Python aa.py shell
接着就可以对这个表进行操作了:
from aa import db、from aa import User、db.create_all()、user1 = User(username = 'yxc',email='123@qq.com',password='123123')
以上都是doc指令,功能是导入、建表、插入行等;
三、实现步骤一中的功能:
很简单,就把这次的建数据库的代码和上一节建Web表单合并一下:
bb.py:
# coding: utf-8 import sys reload(sys) sys.setdefaultencoding('utf-8') from flask import Flask, render_template,url_for,session,redirect,flash from flask_script import Manager from flask_bootstrap import Bootstrap from flask_moment import Moment from flask_wtf import Form from wtforms import StringField, SubmitField from wtforms.validators import Required from flask_sqlalchemy import SQLAlchemy #这里导入框架 app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root@localhost/yxctest' #自己的MySQL账户和建立的表 app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True #app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True db = SQLAlchemy(app) #db实例 bootstrap = Bootstrap(app) app.secret_key = '1234567' class NameForm(Form): #Web表中定义的几个片段 name = StringField('What is your name?', validators=[Required()]) email = StringField('What is your email', validators=[Required()]) password = StringField('What is your password', validators=[Required()]) submit= SubmitField('Submit') class User(db.Model): #定义的数据库的表 __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(320), unique=True) password = db.Column(db.String(32), nullable=False) def __repr__(self): return '<User %r>' % self.username @app.route('/', methods=['GET', 'POST']) def index(): form = NameForm() if form.validate_on_submit: user = User.query.filter_by(username = form.name.data).first()#查询语句,精确查询输入的name和数据库表中的name比对 if user is None: user = User(username = form.name.data,email=form.email.data,password=form.password.data)#如果不存在,则插入一行 db.session.add(user) db.session.commit()#这两行是必须的 session['known'] = False else: session['known'] = True session['name']=form.name.data form.name.data = '' return render_template('index.html',form=form,name=session.get('name'),known = session.get('known',False)) if __name__ == '__main__': app.run(debug=True)
当然我们的模板渲染也得改一下:
index.html:
{% extends "bootstrap/base.html" %} {% import "bootstrap/wtf.html" as wtf %} {% block title %}TTTTT{% endblock %} {% block content %} <div class="container"> <div class="page-header"> <h1>Hello, {% if name %}{{ name }}{% else %}Stranger{% endif %}!</h1> {%if not known%} <p>Please meet you</p> {%else%} <p>Happy see you again</p> {%endif%} </div> </div> {{ wtf.quick_form(form) }} {% endblock %}
效果: