Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ADD: Python logging to *.py files #71

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,19 @@
from models import RedditData
import spotipy
import prawcore
import logging

from xml.sax import saxutils as su

# Setting up logger
logging.basicConfig(
filename='fresh_script.log',
filemode='w+',
format='%(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


# global objects
app = Flask(__name__)
User = createUser()
Expand Down Expand Up @@ -43,6 +53,7 @@ def tracks(Name=None):
media = sub.media_embed
images.append(su.unescape(media['content']))
print("spotify media:", media)
logger.info("spotify media:", media)

else:
# handle non-spotify posts
Expand All @@ -62,14 +73,17 @@ def tracks(Name=None):

media = sub.media_embed
print("other media:", media)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you should remove the prints

logger.info("other media:", media)
if 'content' in media:
s = su.unescape(media['content'])
images.append(s)

print("content media:", s)
logger.info("content media:", s)
else:
images.append(media)
print("other media:", media)
logger.info("other media:", media)

# zip tracks and info together to be rendered on the tracks page
track_info = zip(titles, tracks, images)
Expand Down
22 changes: 22 additions & 0 deletions fresh.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@
from constants import ft_set
from models import User
import cutie
import logger

# Getting logger
logger = logging.getLogger(__name__)


def createUserConfig(user, config_path='.config.ini'):
"""
Expand Down Expand Up @@ -91,6 +96,7 @@ def createUser():

elif not os.path.isfile('.config.ini'):
print('Credentials file not found!')
logger.info('Credentials file not found!')

# get credentials
s_client_id = input('Enter your Spotify Client ID: ').strip()
Expand Down Expand Up @@ -129,6 +135,7 @@ def createUser():
'''
except Exception as e:
print(f'config failure: {e}')
logger.error(f'config failure: {e}')

return user

Expand Down Expand Up @@ -314,6 +321,7 @@ def process_subreddit(subreddit, choice, l):
sub_choice = subreddit.top(limit=l)
else:
print("Unsupported sorting method")
logger.warn("Unsupported sorting method")
sys.exit()
return sub_choice

Expand All @@ -328,6 +336,10 @@ def addSpotifyTrack(fresh, threshold, includeAlbums, verbose, sub, tracks):
print("Score: ", sub.score)
print("------------------------\n")

logger.info("Post: ", sub.title)
logger.info("URL: ", sub.url)
logger.info("Score: ", sub.score)

# Discard post below threshold if given
if threshold and sub.score < threshold:
return
Expand Down Expand Up @@ -382,6 +394,7 @@ def main():
spotifyObj.trace = False
if args.verbose:
print('Welcome to the HipHopHeads Fresh Script')
logger.info('Welcome to the HipHopHeads Fresh Script')
verbose, l, choice, threshold, includeAlbums, fresh = process_args(
args, user)
sub_choice = process_subreddit(subreddit, choice, l)
Expand Down Expand Up @@ -412,6 +425,10 @@ def main():
print("Score: ", sub.score)
print("------------------------\n")

logger.info("Post: ", sub.title)
logger.info("URL: ", sub.url)
logger.info("Score: ", sub.score)

tracks.append(track_url)
# handle overflow
if len(tracks) > 90:
Expand All @@ -438,13 +455,18 @@ def main():
print('New Tracks added to ', spotifyObj.user_playlist(user.username, playlist, 'name')['name'], ': ', abs(
existing_tracks['total'] - spotifyObj.user_playlist_tracks(user.username, playlist)['total']))
print()
logger.info('New Tracks added to ', spotifyObj.user_playlist(user.username, playlist, 'name')['name'], ': ', abs(
existing_tracks['total'] - spotifyObj.user_playlist_tracks(user.username, playlist)['total']))
except:
if results == [] and verbose:
print("No new tracks have been added.")
logger.error("No new tracks have been added.")
else:
print("An error has occured removing or adding new tracks")
logger.error("An error has occured removing or adding new tracks")
# if verbose:
# print(tracks)
# logger.error(tracks)

if __name__ == '__main__':
main()
18 changes: 17 additions & 1 deletion models.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@
from crontab import CronTab
import textwrap
import praw
import logging

# Getting logger
logger = logging.getLogger(__name__)


# user object to hold the things
class User:
Expand Down Expand Up @@ -45,6 +50,7 @@ def addPlaylists(self):
ownedPlaylists = self.fetchPlaylists(offset)
except:
print("You don't have any Spotify playlists!")
logger.error("You don't have any Spotify playlists!")
return
self.printOwnedPlaylists(ownedPlaylists)
enteringPlaylists = True
Expand All @@ -68,6 +74,7 @@ def addPlaylists(self):
except:
print()
print("No more playlists to view.")
logger.error("No more playlists to view.")
offset = offset - 50
finally:
self.printOwnedPlaylists(ownedPlaylists)
Expand All @@ -78,6 +85,7 @@ def addPlaylists(self):
except:
print()
print("No previous playlists to view.")
logger.error("No previous playlists to view.")
offset = offset + 50
finally:
self.printOwnedPlaylists(ownedPlaylists)
Expand All @@ -87,9 +95,11 @@ def addPlaylists(self):
else:
print()
print("Unexpected input!")
logger.error("Unexpected input!")
continue
except:
print("That playlist number doesn't exist!")
print("That playlist number doesn't exist!")'
logger.error("Unexpected input!")'
enteringPlaylists = self.str2bool(input('Would you like to enter another playlist ID? [Y/N] ').strip())
self.playlists.extend(playlistsToAdd)

Expand All @@ -108,11 +118,14 @@ def printOwnedPlaylists(self, ownedPlaylists):
if len(ownedPlaylists) == 0:
print()
print("You do not own any playlists in this batch. Type 'n' or 'next' to go to the next one.")
logger.warn("You do not own any playlists in this batch. Type 'n' or 'next' to go to the next one.")
else:
for i, playlist in enumerate(ownedPlaylists):
print()
print(f"{i+1}. {playlist['name']}")
print(' total tracks', playlist['tracks']['total'])
logger.info(f"{i+1}. {playlist['name']}")
logger.info(' total tracks', playlist['tracks']['total'])

# prompt user to remove current playlists
def removePlaylists(self):
Expand All @@ -125,14 +138,17 @@ def removePlaylists(self):
del self.playlists[index-1]
except:
print("That playlist number doesn't exist!")
logger.error("That playlist number doesn't exist!")
removingPlaylists = self.str2bool(input('Would you like to remove another playlist? [Y/N] ').strip())

# print out numbered list of the names of the playlists that are currently being added to
def printPlaylists(self):
sp = spotipy.Spotify(auth=self.token)
print("\nYour current playlists are:")
logger.info(Your current playlists are:")
for index, playlist in enumerate(self.playlists):
print(f"{index+1}. {sp.user_playlist(self.username, playlist, 'name')['name']}")
logger.info(f"{index+1}. {sp.user_playlist(self.username, playlist, 'name')['name']}")
print()

# use python-crontab to write a cron task
Expand Down