add execute_many method to Database class and update fetch_reddit endpoint to insert posts into database

This commit is contained in:
2026-01-11 14:44:22 +00:00
parent 1e9eb11aa1
commit 5e1bccb2a8
2 changed files with 12 additions and 2 deletions

View File

@@ -21,6 +21,10 @@ class Database:
if cursor.description: if cursor.description:
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()

View File

@@ -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)