add execute_many method to Database class and update fetch_reddit endpoint to insert posts into database
This commit is contained in:
@@ -22,5 +22,9 @@ class Database:
|
|||||||
return cursor.fetchall()
|
return cursor.fetchall()
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
def execute_many(self, query: str, params_list: list[tuple]):
|
||||||
|
with self.connection.cursor(cursor_factory=RealDictCursor) as cursor:
|
||||||
|
cursor.executemany(query, params_list)
|
||||||
|
|
||||||
def close(self):
|
def close(self):
|
||||||
self.connection.close()
|
self.connection.close()
|
||||||
@@ -7,11 +7,17 @@ db = Database(db_name='ethnograph', user='ethnograph_user', password='ethnograph
|
|||||||
|
|
||||||
reddit_connector = RedditConnector()
|
reddit_connector = RedditConnector()
|
||||||
|
|
||||||
@app.route('/get_reddit_posts/<string:search>/<int:limit>', methods=['GET'])
|
@app.route('/fetch_reddit/<string:search>/<int:limit>', methods=['GET'])
|
||||||
def index(search, limit = 10):
|
def index(search, limit = 10):
|
||||||
posts = reddit_connector.search_posts(search, limit=limit)
|
posts = reddit_connector.search_posts(search, limit=limit)
|
||||||
return {"posts": [post.__dict__ for post in posts]}
|
|
||||||
|
|
||||||
|
db.execute_many(
|
||||||
|
"""INSERT INTO ethnograph.posts (title, content, author_username, created_utc)
|
||||||
|
VALUES (%s, %s, %s, to_timestamp(%s));""",
|
||||||
|
[(post.title, post.content, post.author, post.timestamp) for post in posts]
|
||||||
|
)
|
||||||
|
|
||||||
|
return {"status": "success", "inserted_posts": len(posts)}
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
app.run(debug=True)
|
app.run(debug=True)
|
||||||
Reference in New Issue
Block a user