Jul 13 - Optimize code

This commit is contained in:
2026-07-13 16:52:00 -04:00
parent 936d860342
commit 00a9ba7770
27 changed files with 141 additions and 208 deletions
+15 -5
View File
@@ -1,7 +1,9 @@
"""Listing business logic: creation/edit with tier enforcement, the
browse/search/radius query builder, and the expiry sweep.
"""
import re
from datetime import datetime, timedelta
from app.utils.time import utcnow
from app.extensions import db
from app.models.listing import Listing
from app.models.enums import ListingStatus, Lang
@@ -30,7 +32,7 @@ def active_count(user):
return Listing.query.filter(
Listing.user_id == user.id,
Listing.status == ListingStatus.active,
Listing.expires_at > datetime.utcnow(),
Listing.expires_at > utcnow(),
).count()
@@ -55,7 +57,15 @@ def _blocklist_hit(title, body):
if not blocklist:
return False
hay = normalize(f"{title} {body}")
return any(normalize(term) in hay for term in blocklist if term)
for term in blocklist:
if not term:
continue
t = normalize(term).strip()
# word-boundary match so "ass" doesn't flag "class"; multi-word
# phrases still match as an internal-boundaried run.
if t and re.search(rf"\b{re.escape(t)}\b", hay):
return True
return False
# --- create / update ---
@@ -78,7 +88,7 @@ def create_listing(user, category, *, title, body, lang, price_cents,
price_cents=price_cents,
attributes=cleaned,
status=ListingStatus.active,
expires_at=datetime.utcnow() + timedelta(days=_life_days(user)),
expires_at=utcnow() + timedelta(days=_life_days(user)),
**hot_values(cleaned),
)
if _blocklist_hit(title, body):
@@ -125,7 +135,7 @@ def browse_query(*, category_id=None, q=None, state=None, min_price=None,
"""Base query of live listings with optional filters (no radius)."""
query = Listing.query.filter(
Listing.status == ListingStatus.active,
Listing.expires_at > datetime.utcnow(),
Listing.expires_at > utcnow(),
)
if category_id:
query = query.filter(Listing.category_id == category_id)
@@ -186,7 +196,7 @@ def search_with_radius(base_query, lat, lng, radius_mi):
# --- expiry sweep (scheduler / CLI) ---
def expire_due_listings():
"""Flip active listings past expires_at to expired. Returns count."""
now = datetime.utcnow()
now = utcnow()
due = Listing.query.filter(
Listing.status == ListingStatus.active,
Listing.expires_at <= now,