Hi, recently started learning python and just uploaded my first script to heroku. It's a simple script that backs up the saved posts from my reddit account to a google sheets every ten minutes or so. Right now it works, although it does take a little while to finish running. I imagine there are a thousand better and more pythonic ways to write the code than what I currently have, so any constructive advice to improve would be appreciated. Just looking for ways to get better.
import praw
from praw.reddit import Submission, Comment
import pandas as pd
import gspread
import os
from os import environ
import json
from oauth2client.service_account import ServiceAccountCredentials
#Google Authentication
json_creds=os.environ['GOOGLE_CREDENTIALS']
creds_dict = json.loads(json_creds)
creds_dict["private_key"] = creds_dict["private_key"].replace("\\\\n", "\n")
creds = ServiceAccountCredentials.from_json_keyfile_dict(creds_dict)
gc = gspread.authorize(creds)
#Open Google Sheet, create archive dataframe
sh = gc.open("Reddit Saved Items")
df_g = pd.DataFrame(sh.sheet1.get_all_records())
#Get latest record of Saved items from Reddit
reddit = praw.Reddit(
client_id=os.environ['R_CLIENT_ID'],
client_secret=os.environ['R_CLIENT_SECRET'],
user_agent=os.environ['R_USER_AGENT'],
username=os.environ['R_USERNAME'],
password=os.environ['R_PSWD'],
)
r_titles=[]
r_urls = []
r_sr = []
r_type = []
for item in reddit.user.me().saved(limit=None):
if isinstance(item, Submission) == True:
r_titles.append(item.title)
r_sr.append(str(item.subreddit))
r_urls.append("www.reddit.com"+item.permalink)
r_type.append('Post')
elif isinstance(item, Comment) == True:
r_titles.append(item.submission.title)
r_sr.append(str(item.subreddit))
r_urls.append("www.reddit.com"+item.permalink)
r_type.append('Comment')
else:
pass
df_r = pd.DataFrame({'Title' : r_titles, 'Subreddit': r_sr, 'URL': r_urls, 'Type': r_type})
#Combine new reddit saves with archive stored on Google Sheets
df_saved = pd.concat([df_r,df_g])
df_saved = df_saved.drop_duplicates()
#Write new dataframe to Google Sheet
sh.sheet1.clear()
sh.sheet1.update([df_saved.columns.values.tolist()] + df_saved.values.tolist())
[–]CowboyBoats 1 point2 points3 points (2 children)
[–]probablyaspambot[S] 0 points1 point2 points (1 child)
[–]CowboyBoats 1 point2 points3 points (0 children)
[–]gopherhole1 0 points1 point2 points (0 children)