|
from pymongo import MongoClient
|
|
from bson.objectid import ObjectId
|
|
from datetime import datetime
|
|
import os
|
|
from dotenv import load_dotenv
|
|
load_dotenv()
|
|
|
|
uri = os.getenv('DATABASE_URL_')
|
|
client = MongoClient(uri)
|
|
db = client["blog_db"]
|
|
collection = db["posts"]
|
|
|
|
|
|
|
|
def add_post(title, content, status, username):
|
|
now = datetime.utcnow()
|
|
post = {
|
|
"title": title,
|
|
"content": content,
|
|
"createdAt": now,
|
|
"updatedAt": now,
|
|
"status": status,
|
|
"auther": username
|
|
}
|
|
collection.insert_one(post)
|
|
return "Post added successfully!"
|
|
|
|
|
|
|
|
def update_post(post_id, title, content, status):
|
|
|
|
try:
|
|
post_id = ObjectId(post_id)
|
|
except Exception as e:
|
|
return f"Invalid post ID: {str(e)}"
|
|
|
|
|
|
result = collection.update_one({"_id": post_id}, {"$set": {"title": title,
|
|
"content": content,
|
|
"status": status,
|
|
"updatedAt": datetime.utcnow(),
|
|
|
|
}})
|
|
|
|
if result.matched_count == 1:
|
|
return "Post updated successfully!"
|
|
else:
|
|
return "Post not found or no changes were made."
|
|
|
|
|
|
def delete_post(post_id):
|
|
collection.delete_one({"_id": ObjectId(post_id)})
|
|
return "Post deleted successfully!"
|
|
|
|
|
|
|
|
def get_post_titles(status):
|
|
titles = collection.find(
|
|
{"status": status},
|
|
{"_id": 1, "title": 1}
|
|
).sort("createdAt", -1)
|
|
|
|
return titles
|
|
|
|
|
|
|
|
def get_post_by_id(post_id):
|
|
post = collection.find_one({"_id": ObjectId(post_id)})
|
|
return post
|
|
|
|
|