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
+4 -3
View File
@@ -1,5 +1,6 @@
"""Admin dashboard KPI queries. Money returned as integer cents."""
from datetime import datetime, timedelta
from app.utils.time import utcnow
from app.extensions import db
from app.models.user import User
from app.models.listing import Listing
@@ -13,12 +14,12 @@ _ACTIVE_SUB_STATUSES = ("active", "trialing")
def active_listings_count():
return Listing.query.filter(
Listing.status == ListingStatus.active,
Listing.expires_at > datetime.utcnow(),
Listing.expires_at > utcnow(),
).count()
def new_users_count(days):
since = datetime.utcnow() - timedelta(days=days)
since = utcnow() - timedelta(days=days)
return User.query.filter(User.created_at >= since).count()
@@ -32,7 +33,7 @@ def mrr_cents():
def revenue_30d_cents():
"""Subscription + boost transactions in the last 30 days."""
since = datetime.utcnow() - timedelta(days=30)
since = utcnow() - timedelta(days=30)
return (db.session.query(db.func.coalesce(db.func.sum(Transaction.amount_cents), 0))
.filter(Transaction.type.in_(("subscription", "boost")),
Transaction.created_at >= since,
+5 -4
View File
@@ -20,6 +20,7 @@ Sponsors:
"""
import random
from datetime import datetime
from app.utils.time import utcnow
from app.extensions import db
from app.models.ads import Ad, Sponsor, PromotedKeyword
from app.models.listing import Listing
@@ -28,7 +29,7 @@ from app.utils.text import normalize
def get_ad(slot: str, lang: str = None, state: str = None) -> "Ad | None":
"""Return one active ad for the slot, targeted then untargeted fallback."""
now = datetime.utcnow()
now = utcnow()
base = Ad.query.filter(
Ad.slot == slot,
Ad.is_active == True,
@@ -76,7 +77,7 @@ def promoted_listings(keyword: str) -> list:
if not keyword:
return []
norm = normalize(keyword)
now = datetime.utcnow()
now = utcnow()
rows = (PromotedKeyword.query
.filter(PromotedKeyword.expires_at > now)
.order_by(PromotedKeyword.priority.desc())
@@ -94,7 +95,7 @@ def promoted_listings(keyword: str) -> list:
def active_sponsors(tier: str = None, category_id: int = None) -> list:
"""Return running sponsors, optionally filtered by tier and category."""
now = datetime.utcnow()
now = utcnow()
q = Sponsor.query.filter(
Sponsor.is_active == True,
Sponsor.starts_at <= now,
@@ -109,7 +110,7 @@ def active_sponsors(tier: str = None, category_id: int = None) -> list:
def expire_promoted_keywords() -> int:
"""Remove expired promoted keyword rows. Returns count."""
now = datetime.utcnow()
now = utcnow()
expired = PromotedKeyword.query.filter(
PromotedKeyword.expires_at <= now).all()
n = len(expired)
+4 -3
View File
@@ -9,6 +9,7 @@ Key rules:
- stripe_enabled() guard lets the app run with no keys in dev.
"""
from datetime import datetime, timedelta
from app.utils.time import utcnow
import stripe
from flask import current_app
from app.extensions import db
@@ -140,7 +141,7 @@ def activate_boost(user_id: int, listing_id: int, boost_type: str,
db.session.add(txn)
db.session.flush()
expires_at = datetime.utcnow() + timedelta(days=info["days"])
expires_at = utcnow() + timedelta(days=info["days"])
boost = Boost(listing_id=listing_id, user_id=user_id,
type=boost_type, expires_at=expires_at,
transaction_id=txn.id)
@@ -152,7 +153,7 @@ def activate_boost(user_id: int, listing_id: int, boost_type: str,
if boost_type == "featured":
listing.is_featured = True
if boost_type == "bump":
listing.bump_at = datetime.utcnow()
listing.bump_at = utcnow()
db.session.commit()
return boost
@@ -307,7 +308,7 @@ def _record_sub_transaction(user_id, session):
def expire_boosts() -> int:
"""Clear expired boosts and revert listing effects. Returns count."""
now = datetime.utcnow()
now = utcnow()
expired = Boost.query.filter(Boost.expires_at <= now).all()
n = 0
for boost in expired:
+7 -4
View File
@@ -10,14 +10,17 @@ moderators can spot scraping attempts.
"""
import re
from datetime import datetime
from app.utils.time import utcnow
from app.models.enums import TrustTier
from app.services.settings import get_setting
# patterns
_PHONE_RE = re.compile(
r"(\+?1[\s\-.]?)?"
r"(\(?\d{3}\)?[\s\-.])"
r"\d{3}[\s\-.]\d{4}"
r"(?<!\d)" # not mid-way through a longer digit run
r"(?:\+?1[\s\-.]?)?" # optional country code
r"\(?\d{3}\)?[\s\-.]?" # area code — separators now optional
r"\d{3}[\s\-.]?\d{4}" # so 5551234567 is caught, not just 555-123-4567
r"(?!\d)"
)
_EMAIL_RE = re.compile(r"[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}")
_URL_RE = re.compile(r"https?://\S+|www\.\S+", re.I)
@@ -32,7 +35,7 @@ def contact_revealed(user) -> bool:
return False
gate_days = get_setting("new_user_trust_gate_days", 0)
if gate_days and user.created_at:
if (datetime.utcnow() - user.created_at).days < gate_days:
if (utcnow() - user.created_at).days < gate_days:
return False
return True
+3 -2
View File
@@ -11,6 +11,7 @@ use the existing `attributes` JSON and a private `_notified` sub-key so no migra
is required. The key is prefixed with `_` to avoid colliding with user attributes.
"""
from datetime import datetime, timedelta
from app.utils.time import utcnow
from flask import current_app
from app.extensions import db
from app.models.listing import Listing
@@ -25,13 +26,13 @@ def _already_notified(listing, key: str) -> bool:
def _mark_notified(listing, key: str):
attrs = dict(listing.attributes or {})
attrs[key] = datetime.utcnow().isoformat()
attrs[key] = utcnow().isoformat()
listing.attributes = attrs
def warn_expiring(days: int = 3) -> int:
"""Send warning emails for listings expiring within `days` days. Returns count."""
now = datetime.utcnow()
now = utcnow()
window_end = now + timedelta(days=days)
soon = (Listing.query
.filter(Listing.status == ListingStatus.active,
+2 -1
View File
@@ -4,6 +4,7 @@ Portable across MySQL and SQLite (no spatial extension needed). For large-scale
deployments, see README for the MySQL POINT + SPATIAL INDEX upgrade.
"""
import math
from app.extensions import db
from app.models.geo import ZipGeo
EARTH_MI = 3958.7613 # mean earth radius, miles
@@ -11,7 +12,7 @@ EARTH_MI = 3958.7613 # mean earth radius, miles
def geocode_zip(zip_code):
"""Return (lat, lng, city, state, metro) or None."""
row = ZipGeo.query.get((zip_code or "").strip())
row = db.session.get(ZipGeo, (zip_code or "").strip())
if row is None:
return None
return row.lat, row.lng, row.city, row.state, row.metro
+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,
+2 -1
View File
@@ -8,6 +8,7 @@ Rules:
for now sent inline — fast enough at low volume).
"""
from datetime import datetime
from app.utils.time import utcnow
from sqlalchemy.exc import IntegrityError
from flask import current_app
from app.extensions import db
@@ -67,7 +68,7 @@ def send_message(conversation, sender, body: str) -> Message:
body=body,
)
db.session.add(msg)
conversation.last_message_at = datetime.utcnow()
conversation.last_message_at = utcnow()
db.session.commit()
if flagged: