SqlAlchemyis aPythonof theOrmFramework.
There is a flask-sqlalchemy extension in flask , which is convenient to use.
1. Create a sqlalchemy the 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 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. Write 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"
Using SQLAlchemy in Python web development-flask