Flask-sqlalchemy is fun to use, easy to use for basic applications, and easy to scale for large projects. For a complete guide, see the API documentation for SQLAlchemy.
In a common case where there is only one Flask application, all we need to do is create the Flask app, choose the load configuration and then create the SQLAlchemy object to pass the Flask app to it as a parameter.
Once created, this object contains all the functions and assistants in SQLAlchemy and Sqlalchemy.orm. It also provides a class named model, which is used as the Delarative base class when declaring models:
from flask import Flaskfrom flask.ext.sqlalchemy import SQLAlchemyapp = Flask(name)app.config[‘SQLALCHEMY_DATABASE_URI‘] = ‘sqlite:////tmp/test.db‘db = SQLAlchemy(app)class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) def __init__(self, username, email): self.username = username self.email = email def __repr__(self): return ‘<User %r>‘ % self.username
In order to create the initial database, you only need to import the DB object from the interactive Python shell and call the Sqlalchemy.create_all () method to create the table and database:
from yourapplication import dbdb.create_all()
The database has been generated. Now to create some users:
from yourapplication import Useradmin = User(‘admin‘, ‘[email protected]‘)guest = User(‘guest‘, ‘[email protected]‘)
But they are not actually written to the database, so let's make sure they're written to the database:
db.session.add(admin)db.session.add(guest)db.session.commit()
Accessing data in a database is also straightforward:
users = User.query.all()[<User u‘admin‘>, <User u‘guest‘>]admin = User.query.filter_by(username=‘admin‘).first()<User u‘admin‘>
A simple relationship
SQLAlchemy is connected to a relational database, and relational data is the most good thing about relationships. Therefore, we will create an application that uses two interrelated tables as an example:
from datetime import datetime
?
class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(80)) body = db.Column(db.Text) pub_date = db.Column(db.DateTime) category_id = db.Column(db.Integer, db.ForeignKey(‘category.id‘)) category = db.relationship(‘Category‘,backref=db.backref(‘posts‘, lazy=‘dynamic‘)) def __init__(self, title, body, category, pub_date=None): self.title = title self.body = body if pub_date is None: pub_date = datetime.utcnow() self.pub_date = pub_date self.category = category def __repr__(self): return ‘<Post %r>‘ % self.titleclass Category(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50)) def __init__(self, name): self.name = name def __repr__(self): return ‘<Category %r>‘ % self.name
Let's start by creating some objects:
py = Category(‘Python‘)p = Post(‘Hello Python!‘, ‘Python is pretty cool‘, py)db.session.add(py)db.session.add(p)
Now because we declared posts as a dynamic relationship in Backref, the query is displayed as:
py.posts<sqlalchemy.orm.dynamic.AppenderBaseQuery object at 0x1027d37d0>
It behaves like a normal query object, so we can query all the articles related to the "Python" category we tested (posts):
py.posts.all()[<Post ‘Hello Python!‘>]
We only need to know what is different from ordinary SQLAlchemy:
- SQLAlchemy allows access to the following things:
- All the functions and classes under SQLAlchemy and Sqlalchemy.orm
- A session with a pre-configured range called session (session)
- Metadata property
- Engine Properties
- Sqlalchemy.create_all () and Sqlalchemy.drop_all (), based on how the model is used to create and delete tables
- A Model base class, which is the basis (base) of a configured declaration (declarative)
- The model declares that the base class behaves like a regular Python class, but has a query property that can be used for querying models (model and Basequery)
- The session must be submitted, but it is not necessary to delete it after each request (session), Flask-sqlalchemy will help complete the delete operation.
Flask-sqlalchemy How to use