Flask operate the database using SQLAlchemy

In web development, database is a necessary tool in which we flask, flask-SQlAlchemy can be used to connect to the database and CRUD operations.

Development tools: pycharm, pip, flask, flask_sqlalchemy, mysql database

Preparation: module Project Interpret pycharm or installation required to install pip

First, create a new DB_demo inside mysql database named in the basic framework of the flask, create a new profile config.py ,:

# encoding:utf-8
DIALECT = 'mysql'
DRIVER = 'MYSQLdb'
USERNAME = 'root'
PASSWORD = 'root'
HOST = 'localhost'
PORT = '3306'
DATABASE = 'DB_demo'
SQLALCHEMY_DATABASE_URI = "{}+{}://{}:{}@{}:{}/{}?charset=utf8".format(DIALECT,DRIVER,USERNAME,PASSWORD,HOST,PORT,DATABASE)
SQLALCHEMY_TRACK_MODIFICATIONS = True

 Is then introduced in the main file to which the corresponding module connection profile, the configuration database objects, preparatory work is completed, the definition of the object model database, where I use the model library management system, a user table, a table Books

from FlaskDemo.SQL foreign key constraint config lookup Import 
app = the Flask (__ name__)   
app.config.from_object (config) connected to the config file # 
db = SQLAlchemy (app) # Set model object db app
the User class (db.Model): 
    __tablename__ = "the User" # table name 
    id = db.Column (db.Integer, primary_key = True, autoincrement = True) # set the id primary key, increment mode 
    username = db.Column (db .String (100), nullable = False ) # username is not empty 

class Book (db.Model): 
    __tablename__ = "Book" 
    the above mentioned id = db.Column (db.Integer, primary_key = True, AUTOINCREMENT = True) # ISBN 
    title = db.Column (db.String (100), nullable = False) # title 
    content = db.Column (db.Text, nullable = False) # Introduction 
    user_id = db.Column (db.Integer, db.ForeignKey ( ' user.id ')) # contacted by a foreign key user ID 
    user db.relationship = (' the user ', backref = db.backref (' books')) # call method to find the corresponding book backref
db.create_all () # create database

 The model is now complete database has been established, the following is on the inside of the main approach to CRUD operations on a database

app.route @ ( '/') 
DEF index (): 
    # data is added first to add properties by way of example two object tables 
    user1 = User (username = 'A students') 
    user2 = the User (username =' B students ') 
    USER3 = the User (username =' C students') 
    Book1 = book (title = "Java from entry to give up", content = "this is a Java book to learn", user_id = 1) 
    Book2 = book (title = " Python from entry to the bald ", content =" this is a python dictionary book ", user_id = 2) 
    Book3 = book (title =" the Flask Web development ", content =" Getting to career change ", user_id = 3)     
    # add db database object into 
    db.session.add (user1) 
    db.session.add (Book1) 
    db.session.add (user2) 
    db.session.add (Book2) 
    db.session.add (USER3) 
    db.session.the Add (Book3) 
    # submitted to the database inside 
    after the completion of the new # for the first time, if the problem can not comment out the code to add an object, because the database already exists, or will be error
    db.session.commit () 
    # information If you are interested can create multiple models, for example, a user can correspond to multiple books, look for books by username
    # The following is a call query.filter () method to find the corresponding attribute object 
    Book.user_id = User.query.filter (User.id == 1) .first () # 1 for the book lookup ISBN 
    book = Book.query .filter (book.title == 'Flask Web developers') .first () # title tool to find books 
    # to find the name of the user based on user_id (lent user number) books 
    user_id = book.user_id 
    the user the user = .query.filter (User.id == user_id) .first () 
    Print ( 'user name:', user.username)     
    # Find the title to change the title of 
    book = Book.query.filter (book.title == ' Java from entry to abandon ') .first () 
    book.title =' Java the second line ' 
    Print (' title: ', book.title) 
    Print (' Introduction: ', book.content) 
    Print (' username : ', book.user.username)
    user = User.query.filter (User.username == 'A students') .first () 
    the Result = user.books 
    for in the Result Book:
      print ( 'Title:', book.title)     
    
    # start the server every time you perform the following refresh 
    return "Database updated successfully!"
if __name__ == '__main__':
    app.run(debug=True)
Published 58 original articles · won praise 31 · views 40000 +

Guess you like

Origin blog.csdn.net/qq_37504771/article/details/83870039