Flask(三)

 

一.wtforms

安裝:pip3 install wtformshtml

用法一:html5

from flask import Flask, render_template, request, redirect
from wtforms import Form
from wtforms.fields import simple
from wtforms import validators
from wtforms import widgets

app = Flask(__name__, template_folder='templates')

app.debug = True


class LoginForm(Form):
    # 字段(內部包含正則表達式)
    name = simple.StringField(
        label='用戶名',
        validators=[
            validators.DataRequired(message='用戶名不能爲空.'),
            validators.Length(min=6, max=18, message='用戶名長度必須大於%(min)d且小於%(max)d')
        ],
        widget=widgets.TextInput(), # 頁面上顯示的插件
        render_kw={'class': 'form-control'}

    )
    # 字段(內部包含正則表達式)
    pwd = simple.PasswordField(
        label='密碼',
        validators=[
            validators.DataRequired(message='密碼不能爲空.'),
            validators.Length(min=8, message='用戶名長度必須大於%(min)d'),
            validators.Regexp(regex="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}",
                              message='密碼至少8個字符,至少1個大寫字母,1個小寫字母,1個數字和1個特殊字符')

        ],
        widget=widgets.PasswordInput(),
        render_kw={'class': 'form-control'}
    )



@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        form = LoginForm()
        return render_template('login.html', form=form)
    else:
        form = LoginForm(formdata=request.form)
        if form.validate():
            print('用戶提交數據經過格式驗證,提交的值爲:', form.data)
        else:
            print(form.errors)
        return render_template('login.html', form=form)

if __name__ == '__main__':
    app.run()

login.html:python

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>登陸</h1>
<form method="post">
    <p>{{form.name.label}} {{form.name}} {{form.name.errors[0] }}</p>

    <p>{{form.pwd.label}} {{form.pwd}} {{form.pwd.errors[0] }}</p>
    <input type="submit" value="提交">
</form>
</body>
</html>

用法二:mysql

from flask import Flask, render_template, request, redirect
from wtforms import Form
from wtforms.fields import core
from wtforms.fields import html5
from wtforms.fields import simple
from wtforms import validators
from wtforms import widgets

app = Flask(__name__, template_folder='templates')
app.debug = True



class RegisterForm(Form):
    name = simple.StringField(
        label='用戶名',
        validators=[
            validators.DataRequired()
        ],
        widget=widgets.TextInput(),
        render_kw={'class': 'form-control'},
        default='cxw'
    )

    pwd = simple.PasswordField(
        label='密碼',
        validators=[
            validators.DataRequired(message='密碼不能爲空.')
        ],
        widget=widgets.PasswordInput(),
        render_kw={'class': 'form-control'}
    )

    pwd_confirm = simple.PasswordField(
        label='重複密碼',
        validators=[
            validators.DataRequired(message='重複密碼不能爲空.'),
            validators.EqualTo('pwd', message="兩次密碼輸入不一致")
        ],
        widget=widgets.PasswordInput(),
        render_kw={'class': 'form-control'}
    )

    email = html5.EmailField(
        label='郵箱',
        validators=[
            validators.DataRequired(message='郵箱不能爲空.'),
            validators.Email(message='郵箱格式錯誤')
        ],
        widget=widgets.TextInput(input_type='email'),
        render_kw={'class': 'form-control'}
    )

    gender = core.RadioField(
        label='性別',
        choices=(
            (1, ''),
            (2, ''),
        ),
        #這句話的意思是上面的choices元組的第一個值是int類型
        #若是上上面爲(‘1’, '男'),(‘2’, '女'),則下面的coerce則不用寫
        coerce=int # 「1」 「2」
     )
    #這裏是單選框
    city = core.SelectField(
        label='城市',
        choices=(
            ('bj', '北京'),
            ('sh', '上海'),
        )
    )
    #這裏是多選框
    hobby = core.SelectMultipleField(
        label='愛好',
        choices=(
            (1, '籃球'),
            (2, '足球'),
        ),
        coerce=int
    )
    #這裏是多選的checkbox
    favor = core.SelectMultipleField(
        label='喜愛',
        choices=(
            (1, '籃球'),
            (2, '足球'),
        ),
        widget=widgets.ListWidget(prefix_label=False),
        option_widget=widgets.CheckboxInput(),
        coerce=int,
        default=[1, 2]
    )
    #這裏能夠改值
    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)
        self.favor.choices = ((1, '籃球'), (2, '足球'), (3, '羽毛球'))

    def validate_pwd_confirm(self, field):
        """
        自定義pwd_confirm字段規則,例:與pwd字段是否一致
        :param field:
        :return:
        """
        # 最開始初始化時,self.data中已經有全部的值

        if field.data != self.data['pwd']:
            # raise validators.ValidationError("密碼不一致") # 繼續後續驗證
            raise validators.StopValidation("密碼不一致")  # 再也不繼續後續驗證


@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        #這裏能夠傳默認值
        form = RegisterForm(data={'gender': 2,'hobby':[1,]}) # initial
        return render_template('register.html', form=form)
    else:
        form = RegisterForm(formdata=request.form)
        if form.validate():
            print('用戶提交數據經過格式驗證,提交的值爲:', form.data)
        else:
            print(form.errors)
        return render_template('register.html', form=form)



if __name__ == '__main__':
    app.run()

register.html正則表達式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>用戶註冊</h1>
<form method="post" novalidate style="padding:0  50px">
    {% for field in form %}
    <p>{{field.label}}: {{field}} {{field.errors[0] }}</p>
    {% endfor %}
    <input type="submit" value="提交">
</form>
</body>
</html>

二.多app應用redis

from werkzeug.wsgi import DispatcherMiddleware
from werkzeug.serving import run_simple
from flask import Flask, current_app
app1 = Flask('app01')
app2 = Flask('app02')

@app1.route('/index')
def index():
    return "app01"

@app2.route('/index2')
def index2():
    return "app2"

# http://www.oldboyedu.com/index
# http://www.oldboyedu.com/sec/index2
dm = DispatcherMiddleware(app1, {
    '/sec': app2,
})

if __name__ == "__main__":
    run_simple('localhost', 5000, dm)

三.flask-script (manage.py就是當前要執行的文件)sql

from flask import Flask,request
from flask_script import Manager
app = Flask(__name__)
manager=Manager(app)

@app.route("/")
def index():
    return "ok"


if __name__ == '__main__':
    manager.run()
#之後在執行,直接:python3 manage.py runserver
#python3 manage.py runserver --help

自定義命令:數據庫

from flask import Flask
from flask_script import Manager
app = Flask(__name__)
manager=Manager(app)

@app.route("/")
def index():
    return "ok"

@manager.command
def custom1(arg):
    """
    自定義命令
    python manage.py custom 123
    :param arg:
    :return:
    """
    print(arg)


@manager.option('-n', '--name', dest='name')
@manager.option('-u', '--url', dest='url')
def cmd(name, url):
    """
    自定義命令(-n也能夠寫成--name)
    執行: python manage.py  cmd -n lqz -u http://www.oldboyedu.com
    執行: python manage.py  cmd --name lqz --url http://www.oldboyedu.com
    :param name:
    :param url:
    :return:
    """
    print(name, url)
#有什麼用?
#把excel的數據導入數據庫,定製個命令,去執行

if __name__ == '__main__':
    manager.run()

 

四.SQLAlchemy

介紹

SQLAlchemy是一個基於Python實現的ORM框架。該框架創建在 DB API之上,使用關係對象映射進行數據庫操做,簡言之即是:將類和對象轉換成SQL,而後使用數據API執行SQL並獲取執行結果。django

pip3 install sqlalchemy

組成部分:flask

Engine,框架的引擎
Connection Pooling ,數據庫鏈接池
Dialect,選擇鏈接數據庫的DB API種類
Schema/Types,架構和類型
SQL Exprression Language,SQL表達式語言

SQLAlchemy自己沒法操做數據庫,其必須以來pymsql等第三方插件,Dialect用於和數據API進行交流,根據配置文件的不一樣調用不一樣的數據庫API,從而實現對數據庫的操做,如:

MySQL-Python
    mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname>
    
pymysql
    mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]
    
MySQL-Connector
    mysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname>
    
cx_Oracle
    oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...]
    
更多:http://docs.sqlalchemy.org/en/latest/dialects/index.html

建立表模型,初始化和刪除表,不可修改字段:

import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import  relationship
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Text, ForeignKey, DateTime, UniqueConstraint, Index
Base = declarative_base()

class Users(Base):
    __tablename__ = 'users'  # 數據庫表名稱
    id = Column(Integer, primary_key=True)  # id 主鍵,autoincrement
    name = Column(String(32), index=True, nullable=False)  # name列,索引,不可爲空
    age =Column(Integer,default=0)
    def __repr__(self):
        return self.name +"_"+str(self.id)
    #email = Column(String(32), unique=True)
    # #datetime.datetime.now不能加括號,加了括號,之後永遠是當前時間
    # ctime = Column(DateTime, default=datetime.datetime.now)
    # extra = Column(Text, nullable=True)

    # __table_args__ = (
    #     UniqueConstraint('id', 'name', name='uix_id_name'), #聯合惟一
    #     Index('ix_id_name', 'name', 'email'), #索引
    # )
#
class use1(Base):
    __tablename__ = 'users1'  # 數據庫表名稱
    ids = Column(Integer, primary_key=True)  # id 主鍵,autoincrement
    names = Column(String(32), index=True, nullable=False)  #


class Hobby(Base):
    __tablename__ = 'hobby'
    id = Column(Integer, primary_key=True)
    caption = Column(String(50), default='籃球')


class Person(Base):
    __tablename__ = 'person'
    nid = Column(Integer, primary_key=True)
    name = Column(String(32), index=True, nullable=True)
    # hobby指的是tablename而不是類名,uselist=False
    hobby_id = Column(Integer, ForeignKey("hobby.id"))

    # 跟數據庫無關,不會新增字段,只用於快速鏈表操做
    # 類名,backref用於反向查詢
    hobby = relationship('Hobby', backref='pers')


class Boy2Girl(Base):
    __tablename__ = 'boy2girl'
    id = Column(Integer, primary_key=True, autoincrement=True)
    girl_id = Column(Integer, ForeignKey('girl.id'))
    boy_id = Column(Integer, ForeignKey('boy.id'))


class Girl(Base):
    __tablename__ = 'girl'
    id = Column(Integer, primary_key=True)
    name = Column(String(64), unique=True, nullable=False)


class Boy(Base):
    __tablename__ = 'boy'

    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(64), unique=True, nullable=False)
    # 與生成表結構無關,僅用於查詢方便,放在哪一個單表中均可以
    girl = relationship('Girl', secondary='boy2girl', backref='boys')


def init_db1():
    """
    根據類建立數據庫表
    :return:
    """
    engine = create_engine(
        "mysql+pymysql://root:root@127.0.0.1:3306/aaa?charset=utf8",
        max_overflow=0,  # 超過鏈接池大小外最多建立的鏈接
        pool_size=5,  # 鏈接池大小
        pool_timeout=30,  # 池中沒有線程最多等待的時間,不然報錯
        pool_recycle=-1  # 多久以後對線程池中的線程進行一次鏈接的回收(重置)
    )

    Base.metadata.create_all(engine)

def drop_db():
    """
    根據類刪除數據庫表
    :return:
    """
    engine = create_engine(
        "mysql+pymysql://root:root@127.0.0.1:3306/aaa?charset=utf8",
        max_overflow=0,  # 超過鏈接池大小外最多建立的鏈接
        pool_size=5,  # 鏈接池大小
        pool_timeout=30,  # 池中沒有線程最多等待的時間,不然報錯
        pool_recycle=-1  # 多久以後對線程池中的線程進行一次鏈接的回收(重置)
    )

    Base.metadata.drop_all(engine)

if __name__ == '__main__':
    #drop_db()
    init_db1()

orm操做及線程安全scoped_session::

from sqlalchemy.orm import sessionmaker,scoped_session
from sqlalchemy import create_engine
from models import Users

engine = create_engine("mysql+pymysql://root:root@127.0.0.1:3306/aaa", max_overflow=0, pool_size=5)
Session = sessionmaker(bind=engine)

"""
# 線程安全,基於本地線程實現每一個線程用同一個session
# 特殊的:scoped_session中有原來方法的Session中的一下方法:

public_methods = (
    '__contains__', '__iter__', 'add', 'add_all', 'begin', 'begin_nested',
    'close', 'commit', 'connection', 'delete', 'execute', 'expire',
    'expire_all', 'expunge', 'expunge_all', 'flush', 'get_bind',
    'is_modified', 'bulk_save_objects', 'bulk_insert_mappings',
    'bulk_update_mappings',
    'merge', 'query', 'refresh', 'rollback',
    'scalar'
)
"""
#scoped_session類並無繼承Session,可是卻又它的全部方法
session = scoped_session(Session)

# ############# 執行ORM操做 #############
obj1 = Users(name="lqz")
session.add(obj1)

# 提交事務
session.commit()
# 關閉session
session.close()

單表增刪改查:

import time
import threading
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine
from sqlalchemy.sql import text

from models import Users,use1

engine = create_engine("mysql+pymysql://root:root@127.0.0.1:3306/aaa", max_overflow=0, pool_size=5)
Session = sessionmaker(bind=engine)

session = Session()

# ################ 添加 ################
#
# obj1 = Users(name="wupeiqi",age=19)
# session.add(obj1)
#
# session.add_all([
#     Users(name="lqz",age=18),
#     Users(name="egon",age=20),
#     use1(names="c1.com"),
# ])
# session.commit()



# ################ 刪除 ################

# session.query(Users).filter(Users.id > 4).delete()
# session.commit()

# ################ 修改 ################

#傳字典
# session.query(Users).filter(Users.id > 0).update({"name" : "lqz"})
#相似於django的F查詢,這個後面必須配合synchronize_session,
#若是是字符串就用False,若是是數字就用#evaluata
# session.query(Users).filter(Users.id > 0).update({Users.name: Users.name + "099"}, synchronize_session=False)
# session.query(Users).filter(Users.id > 0).update({"age": Users.age + 1}, synchronize_session="evaluate")
# session.commit()

# ################ 查詢 ################

# r1 = session.query(Users).all()
# print(r1[0].name)
#只取age列,把name重命名爲xx
# r2 = session.query(Users.name.label('xx'), Users.age).all()
# print(r2[0].xx)
#filter傳的是表達式,filter_by傳的是參數
# r3 = session.query(Users).filter(Users.name == "lqz").all()
# print(r3[0].name)
# r4 = session.query(Users).filter_by(name='lqz').all()
# print(r4[0].name)
# r5 = session.query(Users).filter_by(name='lqz').first()
# print(r5.name)
#:value 和:name 至關於佔位符,用params傳參數
# r6 = session.query(Users).filter(text("id<:value and name=:name")).params(value=224, name='fred').order_by(Users.id).all()
#自定義查詢sql
#r7 = session.query(Users).from_statement(text("SELECT * FROM users where name=:name")).params(name='ed').all()



# 條件
# ret = session.query(Users).filter_by(name='lqz').all()
#表達式,and條件鏈接
# ret = session.query(Users).filter(Users.id > 2, Users.name == 'lqz').all()
# print(ret[0].name,ret[0].id)

# ret = session.query(Users).filter(Users.id.between(1, 3)).all()
# print(ret)
#注意下劃線
# ret = session.query(Users).filter(Users.id.in_([1,3,4])).all()
# print(ret)
#~非,除。。外
# ret = session.query(Users).filter(~Users.id.in_([1,3,4])).all()
# print(ret)
#二次篩選
# ret = session.query(Users).filter(Users.id.in_(session.query(Users.id).filter(Users.name=='lqz'))).all()
# print(ret)
from sqlalchemy import and_, or_
#or_包裹的都是or條件,and_包裹的都是and條件
# ret = session.query(Users).filter(and_(Users.id > 3, Users.name == 'lqz')).all()

# ret = session.query(Users).filter(or_(Users.id < 2, Users.name == 'lqz')).all()
# print(ret)
# ret = session.query(Users).filter(
#     or_(
#         Users.id < 2,
#         and_(Users.name == 'eric', Users.id > 3),
#         Users.extra != ""
#     )).all()


# 通配符,以e開頭,不以e開頭  (_表明佔位)
# ret = session.query(Users).filter(Users.name.like('_u%')).all()
# print(ret)
# ret = session.query(Users).filter(~Users.name.like('e%')).all()

# 限制,用於分頁,區間
# ret = session.query(Users).all()[1:2]
# print(ret)

# 排序,根據name降序排列(從大到小)
# ret = session.query(Users).order_by(Users.name.desc()).all()
#第一個條件重複後,再按第二個條件升序排
# ret = session.query(Users).order_by(Users.name.desc(), Users.id.asc()).all()
# print(ret)

# 分組
# from sqlalchemy.sql import func
#
# ret = session.query(Users).group_by(Users.name).all()
# print(ret)
#分組以後取最大id,id之和,最小id
# ret = session.query(
#     func.max(Users.id),
#     func.sum(Users.id),
#     func.min(Users.id)).group_by(Users.name).all()
# print(ret)
#haviing篩選
# ret = session.query(
#     func.max(Users.id),
#     func.sum(Users.id),
#     func.min(Users.id)).group_by(Users.name).having(func.min(Users.id) >2).all()
# print(ret)

#增,刪,改都要commit()
session.close()

一對多: 一個愛好對應多我的

class Hobby(Base):
    __tablename__ = 'hobby'
    id = Column(Integer, primary_key=True)
    caption = Column(String(50), default='籃球')


class Person(Base):
    __tablename__ = 'person'
    nid = Column(Integer, primary_key=True)
    name = Column(String(32), index=True, nullable=True)
    # hobby指的是tablename而不是類名,uselist=False
    hobby_id = Column(Integer, ForeignKey("hobby.id"))

    # 跟數據庫無關,不會新增字段,只用於快速鏈表操做
    # 類名,backref用於反向查詢
    hobby = relationship('Hobby', backref='pers')

基本操做

import time
import threading

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine
from sqlalchemy.sql import text
from sqlalchemy.engine.result import ResultProxy
from models import Users, Hobby, Person

engine = create_engine("mysql+pymysql://root:root@127.0.0.1:3306/aaa?charset=utf8", max_overflow=0, pool_size=5)
Session = sessionmaker(bind=engine)
session = Session()
# 添加一

# session.add_all([
#     Hobby(caption='乒乓球'),
#     Hobby(caption='羽毛球'),
#     Person(name='張三', hobby_id=1),
#     Person(name='李四', hobby_id=2),
# ])

# person = Person(name='張九', hobby=Hobby(caption='姑娘'))
# session.add(person)
#添加二
# hb = Hobby(caption='人妖')
# hb.pers = [Person(name='文飛'), Person(name='博雅')]
# session.add(hb)
#
# session.commit()


# 使用relationship正向查詢

# v = session.query(Person).filter(Person.hobby_id==4).first()
# print(v.name)
# print(v.hobby.caption)


# 使用relationship反向查詢

# v = session.query(Hobby).filter(Hobby.id==4).first()
# print(v.caption)
# print(v.pers)

#方式一,本身鏈表
# person_list=session.query(Person).join(Hobby,isouter=True)

# ret = session.query(Person).join(Hobby,Person.nid == Hobby.id, isouter=True)
# print(ret)
# print(person_list)
# person_list=session.query(Person,Hobby).join(Hobby,isouter=True).all()
# for row in person_list:
#     # print(row.name,row.caption)
#     print(row[0].name,row[1].caption)

#方式二:經過relationship

# person_list=session.query(Person).all()
# for row in person_list:
#     print(row.name,row.hobby.caption)
#查詢喜歡姑娘的全部人
# obj=session.query(Hobby).filter(Hobby.id==1).first()
# persons=obj.pers


session.close()

多對多:

class Boy2Girl(Base):
    __tablename__ = 'boy2girl'
    id = Column(Integer, primary_key=True, autoincrement=True)
    girl_id = Column(Integer, ForeignKey('girl.id'))
    boy_id = Column(Integer, ForeignKey('boy.id'))


class Girl(Base):
    __tablename__ = 'girl'
    id = Column(Integer, primary_key=True)
    name = Column(String(64), unique=True, nullable=False)


class Boy(Base):
    __tablename__ = 'boy'

    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(64), unique=True, nullable=False)
    # 與生成表結構無關,僅用於查詢方便,放在哪一個單表中均可以
    girl = relationship('Girl', secondary='boy2girl', backref='boys')

基本操做:

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from models import Girl,Boy,Boy2Girl

engine = create_engine("mysql+pymysql://root:root@127.0.0.1:3306/aaa?charset=utf8", max_overflow=0, pool_size=5)
Session = sessionmaker(bind=engine)
session = Session()
# 添加

# session.add_all([
#     Girl(name='g_com1'),
#     Girl(name='g2.com1'),
#     Boy(name='A組1'),
#     Boy(name='B組2'),
# ])
# session.commit()
# '''
# s2g = Boy2Girl(girl_id=2, boy_id  =2)
# session.add(s2g)
# session.commit()
#
正向添加
# gp = Boy(name='C組')
# gp.girl = [Girl(name='c3.com'),Girl(name='c4.com')]
# session.add(gp)
# session.commit()
#
反向添加
# """
# ser = Girl(name='c6.com')
# ser.boys = [Boy(name='F組pp'),Boy(name='G組ll')]
# session.add(ser)
# session.commit()
#
# """
#
#
# # 使用relationship正向查詢
# """
# '''
# v = session.query(Boy).filter(Boy.id==2).first()
# print(v.name)
# print(v.girl)
# '''
# # 使用relationship反向查詢
#
# '''
# v = session.query(Girl).filter(Girl.id==3).first()
# print(v.name)
# print(v.boys[0].name)
#
#
# session.close()

五.flask_sqlalchemy和sql_migrate

sansa---------views--------------- |
   |           |                   |-----account.py
   |           |
manage.py      |----_init_.py
   |
| |
settings.py
| |----models.py

manage.py:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
生成依賴文件:
    pipreqs ./

"""
from sansa import create_app
from flask_script import Manager
from flask_migrate import Migrate,MigrateCommand
from sansa import db
app = create_app()
manager=Manager(app)

Migrate(app,db)
manager.add_command('db1', MigrateCommand)

if __name__ == '__main__':
    # app.run()
    manager.run()

init.py:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

from .models import *
from .views import account

def create_app():
    app = Flask(__name__)
    app.config.from_object('settings.DevelopmentConfig')

    # 將db註冊到app中
    db.init_app(app)

    # 註冊藍圖
    app.register_blueprint(account.account)


    return app

account.py:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

from flask import Blueprint
from .. import db
from .. import models

account = Blueprint('account', __name__)


@account.route('/login')
def login():
    db.session.add(models.Users(username='lqz', email='123'))
    db.session.query(models.Users).all()
    db.session.commit()
    # 添加示例
    """
    db.session.add(models.Users(username='lqz', pwd='123', gender=1))
    db.session.commit()

    obj = db.session.query(models.Users).filter(models.Users.id == 1).first()
    print(obj)

    PS: db.session和db.create_session
    """
    # db.session.add(models.Users(username='wupeiqi1', email='wupeiqi1@xx.com'))
    # db.session.commit()
    # db.session.close()
    #
    # db.session.add(models.Users(username='wupeiqi2', email='wupeiqi2@xx.com'))
    # db.session.commit()
    # db.session.close()
    # db.session.add(models.Users(username='alex1',email='alex1@live.com'))
    # db.session.commit()
    # db.session.close()



    user_list = db.session.query(models.Users).all()
    db.session.close()
    for item in user_list:
        print(item.username)


    return 'login'

settings.py (引擎不用註冊):

#!/usr/bin/env python
# -*- coding:utf-8 -*-

class BaseConfig(object):
    # SESSION_TYPE = 'redis'  # session類型爲redis
    # SESSION_KEY_PREFIX = 'session:'  # 保存到session中的值的前綴
    # SESSION_PERMANENT = True  # 若是設置爲False,則關閉瀏覽器session就失效。
    # SESSION_USE_SIGNER = False  # 是否對發送到瀏覽器上 session:cookie值進行加密

    SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:root@127.0.0.1:3306/bbb?charset=utf8"
    SQLALCHEMY_POOL_SIZE = 5
    SQLALCHEMY_POOL_TIMEOUT = 30
    SQLALCHEMY_POOL_RECYCLE = -1

    # 追蹤對象的修改而且發送信號
    SQLALCHEMY_TRACK_MODIFICATIONS = False


class ProductionConfig(BaseConfig):
    pass


class DevelopmentConfig(BaseConfig):
    pass


class TestingConfig(BaseConfig):
    pass

models.py:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from . import db


class Users(db.Model):
    """
    用戶表
    """
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    ids = db.Column(db.Integer)

    def __repr__(self):
        return '<User %r>' % self.username

執行命令:

flask-migrate  
 python3 manage.py db1 init   初始化:只執行一次

 python3 manage.py db1 migrate 等同於 makemigartions
 python3 manage.py db1 upgrade  等同於migrate

執行並登login便可添加數據:

python3 manage.py runserver
相關文章
相關標籤/搜索