Skip to content

Commit 1796229

Browse files
committed
Part 1 tutorial demonstartion.
1 parent 87121f3 commit 1796229

File tree

10 files changed

+111
-83
lines changed

10 files changed

+111
-83
lines changed

Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ all help:
3131

3232
.PHONY: run
3333
run: env
34-
service $(PROJECTNAME) start
34+
flask run
3535

3636

3737
.PHONY: deploy

config.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,5 @@
1010

1111

1212
SQLALCHEMY_DATABASE_URI = environ.get("SQLALCHEMY_DATABASE_URI")
13+
SQLALCHEMY_DATABASE_PEM = environ.get("SQLALCHEMY_DATABASE_PEM")
1314
TIME_NOW = datetime.now()

poetry.lock

Lines changed: 38 additions & 38 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
pymysql==0.10.1
1+
pymysql==1.0.2; python_version >= "3.6"
22
python-dotenv==0.15.0
33
sqlalchemy==1.3.22; (python_version >= "2.7" and python_full_version < "3.0.0") or (python_full_version >= "3.4.0")

sqlalchemy_tutorial/__init__.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,16 @@
11
"""Script entry point."""
2-
from sqlalchemy_tutorial.models import create_tables
2+
import pprint
33

4+
from sqlalchemy_tutorial.database.engine import db
5+
from sqlalchemy_tutorial.queries import fetch_job_listings, update_job_listing
6+
7+
# Print formatter
8+
pp = pprint.PrettyPrinter(indent=4, width=300)
49

5-
def init_script():
6-
result = create_tables()
7-
print(result)
810

11+
def init_script():
12+
"""Demonstrate SELECT and UPDATE queries with SQLAlchemy."""
13+
rows_selected = fetch_job_listings(db)
14+
pp.pprint(rows_selected)
15+
rows_updated = update_job_listing(db)
16+
print(rows_updated)

sqlalchemy_tutorial/database.py

Lines changed: 0 additions & 11 deletions
This file was deleted.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
from .engine import db
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
"""Create database connection."""
2+
from sqlalchemy import create_engine
3+
from sqlalchemy.orm import Session
4+
5+
from config import SQLALCHEMY_DATABASE_PEM, SQLALCHEMY_DATABASE_URI
6+
7+
# Create database engine
8+
db = create_engine(
9+
SQLALCHEMY_DATABASE_URI,
10+
connect_args={"ssl": {"key": SQLALCHEMY_DATABASE_PEM}},
11+
echo=True,
12+
)
13+
14+
# Create database session
15+
session = Session(db)
Lines changed: 14 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,66 +1,52 @@
11
"""Declare models and relationships."""
2-
from sqlalchemy import (
3-
Boolean,
4-
Column,
5-
DateTime,
6-
ForeignKey,
7-
Integer,
8-
String,
9-
Table,
10-
Text,
11-
text,
12-
)
2+
from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Integer, String, Text
133
from sqlalchemy.ext.declarative import declarative_base
144
from sqlalchemy.orm import relationship
5+
from sqlalchemy.sql import func
6+
157
from sqlalchemy_tutorial.database import engine
168

179
Base = declarative_base()
1810

19-
association_table = Table(
20-
"association",
21-
Base.metadata,
22-
Column("team_id", Integer, ForeignKey("sport.player.team_id")),
23-
Column("id", Integer, ForeignKey("sport.team.id")),
24-
)
25-
2611

2712
class Player(Base):
28-
"""Individual player object."""
13+
"""Individual player belonging to a team."""
2914

3015
__tablename__ = "player"
3116

3217
id = Column(Integer, primary_key=True, autoincrement="auto")
33-
team_id = Column(Integer, ForeignKey("sport.team.id"), nullable=False)
18+
team_id = Column(Integer, ForeignKey("team.id"), nullable=False)
3419
first_name = Column(String(255), nullable=False)
3520
last_name = Column(String(255), nullable=False)
3621
position = Column(String(100), nullable=False)
3722
injured = Column(Boolean)
3823
description = Column(Text, nullable=True)
39-
created_at = Column(DateTime)
40-
updated_at = Column(DateTime, server_default=text("NOW()"), nullable=False)
24+
created_at = Column(DateTime, server_default=func.now())
25+
updated_at = Column(DateTime, onupdate=func.now())
4126

4227
# Relationships
4328
team = relationship("Team")
4429

4530
def __repr__(self):
46-
return "<Person model {}>".format(self.id)
31+
return "<Player {}>".format(self.id)
4732

4833

4934
class Team(Base):
50-
"""Sport team consisting of players."""
35+
"""Team consisting of many players."""
5136

5237
__tablename__ = "team"
5338

5439
id = Column(Integer, primary_key=True, autoincrement="auto")
5540
name = Column(String(255), nullable=False)
5641
city = Column(String(255), nullable=False)
57-
created_at = Column(DateTime, nullable=False)
58-
updated_at = Column(DateTime, server_default=text("NOW()"), nullable=False)
42+
abbreviation = Column(String(255), nullable=False)
43+
logo = Column(String(255), nullable=False)
44+
created_at = Column(DateTime, server_default=func.now())
45+
updated_at = Column(DateTime, onupdate=func.now())
5946

6047
def __repr__(self):
61-
return "<Team model {}>".format(self.id)
48+
return "<Team {}>".format(self.id)
6249

6350

6451
def create_tables():
6552
return Base.metadata.create_all(engine)
66-

sqlalchemy_tutorial/queries.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""Executing raw SQL queries against an SQLAlchemy engine."""
2+
from typing import List, Optional
3+
4+
from sqlalchemy import engine, text
5+
6+
7+
def fetch_job_listings(db: engine) -> Optional[List[dict]]:
8+
"""Select rows from database and parse as list of dicts."""
9+
results = db.execute(
10+
"SELECT job_id, agency, business_title, \
11+
salary_range_from, salary_range_to \
12+
FROM nyc_jobs ORDER BY RAND();"
13+
)
14+
print(f"Selected {results.rowcount} rows.")
15+
rows = [dict(row) for row in results.fetchall()]
16+
return rows
17+
18+
19+
def update_job_listing(db: engine) -> Optional[List[dict]]:
20+
"""Update row in database with problematic characters escaped."""
21+
result = db.execute(
22+
text(
23+
"UPDATE nyc_jobs SET business_title = 'Senior QA Scapegoat 🏆', \
24+
job_category = 'Information? <>!#%%Technology!%%#^&%* & Telecom' \
25+
WHERE job_id = 229837;"
26+
)
27+
)
28+
return result.rowcount

0 commit comments

Comments
 (0)