def get_books(api_key, username, shelf_name="to-read"): # Configure logger. logger = logging.getLogger("Goodreads") handler = logging.StreamHandler() formatter = logging.Formatter( "%(asctime)s %(levelname)s (%(name)s): %(message)s") handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.DEBUG) # Initialize Goodreads client and user. logger.info("Authenticating with the Goodreads API.") goodreads_client = client.GoodreadsClient(client_key=api_key, client_secret=None) user = goodreads_client.user(username=username) # Get books from the specified shelf. logger.info( f'Getting the list of books from {username}\'s "{shelf_name}" shelf.') reviews = user.per_shelf_reviews(shelf_name=shelf_name) # Normalize the list of books. books = [Book(book_dict=review.book) for review in reviews] return books
def addtoReading(myisbn): gc = client.GoodreadsClient(grkey, grsecret) gc.authenticate(tok1, tok2) pp = pprint.PrettyPrinter(indent=4) (res, mibook) = chkGoodReads(myisbn) if (res == 0): print("Sorry, book with isbn: {0} not found in GR".format(myisbn)) return 0 # TODO 2 diff ways to access gr, remove 1 # grbookid = session.get('https://www.goodreads.com/book/isbn_to_id', # {'isbn' : myisbn}) # print grbookid gid = mibook.gid print("Book found: gid:" + str(gid) + " isbn:", str(myisbn)) # if there is reason to believe that old session is not working ##session = graskaccess() #(tok1, tok2) = gettokens() session = grExistingSession(tok1, tok2) res = session.post('https://www.goodreads.com/shelf/add_to_shelf.xml', { 'name': 'currently-reading', 'book_id': gid }) #print("result:", res) return res
def __init__(self): self.API_KEY = os.getenv('API_KEY') self.API_SECRET = os.getenv('API_SECRET') self.ACCESS_TOKEN = os.getenv('ACCESS_TOKEN') self.ACCESS_TOKEN_SECRET = os.getenv('ACCESS_TOKEN_SECRET') if not self.API_KEY or not self.API_SECRET: logging.error("API key and secret not provided") self.gc = client.GoodreadsClient(self.API_KEY, self.API_SECRET) self.user_authenticated = False
def home_view(): if request.method == "GET": return render_template("main_page.html") api_key = "Eny1ro9b7mxhs8CuFj2o6w" api_secret = "bQKcvwYsv0ceEBjk95guDtguTXRUSgBxGPBT0YtxD6U" gc = client.GoodreadsClient(api_key, api_secret) user_id = int(request.form['user_id']) user = gc.user(user_id) if 'private' in list(user.__dict__['_user_dict'].keys( )) and user.__dict__['_user_dict']['private'] == 'true': return render_template( "main_page.html", successes= "Oops! Looks like your profile is on private. You can change this in Goodreads -> Account Settings -> Settings -> Privacy" ) gr_books = user.per_shelf_reviews(shelf_name="to-read") valid_books = [] error = False successful_processes = 0 shelf_size = 0 for book in gr_books: temp_book = book.book title = temp_book["title"] author = temp_book["authors"]["author"]["name"] results = bookOutletHas(title=title, author=author) if results: print(results) if results[0] == "ERROR": error = True continue else: successful_processes += 1 if results: for result in results: valid_books += [result] shelf_size += 1 successes = "Out of the " + str( shelf_size ) + " books processed from your Goodreads to-read shelf, " + str( successful_processes) + " are on Book Outlet" numrows = math.ceil(len(valid_books) / 4) return render_template("main_page.html", books=valid_books, err=error, successes=successes)
def getBooks(user_id, to_read, read): api_key = "Eny1ro9b7mxhs8CuFj2o6w" api_secret = "bQKcvwYsv0ceEBjk95guDtguTXRUSgBxGPBT0YtxD6U" gc = client.GoodreadsClient(api_key, api_secret) user = gc.user(user_id) if 'private' in list(user.__dict__['_user_dict'].keys( )) and user.__dict__['_user_dict']['private'] == 'true': print("PRIVATE") return [], [], [], -1 #gr_books = user.per_shelf_reviews(shelf_name = "currently-reading") gr_books = [] if to_read: gr_books += user.per_shelf_reviews(shelf_name="to-read") if read: gr_books += user.per_shelf_reviews(shelf_name="read") valid_books, error, successful_processes, shelf_size, leftover_books = getBooksHelper( gr_books) return valid_books, error, successful_processes, shelf_size
def chkGoodReads(myisbn): gc = client.GoodreadsClient(grkey, grsecret) isbn = "978-055-38-0371-6" # url = "https://www.goodreads.com/search[isbn]="+isbn try: book = gc.book(isbn=myisbn) except: print("Book with isbn {0} not found(?)\n".format(myisbn)) return (0, 0) print("\n", book.authors[0].name) print(book.title, book.gid) # , "by ", codecs.decode(str(book.authors[0].name)) # , "\n", book.description , "\n" return (1, book)
def main(): if request.method == 'GET': return render_template("main_page.html") if request.method == 'POST': api_key = "Eny1ro9b7mxhs8CuFj2o6w" api_secret = "bQKcvwYsv0ceEBjk95guDtguTXRUSgBxGPBT0YtxD6U" gc = client.GoodreadsClient(api_key, api_secret) if request.method == 'POST': user_id = int(request.form['user_id']) user = gc.user(user_id) books = user.per_shelf_reviews(shelf_name="currently-reading") valid_books = [] for review in books: temp_book = review.book title = temp_book["title"] author = temp_book["authors"]["author"]["name"] arr = bookOutletHas(title=title, author=author) if arr[0]: valid_books += [arr[1]] return render_template("main_page.html", sum=valid_books)
db = SQLAlchemy() bcrypt = Bcrypt() login_manager = LoginManager() login_manager.login_view = 'users.login' login_manager.login_message_category = 'info' mail = Mail() current_working_directory = Path(os.getcwd()) load_dotenv(os.path.join(current_working_directory, 'variables.env')) #setting up goodreads api goodreadsAPIKey = os.getenv('goodreadsAPIKey') goodreadsAPISecret = os.getenv('goodreadsAPISecret') gc = client.GoodreadsClient(goodreadsAPIKey,goodreadsAPISecret) #setting up tmdb movies api tmdb.API_KEY = os.getenv('tmdbAPIKey') #loading pretrained model and precomputed movies overview and books description vectors model = pickle.load(open(current_working_directory/'recommenderwebsite/word2vec.pkl','rb')) movie_vectors = pickle.load(open(current_working_directory/'recommenderwebsite/movies_overview_vectors.pkl','rb')) book_vectors = pickle.load(open(current_working_directory/'recommenderwebsite/books_description_vectors.pkl','rb')) def create_app(config_class = Config): """ Application factory function """ app = Flask(__name__) app.config.from_object(config_class) db.init_app(app)
import os import time from typing import List from betterreads import client from requests import get from tqdm import tqdm_notebook goodreads_api_key = os.environ.get("GOODREADS_API_KEY") goodreads_api_secret = os.environ.get("GOODREADS_API_SECRET") gc = client.GoodreadsClient(goodreads_api_key, goodreads_api_secret) def acquire_goodreads_id(isbn_numbers: List[str]) -> List[int]: """Collect Goodreads IDs using ISBNs and the Goodreads API. A 1 second delay is included in the function to avoid getting my IP address blocked. Args: isbn_numbers (List[str]): list of ISBNs for which we want to collect goodreads IDs. Returns: A list of goodreads IDs """ goodreads_id = [] for number in tqdm_notebook(isbn_numbers): base_url = "https://www.goodreads.com/book/isbn_to_id" params = {"key": goodreads_api_key, "isbn": number}
from betterreads import client key = 'UnJEUENuYcvAB9ZAWrD7Q' secret = 'RgEtOdnNHFxnkumatFOLgzPnfMeN0dQEJ8DbjLV4' gc = client.GoodreadsClient(key,secret) author = gc.author(2618) type(author) print(author)
# socket import from flask_socketio import SocketIO, send, emit # wrapping the app with the socket socketio = SocketIO(app, cors_allowed_origins="*") # get db user_collection = db.user_collection goodreads_user_coll = db.goodreads_coll dev_key = os.getenv('GOODREADS_DEV_KEY') dev_sec = os.getenv('GOODREADS_SECRET_KEY') # the goodread client # gc = client.GoodreadsClient(dev_key, dev_sec) goodreads = client.GoodreadsClient(dev_key, dev_sec) # gr_service = goodreads.auth_attempt() def authHelper(): # if user exists, use the session token / secret from db # print(user_collection.find_one({'user_id': })) if (hasattr(goodreads, 'session')): goodreads.authenticate_with_callback( access_token=goodreads.session.access_token, access_token_secret=goodreads.session.access_token_secret) @app.route("/", methods=["GET"]) def index():
def __authClient(self): self.gc = client.GoodreadsClient(self.api_key,self.api_secret) self.gc.authenticate(self.oauth_token,self.oauth_signature)
config_parser = configparser.ConfigParser() config_parser.read('config.ini') client_key = config_parser.get('Client Parameters', 'client_key', fallback=NOT_SET_VALUE) client_secret = config_parser.get('Client Parameters', 'client_secret', fallback=NOT_SET_VALUE) access_token = config_parser.get('Client Parameters', 'access_token', fallback=NOT_SET_VALUE) access_token_secret = config_parser.get('Client Parameters', 'access_token_secret', fallback=NOT_SET_VALUE) gc = client.GoodreadsClient(client_key, client_secret) if access_token == NOT_SET_VALUE: gc.authenticate() else: gc.authenticate(access_token, access_token_secret) access_token = gc.session.access_token access_token_secret = gc.session.access_token_secret config_parser['Client Parameters']['access_token'] = access_token config_parser['Client Parameters']['access_token_secret'] = access_token_secret with open('config.ini', 'w') as f: config_parser.write(f) user = gc.user() shelves = user.shelves() return_value = {
#print(nm + " VS " + od_author) if nm not in od_author: correct_author = False if correct_title and correct_author: #hasBook = True my_books += [[ author, title, link_url, image_url, available, booktype ]] #print("True") return my_books api_key = "Eny1ro9b7mxhs8CuFj2o6w" api_secret = "bQKcvwYsv0ceEBjk95guDtguTXRUSgBxGPBT0YtxD6U" user_id = "43329866" #ID of user to check the shelf of, can be found in url of user profile gc = client.GoodreadsClient(api_key, api_secret) user = gc.user(user_id) all_books = [] my_books = user.per_shelf_reviews(shelf_name="to-read") #tbr=list(review.book for review in my_books if review.book['num_pages'] is not None) tbr = list(review.book for review in my_books) #tbr_bypages = sorted(tbr, key=lambda k: int(k['num_pages'])) #by_pages = list( int(book['num_pages']) for book in tbr if book['num_pages'] is not None) categories = set() outof = len(tbr) i = 1 for book in tbr: title = book["title"] author = book["authors"]["author"]["name"] gr_id = int(book["id"]["#text"]) gr_book = gc.book(gr_id)