The use of SQLAlchemy in Python web development-flask

Source: Internet
Author: User
Tags sqlite

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

Related Article

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.