Home > database >  Why flask using sqlalchemy db. Create_all () to establish a database to appear empty table ah, save
Why flask using sqlalchemy db. Create_all () to establish a database to appear empty table ah, save

Time:02-25

The from flask import flask
The from flask_sqlalchemy import SQLAlchemy


App=Flask (__name__)

App. Config [' SQLALCHEMY_DATABASE_URI]='mysql + pymysql://root: [email protected]/flask_books'
App. Config [' SQLALCHEMY_TRACK_MODIFICATIONS]=False

Db: SQLAlchemy=SQLAlchemy (app)


Class Author (the Model) :
__tablename__='the authors'

Id=db. The Column (db. The Integer, primary_key=True)
Name=db. The Column (the String (16), unique=True)

Books=db. The relationship (' Book 'backref=' author ')

Def __repr__ (self) :
Return 'Author: % s' % self. The name


Class Book (the Model) :
__tablename__='books'

Id=db. The Column (db. The Integer, primary_key=True)
Name=db. The Column (the String (16), unique=True)
Author_id=db. The Column (db. The Integer, db ForeignKey (' the authors. Id '))

Def __repr__ (self) :
Return '% s' Book: % s % (self. The name, the self. Author_id)


@ app. The route ('/')
Def hello_world () :
Return "Hello World! '


If __name__=="__main__ ':
# to demonstrate convenient, first remove all tables, create
Db. Drop_all ()
Db. Create_all ()

# add test database
# generate data
Au1=Author (name='Lao wang')
Au2=Author (name='old Yin)
Au3=Author (name='liu')
# the data submitted to the user's session
The db. The session. Add_all ([au1 au2, au3])
# submit session
MIT ()
db.session.com
Bk1=Book (name='Lao wang memoirs, author_id=au1. Id)
Bk2=Book (name='I read less, you don't lie to me, and author_id=au1. Id)
Bk3=Book (name='how can let oneself more SAO, author_id=au2. Id)
Bk4=Book (name='how to conquer the beautiful girl, and author_id=au3. Id)
Bk5=Book (name='how to conquer the handsome boys' author_id=au3. Id)
# the data submitted to the user's session
Db. The session. Add_all ([bk1, bk2, bk3 bk4, bk5])
# submit session
MIT ()
db.session.com
App. The run (debug=True)

CodePudding user response:

Really crack
  • Related