mirror of
https://github.com/ltcptgeneral/cs239-caching.git
synced 2026-02-03 06:31:02 +00:00
[ADD] - Added social media user profile get and upsert microservice with nosql database integration
This commit is contained in:
29
app/database.py
Normal file
29
app/database.py
Normal file
@@ -0,0 +1,29 @@
|
||||
|
||||
from tinydb import TinyDB, Query
|
||||
|
||||
# Initialize TinyDB as a NoSQL key-value store
|
||||
DB_FILE = "database.json"
|
||||
db = TinyDB(DB_FILE)
|
||||
User = Query()
|
||||
|
||||
def get_user_profile(user_id):
|
||||
"""Fetch user profile from TinyDB"""
|
||||
result = db.search(User.user_id == user_id)
|
||||
return result[0] if result else None
|
||||
|
||||
def update_user_profile(user_id, name, followers, bio, posts):
|
||||
"""Update user profile in TinyDB"""
|
||||
db.upsert({"user_id": user_id, "name": name, "followers": followers, "bio": bio, "posts": posts}, User.user_id == user_id)
|
||||
|
||||
def init_db():
|
||||
"""Ensure TinyDB is initialized before FastAPI starts and prepopulate some data"""
|
||||
global db
|
||||
db = TinyDB(DB_FILE) # Reload TinyDB if needed
|
||||
|
||||
# Prepopulate database with some sample users if empty
|
||||
if len(db) == 0:
|
||||
db.insert_multiple([
|
||||
{"user_id": "1", "name": "Alice", "followers": 100, "bio": "Love coding!", "posts": "Hello, world!"},
|
||||
{"user_id": "2", "name": "Bob", "followers": 200, "bio": "Tech enthusiast", "posts": "AI is amazing!"},
|
||||
{"user_id": "3", "name": "Charlie", "followers": 50, "bio": "Blogger", "posts": "Check out my latest post!"}
|
||||
])
|
||||
Reference in New Issue
Block a user