SQLAlchemy is a Python ORM framework.
There is a flask-sqlalchemy extension in flask, which is convenient to use.
1. Create a sqlalchemy model module
To create a models.py module
When creating the model, first introduce the extension of Flask-sqlalchemy
from Flask Import flask
from Flask_sqlalchemy import SQLAlchemy
Then initialize the app and SQLAlchemy
App = Flask (__name__)
app.config['sqlalchemy_database_uri'sqlite:////www/db/mydb '
db = SQLAlchemy (APP)
2. Build the database
Upload the code to the Linux server, and refer to the previous write-up procedure for deploying Flask to Linux Server articles. After uploading, CD to www/directory, then execute Python, import db
From models Import db
Executive Db.create_all ()
And then we'll take a look under SQLite.
Sqlite>. Open/www/db/mydb
Sqlite>. Tables
Posts user
Sqlite>. Schema posts
CREATE TABLE Posts (
ID INTEGER not NULL,
Title VARCHAR (80),
Content VARCHAR (500),
PRIMARY KEY (ID),
UNIQUE (title),
UNIQUE (content)
);
You can see that the data table has been created.
3. Writing data
Import Posts, from models import Posts, and then execute the add command
>>> Db.session.add (Posts (' title1 ', ' content '))
>>> Db.session.add (Posts (' title2 ', ' Content2 '))
>>> Db.session.commit ()
4. Querying Data
Go to sqlite3 and check the newly added data.
Sqlite>. Open/www/db/mydb
Sqlite> SELECT * from posts;
1|title1|content
2|title2|content2
Sqlite>
At this point, the basic operation of Sqlite3 through SQLAlchemy is completed.
More articles about the public number "kick genius"
The use of SQLAlchemy in Python web development-flask