Skip to content

Commit

Permalink
Merge pull request #42 from freezingsaddles/black-2024-1
Browse files Browse the repository at this point in the history
Format with black
  • Loading branch information
obscurerichard authored Jan 13, 2024
2 parents df3c4f9 + c4e3a22 commit d876c5b
Show file tree
Hide file tree
Showing 22 changed files with 52 additions and 68 deletions.
7 changes: 5 additions & 2 deletions freezing/sync/autolog.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,10 @@ def _getUnterpolatedMessage(self, msg, args):
# by casting the left side (the "msg" variable) in this context
# to unicode. So we'll do that here

if sys.version_info >= (3, 0,):
if sys.version_info >= (
3,
0,
):
# this is most likely unnecessary on python 3, but it's here
# for completeness, in the case of someone manually creating
# a bytestring
Expand Down Expand Up @@ -213,7 +216,7 @@ def __getattr__(self, name):


def log_exceptions(fn):
""" A decorator designed to wrap a function and log any exception that method produces.
"""A decorator designed to wrap a function and log any exception that method produces.
The exception will still be raised after being logged.
Expand Down
1 change: 0 additions & 1 deletion freezing/sync/cli/sync_activities.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ def build_parser(self):
return parser

def execute(self, args):

fetcher = ActivitySync(logger=self.logger)
fetcher.sync_rides(
start_date=args.start_date,
Expand Down
1 change: 0 additions & 1 deletion freezing/sync/cli/sync_details.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@


class SyncActivityDetails(BaseCommand):

name = "sync-activity-detail"
description = "Sync the activity details JSON."

Expand Down
2 changes: 0 additions & 2 deletions freezing/sync/cli/sync_photos.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,10 @@


class SyncPhotosScript(BaseCommand):

name = "sync-photos"
description = "Sync ride photos."

def execute(self, args):

fetcher = PhotoSync()
fetcher.sync_photos()

Expand Down
5 changes: 3 additions & 2 deletions freezing/sync/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@


class Config:

DEBUG = env("DEBUG") # type: bool
SQLALCHEMY_URL = env("SQLALCHEMY_URL")
BEANSTALKD_HOST = env("BEANSTALKD_HOST", default="localhost")
Expand All @@ -32,7 +31,9 @@ class Config:
)

VISUAL_CROSSING_API_KEY = env("VISUAL_CROSSING_API_KEY")
VISUAL_CROSSING_CACHE_DIR = env("VISUAL_CROSSING_CACHE_DIR", default="/data/cache/weather")
VISUAL_CROSSING_CACHE_DIR = env(
"VISUAL_CROSSING_CACHE_DIR", default="/data/cache/weather"
)

COMPETITION_TEAMS = env("TEAMS", cast=list, subcast=int, default=[])
OBSERVER_TEAMS = env("OBSERVER_TEAMS", cast=list, subcast=int, default=[])
Expand Down
11 changes: 8 additions & 3 deletions freezing/sync/data/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ class StravaClientForAthlete(Client):
"""

def __init__(
self, athlete: Union[int, Athlete], logger: logging.Logger = None,
self,
athlete: Union[int, Athlete],
logger: logging.Logger = None,
):
self.logger = logger or logging.getLogger(__name__)
assert athlete, "No athlete ID or Athlete object provided."
Expand Down Expand Up @@ -49,7 +51,8 @@ def refresh_access_token(self, athlete: Athlete):
# Access token is still valid - no action needed
refresh_token = None
self.logger.info(
"access token for athlete %s is still valid ", athlete.id,
"access token for athlete %s is still valid ",
athlete.id,
)
elif athlete.access_token is not None:
# Athlete has an access token but no refresh token yet.
Expand All @@ -63,7 +66,9 @@ def refresh_access_token(self, athlete: Athlete):
if refresh_token:
self.logger.info("saving refresh token for athlete %s", athlete.id)
token_dict = super().refresh_access_token(
Config.STRAVA_CLIENT_ID, Config.STRAVA_CLIENT_SECRET, refresh_token,
Config.STRAVA_CLIENT_ID,
Config.STRAVA_CLIENT_SECRET,
refresh_token,
)
self.access_token = token_dict["access_token"]
athlete.access_token = token_dict["access_token"]
Expand Down
12 changes: 2 additions & 10 deletions freezing/sync/data/activity.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@


class ActivitySync(BaseSync):

name = "sync-activity"
description = "Sync activities."

Expand Down Expand Up @@ -144,7 +143,7 @@ def write_ride_efforts(self, strava_activity: Activity, ride: Ride):
else:
ride.resync_count = 1 + sync_count
ride.resync_date = datetime.now() + timedelta(
hours=6 ** sync_count
hours=6**sync_count
) # 1, 6, 36 hours

except:
Expand Down Expand Up @@ -266,7 +265,6 @@ def sync_rides_detail(
use_cache: bool = True,
only_cache: bool = False,
):

session = meta.scoped_session()

q = session.query(Ride)
Expand Down Expand Up @@ -345,9 +343,7 @@ def delete_activity(self, *, athlete_id: int, activity_id: int):
def fetch_and_store_activity_detail(
self, *, athlete_id: int, activity_id: int, use_cache: bool = False
):

with meta.transaction_context() as session:

self.logger.info(
"Fetching detailed activity athlete_id={}, activity_id={}".format(
athlete_id, activity_id
Expand Down Expand Up @@ -624,7 +620,6 @@ def write_ride(self, activity: Activity) -> Ride:
ride = Ride(activity.id)

if new_ride:

# Set the "workflow flags". These all default to False in the database. The value of NULL means
# that the workflow flag does not apply (e.g. do not bother fetching this)

Expand Down Expand Up @@ -667,7 +662,6 @@ def write_ride(self, activity: Activity) -> Ride:
def _sync_rides(
self, start_date: datetime, end_date: datetime, athlete, rewrite: bool = False
):

sess = meta.scoped_session()

api_ride_entries = self.list_rides(
Expand Down Expand Up @@ -695,7 +689,7 @@ def _sync_rides(
ride_ids_needing_detail = []
ride_ids_needing_streams = []

for (i, strava_activity) in enumerate(api_ride_entries):
for i, strava_activity in enumerate(api_ride_entries):
self.logger.debug(
"Processing ride: {0} ({1}/{2})".format(
strava_activity.id, i + 1, num_rides
Expand Down Expand Up @@ -834,9 +828,7 @@ def sync_rides(
force: bool = False,
athlete_ids: List[int] = None,
):

with meta.transaction_context() as sess:

if start_date is None:
start_date = config.START_DATE

Expand Down
8 changes: 4 additions & 4 deletions freezing/sync/data/athlete.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@


class AthleteSync(BaseSync):

name = "sync-athletes"
description = "Sync athletes."

Expand All @@ -48,9 +47,7 @@ def all_done(self):
return loc_time > end_time

def sync_athletes(self, max_records: int = None):

with meta.transaction_context() as sess:

# We iterate over all of our athletes that have access tokens.
# (We can't fetch anything for those that don't.)

Expand Down Expand Up @@ -171,7 +168,10 @@ def register_athlete_team(
matches = [c for c in matches if c.id not in config.OBSERVER_TEAMS]
if len(matches) > 1:
self.logger.info(
"Multiple teams matched for {}: {}".format(strava_athlete, matches,)
"Multiple teams matched for {}: {}".format(
strava_athlete,
matches,
)
)
raise MultipleTeamsError(matches)
if len(matches) == 0:
Expand Down
4 changes: 0 additions & 4 deletions freezing/sync/data/photos.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,11 @@


class PhotoSync(BaseSync):

name = "sync-photos"
description = "Sync (non-primary) ride photos."

def sync_photos(self):

with meta.transaction_context() as sess:

q = sess.query(orm.Ride)
q = q.filter_by(photos_fetched=False, private=False)

Expand Down Expand Up @@ -76,7 +73,6 @@ def write_ride_photos_nonprimary(self, activity_photos, ride):
# insta_client = insta.configured_instagram_client()

for activity_photo in activity_photos:

# If it's already in the db, then skip it.
existing = meta.scoped_session().query(RidePhoto).get(activity_photo.uid)
if existing:
Expand Down
8 changes: 3 additions & 5 deletions freezing/sync/data/streams.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@


class StreamSync(BaseSync):

name = "sync-activity-streams"
description = "Sync activity streams (GPS, etc.) JSON."

Expand All @@ -35,7 +34,6 @@ def sync_streams(
use_cache: bool = True,
only_cache: bool = False,
):

session = meta.scoped_session()

q = session.query(Ride).options(joinedload(Ride.athlete))
Expand All @@ -44,7 +42,9 @@ def sync_streams(
q = q.filter(and_(Ride.private == False, Ride.manual == False))

if not rewrite:
q = q.filter(Ride.track_fetched == False,)
q = q.filter(
Ride.track_fetched == False,
)

if athlete_id:
self.logger.info("Filtering activity details for {}".format(athlete_id))
Expand Down Expand Up @@ -86,9 +86,7 @@ def sync_streams(
def fetch_and_store_activity_streams(
self, *, athlete_id: int, activity_id: int, use_cache: bool = False
):

with meta.transaction_context() as session:

self.logger.info(
"Fetching activity streams for athlete_id={}, activity_id={}".format(
athlete_id, activity_id
Expand Down
5 changes: 2 additions & 3 deletions freezing/sync/data/weather.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,6 @@ def sync_weather(
num_rides = len(rows)

for i, r in enumerate(rows):

if limit and i >= limit:
logging.info("Limit ({0}) reached".format(limit))
break
Expand All @@ -80,7 +79,6 @@ def sync_weather(
)

try:

# If you can't reproduce the ancient infrastructure required by all this and so can't run any of the
# geoalchemy stuff you can hardcode this to debug
# start_geo_wkt = "POINT(-76.96 38.96)"
Expand Down Expand Up @@ -120,7 +118,8 @@ def sync_weather(
key=lambda d: abs((d.time - ride_start).total_seconds()),
)
end_obs = min(
hist.day.hours, key=lambda d: abs((d.time - ride_end).total_seconds())
hist.day.hours,
key=lambda d: abs((d.time - ride_end).total_seconds()),
)

if len(ride_observations) <= 2:
Expand Down
1 change: 0 additions & 1 deletion freezing/sync/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@


def main():

init_logging()
init_model(config.SQLALCHEMY_URL)

Expand Down
1 change: 0 additions & 1 deletion freezing/sync/subscribe.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ def handle_message(self, message: ActivityUpdate):
self.logger.info("Processing activity update {}".format(message))

with meta.transaction_context() as session:

athlete: Athlete = session.query(Athlete).get(message.athlete_id)
if not athlete:
self.logger.warning(
Expand Down
3 changes: 0 additions & 3 deletions freezing/sync/utils/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,6 @@ def retrieve_object_json(
object_json = None

if object_json is None:

if only_cache:
self.logger.info(
"[CACHE-MISS] Skipping {} {} "
Expand Down Expand Up @@ -171,7 +170,6 @@ def retrieve_object_json(


class CachingActivityFetcher(CachingAthleteObjectFetcher):

object_type = "activity"

def download_object_json(
Expand Down Expand Up @@ -209,7 +207,6 @@ def fetch(


class CachingStreamFetcher(CachingAthleteObjectFetcher):

object_type = "streams"

def filename(self, *, athlete_id: int, object_id: int):
Expand Down
3 changes: 0 additions & 3 deletions freezing/sync/wx/darksky/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@


class Hour(object):

time: datetime
temperature: float
apparent_temperature: float
Expand All @@ -22,7 +21,6 @@ def __init__(self, json, tz):


class Day(object):

sunrise_time: datetime
sunset_time: datetime
temperature_min: float
Expand All @@ -36,7 +34,6 @@ def __init__(self, json, tz):


class Forecast(object):

timezone: str
latitude: float
longitude: float
Expand Down
5 changes: 2 additions & 3 deletions freezing/sync/wx/ncdc/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ def __init__(self, p1, p2=None):


class Client(object):

base_url = urllib.parse.urlparse("http://www.ncdc.noaa.gov/cdo-services/services")

def __init__(self, token, cache_dir=None):
Expand All @@ -56,9 +55,9 @@ def _handle_protocol_error(self, response):
"""
Parses the JSON response from the server, raising a :class:`stravatools.api.Fault` if the
server returned an error.
:param response: The response JSON
:raises Fault: If the response contains an error.
:raises Fault: If the response contains an error.
"""
if "cdoError" in response:
raise Fault(response["name"], response["message"])
Expand Down
5 changes: 1 addition & 4 deletions freezing/sync/wx/ncdc/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@


class BaseCollection(object):
"""
"""
""" """

totalCount = None

Expand All @@ -17,7 +16,6 @@ def parse(self, result):


class PagedCollection(object):

pageCount = None
_page = None

Expand Down Expand Up @@ -112,7 +110,6 @@ def fill(self, collection, overwrite=False):


class LocationSearchResult(object):

_minDate = None
_maxDate = None

Expand Down
Loading

0 comments on commit d876c5b

Please sign in to comment.