Thomas Hobohm
I'm a young, passionate Computer Scientist and Software Engineer.
from sqlalchemy.ext.declarative import declarative_base
To start making mapped classes, you must create a Base class, which all of your mapped classes will inherit from:# Base is a class
Base = declarative_base()
Your mapped classes will inherit from the Base class, like so:class MyMappedClass(Base):
...
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column
Base = declarative_base()
class MyMappedClass(Base):
username = Column(...)
email = Column(...)
Columns are represented through Static Class Variables.from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column
from sqlalchemy import String
Base = declarative_base()
class MyMappedClass(Base):
username = Column(String)
email = Column(String)
id = db.Column(db.Integer, primary_key=True)
Flask-SQLAlchemy automatically assigns unique Keys to records.from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "/path/to/database/file.db"
db = SQLAlchemy(app)
The SQLALCHEMY_DATABASE_URI config variable is the location of your database file.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)
All of the classes used to create Mapped Classes in SQLAlchemy are properties of the DB object in Flask-SQLAlchemy.id = db.Column(db.Integer, primary_key=True)
Just like SQLAlchemy, Flask-SQLAlchemy will automatically handle the assignment of unique keys to each Record in your database. Some people will create a Base model with a Primary Key column so they don't have to keep writing out the above code:class Base(db.Model):
__abstract__ = True
id = db.Column(db.Integer, primary_key=True)
Setting the static class variable __abstract__ to True tells SQLAlchemy not to create a database table or mapper for the class. This allows subclasses to extend from the class.username = db.Column(db.String(20), unique=True)
All of the column types are properties of the db instance. Columns can be specified as Unique:# If unique is True, SQLAlchemy will make sure that all of the records have unique Usernames
username = db.Column(unique=True / False)
All of the types mentioned previously are properties of the db Object:db.Integer
db.String
db.Text
db.DateTime
db.Float
db.Boolean
db.PickleType
db.LargeBinary
myuser = User()
user.username = "superman3275"
user.email = "superman3275@gmail.com
SQLAlchemy will automatically convert Python types to database types! This allows you to work with your database records in pure Python!class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(12), unique=True)
password = db.Column(db.String(12))
bio = db.Column(db.String(140))
Oftentimes, in real applications, we want to tie models to each other. For example, many websites tie Users to Posts. Flask-SQLAlchemy abstracts these connetions away to two types of relationships:class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.String(140))
And we want to link Users to Posts. To do this, we have to use a Relationship and a Foreign Key:class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
posts = db.relationship("Post", backref="user", lazy="dynamic")
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.String(140))
user_id = db.Column(db.Integer, db.ForeignKey("user.id"))
posts = db.relationship("Post", backref="user", lazy="dynamic")
This creates a relationship between the User class and the Post class. We use a string, "Post", to represent the post class because it is declared later in the file. Setting backref="user" creates an attribute called "user" in the post class, which links to the User which created a post. posts is a list of instances of the Post class.user_id = db.Column(db.Integer, db.ForeignKey("post.id"))
This creaes a foreign key column in the Post table. A foreign key is a field in one table that uniquely identifies a row of another table. This enforces a link between two tables.tags = db.Table('tags',
db.Column('tag_id', db.Integer, db.ForeignKey('tag.id')),
db.Column('page_id', db.Integer, db.ForeignKey('page.id'))
)
class Page(db.Model):
id = db.Column(db.Integer, primary_key=True)
tags = db.relationship('Tag', secondary=tags,
backref=db.backref('pages', lazy='dynamic'))
class Tag(db.Model):
id = db.Column(db.Integer, primary_key=True)
I'm not going to go into much depth regarding Many to Many relationships, because they're very complex and specialized depending on your application.new_user = User()
new_user.username = "superman3275"
new_user.email = "superman3275@gmail.com"
db.session.add(new_user)
To actually save your changes, however, you must call the commit() method:db.session.commit()
The session object also allows you to get rid of all the changes you've made:db.session.rollback()
User.query.get(id) # Returns User object
2. query.filter_by() - Takes values of columns in table as arguments.
User.query.filter_by(username="superman3275") # Gets users whose username is superman3275
3. It's important to note that query.filter_by() doesn't return a list, it returns a query object with it's own methods. Two of the most useful methods are first() and order_by().By Thomas Hobohm
These are the slides for my presentation on using SQLAlchemy in Flask.
I'm a young, passionate Computer Scientist and Software Engineer.