Skip to content

Commit 1ca0ae2

Browse files
authored
Format and lint shared directory (#64)
1 parent a9ca410 commit 1ca0ae2

File tree

13 files changed

+255
-102
lines changed

13 files changed

+255
-102
lines changed

app/shared/aa_utils.py

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,23 +11,39 @@
1111
def get_all_urls(result: Metadata) -> List[models.ArchiveUrl]:
1212
db_urls = []
1313
for m in result.media:
14-
for i, url in enumerate(m.urls): db_urls.append(models.ArchiveUrl(url=url, key=m.get("id", f"media_{i}")))
14+
for i, url in enumerate(m.urls):
15+
db_urls.append(
16+
models.ArchiveUrl(url=url, key=m.get("id", f"media_{i}"))
17+
)
1518
for k, prop in m.properties.items():
1619
if prop_converted := convert_if_media(prop):
17-
for i, url in enumerate(prop_converted.urls): db_urls.append(models.ArchiveUrl(url=url, key=prop_converted.get("id", f"{k}_{i}")))
20+
for i, url in enumerate(prop_converted.urls):
21+
db_urls.append(
22+
models.ArchiveUrl(
23+
url=url, key=prop_converted.get("id", f"{k}_{i}")
24+
)
25+
)
1826
if isinstance(prop, list):
1927
for i, prop_media in enumerate(prop):
2028
if prop_media := convert_if_media(prop_media):
2129
for j, url in enumerate(prop_media.urls):
22-
db_urls.append(models.ArchiveUrl(url=url, key=prop_media.get("id", f"{k}{prop_media.key}_{i}.{j}")))
30+
db_urls.append(
31+
models.ArchiveUrl(
32+
url=url,
33+
key=prop_media.get(
34+
"id", f"{k}{prop_media.key}_{i}.{j}"
35+
),
36+
)
37+
)
2338
return db_urls
2439

2540

26-
2741
def convert_if_media(media):
28-
if isinstance(media, Media): return media
42+
if isinstance(media, Media):
43+
return media
2944
elif isinstance(media, dict):
30-
try: return Media.from_dict(media)
45+
try:
46+
return Media.from_dict(media)
3147
except Exception as e:
3248
logger.debug(f"error parsing {media} : {e}")
3349
return False

app/shared/business_logic.py

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,35 @@
1-
# TODO: temporary file for this code, maybe other code belongs here, maybe not. do decide
2-
3-
41
import datetime
2+
from typing import Union
53

64
from sqlalchemy.orm import Session
75

86
from app.shared.db import worker_crud
97

108

11-
def get_store_archive_until(db: Session, group_id: str) -> datetime.datetime:
9+
# TODO: temporary file for this code, maybe other code belongs here, maybe not. do
10+
# decide
11+
12+
13+
def get_store_archive_until(
14+
db: Session, group_id: str
15+
) -> Union[datetime.datetime, None]:
1216
group = worker_crud.get_group(db, group_id)
1317
assert group, f"Group {group_id} not found."
14-
assert group.permissions and type(group.permissions) == dict, f"Group {group_id} has no permissions."
18+
assert group.permissions and isinstance(group.permissions, dict), (
19+
f"Group {group_id} has no permissions."
20+
)
1521

1622
max_lifespan = group.permissions.get("max_archive_lifespan_months", -1)
17-
if max_lifespan == -1: return None
23+
if max_lifespan == -1:
24+
return None
1825

1926
return datetime.datetime.now() + datetime.timedelta(days=30 * max_lifespan)
2027

2128

22-
def get_store_archive_until_or_never(db: Session, group_id: str) -> datetime.datetime:
29+
def get_store_archive_until_or_never(
30+
db: Session, group_id: str
31+
) -> Union[datetime.datetime, None]:
2332
try:
2433
return get_store_archive_until(db, group_id)
25-
except AssertionError as e:
34+
except AssertionError:
2635
return None

app/shared/db/database.py

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@ def make_engine(database_url: str):
1818
engine = create_engine(
1919
database_url,
2020
connect_args={"check_same_thread": False},
21-
pool_size=15, # Increase pool size
22-
max_overflow=20, # Allow more temporary connections
23-
pool_recycle=1800 # Recycle connections every 30 minutes
21+
pool_size=15, # Increase pool size
22+
max_overflow=20, # Allow more temporary connections
23+
pool_recycle=1800, # Recycle connections every 30 minutes
2424
)
2525

2626
@event.listens_for(engine, "connect")
@@ -40,8 +40,10 @@ def make_session_local(engine: Engine):
4040
@contextmanager
4141
def get_db():
4242
session = make_session_local(make_engine(get_settings().DATABASE_PATH))()
43-
try: yield session
44-
finally: session.close()
43+
try:
44+
yield session
45+
finally:
46+
session.close()
4547

4648

4749
def get_db_dependency():
@@ -59,22 +61,32 @@ def wal_checkpoint():
5961

6062
# ASYNC connections
6163
async def make_async_engine(database_url: str) -> AsyncEngine:
62-
engine = create_async_engine(database_url, connect_args={"check_same_thread": False})
64+
engine = create_async_engine(
65+
database_url, connect_args={"check_same_thread": False}
66+
)
6367

6468
async with engine.begin() as conn:
65-
await conn.run_sync(lambda sync_conn: sync_conn.execute(text("PRAGMA journal_mode=WAL;")))
69+
await conn.run_sync(
70+
lambda sync_conn: sync_conn.execute(
71+
text("PRAGMA journal_mode=WAL;")
72+
)
73+
)
6674

6775
return engine
6876

6977

7078
async def make_async_session_local(engine: AsyncEngine) -> AsyncSession:
71-
return async_sessionmaker(engine, expire_on_commit=False, autoflush=False, autocommit=False)
79+
return async_sessionmaker(
80+
engine, expire_on_commit=False, autoflush=False, autocommit=False
81+
)
7282

7383

7484
@asynccontextmanager
7585
async def get_db_async():
76-
engine = await make_async_engine(get_settings().ASYNC_DATABASE_PATH)
86+
engine = await make_async_engine(get_settings().async_database_path)
7787
async_session = await make_async_session_local(engine)
7888
async with async_session() as session:
79-
try: yield session
80-
finally: await engine.dispose()
89+
try:
90+
yield session
91+
finally:
92+
await engine.dispose()

app/shared/db/models.py

Lines changed: 39 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,9 @@ class Archive(Base):
4242
id = Column(String, primary_key=True, index=True)
4343
url = Column(String, index=True)
4444
result = Column(JSON, default=None)
45-
public = Column(Boolean, default=True) # if public=false, access by group and author
45+
public = Column(
46+
Boolean, default=True
47+
) # if public=false, access by group and author
4648
deleted = Column(Boolean, default=False)
4749
created_at = Column(DateTime(timezone=True), server_default=func.now())
4850
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
@@ -52,7 +54,11 @@ class Archive(Base):
5254
author_id = Column(String, ForeignKey("users.email"))
5355
sheet_id = Column(String, ForeignKey("sheets.id"), default=None)
5456

55-
tags = relationship("Tag", back_populates="archives", secondary=association_table_archive_tags)
57+
tags = relationship(
58+
"Tag",
59+
back_populates="archives",
60+
secondary=association_table_archive_tags,
61+
)
5662
group = relationship("Group", back_populates="archives")
5763
author = relationship("User", back_populates="archives")
5864
urls = relationship("ArchiveUrl", back_populates="archive")
@@ -75,7 +81,11 @@ class Tag(Base):
7581
id = Column(String, primary_key=True, index=True)
7682
created_at = Column(DateTime(timezone=True), server_default=func.now())
7783

78-
archives = relationship("Archive", back_populates="tags", secondary=association_table_archive_tags)
84+
archives = relationship(
85+
"Archive",
86+
back_populates="tags",
87+
secondary=association_table_archive_tags,
88+
)
7989

8090

8191
class User(Base):
@@ -85,7 +95,9 @@ class User(Base):
8595

8696
archives = relationship("Archive", back_populates="author")
8797
sheets = relationship("Sheet", back_populates="author")
88-
groups = relationship("Group", back_populates="users", secondary=association_table_user_groups)
98+
groups = relationship(
99+
"Group", back_populates="users", secondary=association_table_user_groups
100+
)
89101

90102

91103
class Group(Base):
@@ -101,7 +113,9 @@ class Group(Base):
101113

102114
archives = relationship("Archive", back_populates="group")
103115
sheets = relationship("Sheet", back_populates="group")
104-
users = relationship("User", back_populates="groups", secondary=association_table_user_groups)
116+
users = relationship(
117+
"User", back_populates="groups", secondary=association_table_user_groups
118+
)
105119

106120

107121
class Sheet(Base):
@@ -110,11 +124,27 @@ class Sheet(Base):
110124
id = Column(String, primary_key=True, index=True, doc="Google Sheet ID")
111125
name = Column(String, default=None)
112126
author_id = Column(String, ForeignKey("users.email"))
113-
group_id = Column(String, ForeignKey("groups.id"), doc="Group ID, user must be in a group to create a sheet.")
114-
frequency = Column(String, default="daily", doc="Frequency of archiving: hourly, daily, weekly.")
127+
group_id = Column(
128+
String,
129+
ForeignKey("groups.id"),
130+
doc="Group ID, user must be in a group to create a sheet.",
131+
)
132+
frequency = Column(
133+
String,
134+
default="daily",
135+
doc="Frequency of archiving: hourly, daily, weekly.",
136+
)
115137
# TODO: stats is not being used, consider removing
116-
stats = Column(JSON, default={}, doc="Sheet statistics like total links, total rows, ...")
117-
last_url_archived_at = Column(DateTime(timezone=True), server_default=func.now(), doc="Last time a new link was archived.")
138+
stats = Column(
139+
JSON,
140+
default={},
141+
doc="Sheet statistics like total links, total rows, ...",
142+
)
143+
last_url_archived_at = Column(
144+
DateTime(timezone=True),
145+
server_default=func.now(),
146+
doc="Last time a new link was archived.",
147+
)
118148
created_at = Column(DateTime(timezone=True), server_default=func.now())
119149
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
120150

app/shared/db/worker_crud.py

Lines changed: 32 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@
99
# TODO: isolate database operations away from worker and into WEB
1010
# ONLY WORKER
1111
def update_sheet_last_url_archived_at(db: Session, sheet_id: str):
12-
db_sheet = db.query(models.Sheet).filter(models.Sheet.id == sheet_id).first()
12+
db_sheet = (
13+
db.query(models.Sheet).filter(models.Sheet.id == sheet_id).first()
14+
)
1315
if db_sheet:
1416
db_sheet.last_url_archived_at = datetime.now()
1517
db.commit()
@@ -19,12 +21,17 @@ def update_sheet_last_url_archived_at(db: Session, sheet_id: str):
1921

2022
# ONLY WORKER and INTEROP
2123

24+
2225
def get_group(db: Session, group_name: str) -> models.Group:
2326
return db.query(models.Group).filter(models.Group.id == group_name).first()
2427

28+
2529
def create_or_get_user(db: Session, author_id: str) -> models.User:
26-
if type(author_id) == str: author_id = author_id.lower()
27-
db_user = db.query(models.User).filter(models.User.email == author_id).first()
30+
if isinstance(author_id, str):
31+
author_id = author_id.lower()
32+
db_user = (
33+
db.query(models.User).filter(models.User.email == author_id).first()
34+
)
2835
if not db_user:
2936
db_user = models.User(email=author_id)
3037
db.add(db_user)
@@ -43,8 +50,22 @@ def create_tag(db: Session, tag: str) -> models.Tag:
4350
return db_tag
4451

4552

46-
def create_archive(db: Session, archive: schemas.ArchiveCreate, tags: list[models.Tag], urls: list[models.ArchiveUrl]) -> models.Archive:
47-
db_archive = models.Archive(id=archive.id, url=archive.url, result=archive.result, public=archive.public, author_id=archive.author_id, group_id=archive.group_id, sheet_id=archive.sheet_id, store_until=archive.store_until)
53+
def create_archive(
54+
db: Session,
55+
archive: schemas.ArchiveCreate,
56+
tags: list[models.Tag],
57+
urls: list[models.ArchiveUrl],
58+
) -> models.Archive:
59+
db_archive = models.Archive(
60+
id=archive.id,
61+
url=archive.url,
62+
result=archive.result,
63+
public=archive.public,
64+
author_id=archive.author_id,
65+
group_id=archive.group_id,
66+
sheet_id=archive.sheet_id,
67+
store_until=archive.store_until,
68+
)
4869
db_archive.tags = tags
4970
db_archive.urls = urls
5071
db.add(db_archive)
@@ -53,10 +74,14 @@ def create_archive(db: Session, archive: schemas.ArchiveCreate, tags: list[model
5374
return db_archive
5475

5576

56-
def store_archived_url(db: Session, archive: schemas.ArchiveCreate) -> models.Archive:
77+
def store_archived_url(
78+
db: Session, archive: schemas.ArchiveCreate
79+
) -> models.Archive:
5780
# create and load user, tags, if needed
5881
create_or_get_user(db, archive.author_id)
5982
db_tags = [create_tag(db, tag) for tag in (archive.tags or [])]
6083
# insert everything
61-
db_archive = create_archive(db, archive=archive, tags=db_tags, urls=archive.urls)
84+
db_archive = create_archive(
85+
db, archive=archive, tags=db_tags, urls=archive.urls
86+
)
6287
return db_archive

app/shared/log.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@
88
logger.add("logs/error_logs.log", retention="30 days", level="ERROR")
99

1010

11-
def log_error(e: Exception, traceback_str: str = None, extra:str = ""):
12-
if not traceback_str: traceback_str = traceback.format_exc()
13-
if extra: extra = f"{extra}\n"
11+
def log_error(e: Exception, traceback_str: str = None, extra: str = ""):
12+
if not traceback_str:
13+
traceback_str = traceback.format_exc()
14+
if extra:
15+
extra = f"{extra}\n"
1416
logger.error(f"{extra}{e.__class__.__name__}: {e}\n{traceback_str}")

app/shared/schemas.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,15 @@ class SubmitSheet(BaseModel):
1111
group_id: str = "default"
1212
tags: set[str] | None = set()
1313

14+
1415
class ArchiveUrl(BaseModel):
1516
url: str
1617
public: bool = False
1718
author_id: str | None
1819
group_id: str | None
1920
tags: set[str] | None = set()
2021

22+
2123
class ArchiveResult(BaseModel):
2224
id: str
2325
url: str

0 commit comments

Comments
 (0)