Skip to content

Commit 144495a

Browse files
pamelafoxdavidism
authored andcommitted
update examples to SQLAlchemy 2 style
1 parent 7d1ce4c commit 144495a

File tree

6 files changed

+53
-30
lines changed

6 files changed

+53
-30
lines changed

examples/flaskr/README.rst

+3-3
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ Install
1212

1313
**Be sure to use the same version of the code as the version of the docs
1414
you're reading.** You probably want the latest tagged version, but the
15-
default Git version is the master branch.
15+
default Git version is the main branch.
1616

1717
.. code-block:: text
1818
@@ -42,7 +42,7 @@ Install Flaskr:
4242
4343
$ pip install -e .
4444
45-
Or if you are using the master branch, install Flask-SQLAlchemy from
45+
Or if you are using the main branch, install Flask-SQLAlchemy from
4646
source before installing Flaskr:
4747

4848
.. code-block:: text
@@ -79,7 +79,7 @@ Test
7979
.. code-block:: text
8080
8181
$ pip install -e '.[test]'
82-
$ pytest
82+
$ python3 -m pytest
8383
8484
Run with coverage report:
8585

examples/flaskr/flaskr/__init__.py

+8-2
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,16 @@
44
from flask import Flask
55
from flask.cli import with_appcontext
66
from flask_sqlalchemy import SQLAlchemy
7+
from sqlalchemy.orm import DeclarativeBase
78

8-
__version__ = (1, 0, 0, "dev")
9+
__version__ = (1, 1, 0, "dev")
910

10-
db = SQLAlchemy()
11+
12+
class Base(DeclarativeBase):
13+
pass
14+
15+
16+
db = SQLAlchemy(model_class=Base)
1117

1218

1319
def create_app(test_config=None):

examples/flaskr/flaskr/auth/models.py

+14-7
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,29 @@
1+
from __future__ import annotations
2+
3+
from typing import TYPE_CHECKING
4+
5+
from sqlalchemy.orm import Mapped, mapped_column, relationship
16
from werkzeug.security import check_password_hash
27
from werkzeug.security import generate_password_hash
38

49
from flaskr import db
510

11+
if TYPE_CHECKING:
12+
from ..blog.models import Post
613

7-
class User(db.Model):
8-
id = db.Column(db.Integer, primary_key=True)
9-
username = db.Column(db.String, unique=True, nullable=False)
10-
password_hash = db.Column(db.String, nullable=False)
1114

12-
posts = db.relationship("Post", back_populates="author")
15+
class User(db.Model):
16+
id: Mapped[int] = mapped_column(primary_key=True)
17+
username: Mapped[str] = mapped_column(unique=True)
18+
password_hash: Mapped[str]
19+
posts: Mapped[list[Post]] = relationship("Post", back_populates="author")
1320

14-
def set_password(self, value):
21+
def set_password(self, value: str) -> None:
1522
"""Store the password as a hash for security."""
1623
self.password_hash = generate_password_hash(value)
1724

1825
# allow password = "..." to set a password
1926
password = property(fset=set_password)
2027

21-
def check_password(self, value):
28+
def check_password(self, value: str) -> bool:
2229
return check_password_hash(self.password_hash, value)

examples/flaskr/flaskr/blog/models.py

+11-9
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from sqlalchemy.orm import Mapped, mapped_column, relationship
2+
from sqlalchemy import ForeignKey
13
from datetime import datetime
24
from datetime import timezone
35

@@ -7,25 +9,25 @@
79
from flaskr.auth.models import User
810

911

10-
def now_utc():
12+
def now_utc() -> datetime:
1113
return datetime.now(timezone.utc)
1214

1315

1416
class Post(db.Model):
15-
id = db.Column(db.Integer, primary_key=True)
16-
author_id = db.Column(db.ForeignKey(User.id), nullable=False)
17-
created = db.Column(db.DateTime, nullable=False, default=now_utc)
18-
title = db.Column(db.String, nullable=False)
19-
body = db.Column(db.String, nullable=False)
17+
id: Mapped[int] = mapped_column(primary_key=True)
18+
author_id: Mapped[int] = mapped_column(ForeignKey("user.id"))
19+
created: Mapped[datetime] = mapped_column(default=now_utc)
20+
title: Mapped[str]
21+
body: Mapped[str]
2022

2123
# User object backed by author_id
2224
# lazy="joined" means the user is returned with the post in one query
23-
author = db.relationship(User, lazy="joined", back_populates="posts")
25+
author: Mapped[User] = relationship(lazy="joined", back_populates="posts")
2426

2527
@property
26-
def update_url(self):
28+
def update_url(self) -> str:
2729
return url_for("blog.update", id=self.id)
2830

2931
@property
30-
def delete_url(self):
32+
def delete_url(self) -> str:
3133
return url_for("blog.delete", id=self.id)

examples/flaskr/setup.cfg

+1-2
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,7 @@ include_package_data = true
1515
python_requires = >= 3.8
1616
install_requires =
1717
Flask>=2.2
18-
Flask-SQLAlchemy>=3
19-
SQLAlchemy>=1.4.18
18+
Flask-SQLAlchemy>=3.1.0
2019

2120
[options.extras_require]
2221
test =

examples/todo/app.py

+16-7
Original file line numberDiff line numberDiff line change
@@ -8,23 +8,32 @@
88
from flask import request
99
from flask import url_for
1010
from flask_sqlalchemy import SQLAlchemy
11+
from sqlalchemy.orm import DeclarativeBase
12+
from sqlalchemy.orm import Mapped, mapped_column
13+
1114

1215
app = Flask(__name__)
1316
app.secret_key = "Achee6phIexoh8dagiQuew0ephuga4Ih"
1417
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///todo.sqlite"
15-
db = SQLAlchemy(app)
1618

1719

18-
def now_utc():
20+
class Base(DeclarativeBase):
21+
pass
22+
23+
24+
db = SQLAlchemy(app, model_class=Base)
25+
26+
27+
def now_utc() -> datetime:
1928
return datetime.now(timezone.utc)
2029

2130

2231
class Todo(db.Model):
23-
id = db.Column(db.Integer, primary_key=True)
24-
title = db.Column(db.String, nullable=False)
25-
text = db.Column(db.String, nullable=False)
26-
done = db.Column(db.Boolean, nullable=False, default=False)
27-
pub_date = db.Column(db.DateTime, nullable=False, default=now_utc)
32+
id: Mapped[int] = mapped_column(primary_key=True)
33+
title: Mapped[str]
34+
text: Mapped[str]
35+
done: Mapped[bool] = mapped_column(default=False)
36+
pub_date: Mapped[datetime] = mapped_column(default=now_utc)
2837

2938

3039
with app.app_context():

0 commit comments

Comments
 (0)