1
0
mirror of https://github.com/ltcptgeneral/cs239-caching.git synced 2025-04-04 05:23:26 +00:00

30 lines
1.2 KiB
Python

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!"}
])