Python Flask-sqlalchemy Primary parsing

Source: Internet
Author: User
Tags sqlite

Flask-sqlalchemy is an extension that adds SQLAlchemy support to your flask application.

The SQLAlchemy is actually included in the Python extension library. After the version has been superimposed, it has been integrated into the flask architecture, Flask-sqlalchemy simplifies the use of sqlalchemy in flask, provides useful defaults and additional assistants to perform common tasks more easily.

I think SQLAlchemy is the most important thing is to use ORM (Object Relational mapping), compared to the traditional connection database using Select,update,insert,delete Operation data table has the following characteristics [1]:

Simple--modeling data in the most basic form

Communication--The database structure is documented in a language that anyone can understand

Accuracy-Create a properly standardized structure based on a data model

No absolute, ORM has a clear advantage, you will want to accompany with shortcomings.

Concealment--The operation of the data table is hidden from the traditional use of select,update,insert,delete, which is not conducive to the study of SQL

Data table structure is difficult to modify-in the design sometimes ignore the definition of some fields, in the ORM mode can only update the Mapping Table Update field, and the effect is far less than the ALTER TABLE [table name] Add field name Update field is easy to understand, often ignore some details

But it has to be said that ORM mode does open the door to a new world, greatly reducing the process and difficulty of learning and using databases.

From flask import Flask
From Flask_sqlalchemy import SQLAlchemy
Import OS
Basedir = Os.path.abspath (Os.path.dirname (__file__))

App = Flask (__name__)
app.config[' sqlalchemy_database_uri ' = ' sqlite:///' + os.path.join (basedir, ' test.db ')
app.config[' sqlalchemy_track_modifications ' = False
db = SQLAlchemy (APP)

Def db_init ():
Db.create_all ()

One sentence to an explanation

(1) From flask import flask

The Flask class is the core class of the Flask framework, which implements the WSGI application specification.

(2) from Flask_sqlalchemy import SQLAlchemy

Reference the built-in SQLAlchemy in Flask-sqlchemy to the file.

(3) Import OS

In this example, the database needs to be created in the project directory, using the Python built-in OS library can be easily located under the engineering path.

(4) Basedir = Os.path.abspath (Os.path.dirname (__file__))

Pass the current file into the DirName function, get the path where the current file is located, and the Abspath function gets the absolute path where the file is located so that the path to create the database is used behind the configuration.

(5) App = Flask (__name__) [2]

The first parameter of the flask constructor specifies a/importname that introduces the parameter.

The FLASK framework uses this name to locate static resources, templates, and error messages. Unless you clearly understand its role, usually we should always use special variable __name__.

The Flask instance is callable (with the Call method), which can be directly docked to the WSGI server.

(6) app.config[' sqlalchemy_database_uri ' = ' sqlite:///' + os.path.join (basedir, ' test.db ')

app.config[' sqlalchemy_track_modifications ' = False

Sqlalchemy_database_uri: Used to connect to the database

eg:sqlite:////tmp/test/db

Mysql://username:[email protected]/db

Sqlalchemy_track_modifications:

If set to True (by default), Flask-sqlalchemy will track the modification of the object and send a signal. This requires additional memory and can be disabled if it is not necessary. If you do not display the call to it, in the latest version of the run environment, a warning is displayed.

(7) db = SQLAlchemy (APP)

The SQLAlchemy function, which binds the flask framework that was just created, to the database that the project needs to use in order to enable engineering to connect to the database and achieve data manipulation.

(8) Db_init () function

Create a function manually to initialize the database

From database Import db

Class User (db. Model):
ID = db. Column (db. Integer, Primary_key=true)
Username = db. Column (db. String (a), unique=true)
email = db. Column (db. String (+), unique=true)

def __init__ (self, username, email):
Self.username = Username
Self.email = Email

def __repr__ (self):
Return ' <user {}> '. Format (Self.usernam)

Is still a sentence-by-step explanation

(1) From database Import db

Reference the SQLAlchemy app you just created to the current file to map the mapping table to the database so that you can create modifications to the data table and delete the updates.

(2) Db. Model

As mentioned above, an empty database file is created when the project file does not provide a mapping table. Inherit DB. Model class, which binds the mapping table and database DB we are currently creating. When the Create_all function is called by the project file, the bound mapping table file is automatically created in the database file.

If you want to explore the detailed binding relationship, apply the Pure SQLAlchemy library, not the Flask-sqlalchemy library, before the Flask-sqlalchemy is a simplified version of the SQLAlchemy, hidden a lot of detail, For further research please go to sqlalchemy official documentation to view the application details.

(3) Db. Column

Create a mapping table field with the most common types below

Integer storing integers
String (size) A string that stores a length
Text Store longer Unicode text
Datetime Store Time Type data
Float Storing floating-point values
Boolean Storing Boolean values
Pickletype Storing a Python object
Largebinary Store an arbitrarily large binary data

Primary_key=true Setting the current field as the primary key

Uniqu=true Setting the current field is not repeatable

Of course, you can also set the primary key foreign key, in this article only create a data table, in a future article will explain this action.

(4) __init__ function

A constructor for a map table, typically used to initialize variables, and to configure related data using the

(5) __repr__ function

Providing interfaces for later debug output

Follow the time to add a summary of the ORM many-to-many relationship considerations and optimize the query.

Python Flask-sqlalchemy Primary parsing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.