api done
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
from .postgresql_database import postgresql_db_handler
|
||||
from .mongodb_database import mongo_db_handler
|
||||
Binary file not shown.
@@ -0,0 +1,4 @@
|
||||
from .connection import MONGODB_CONFIG, MongoDbHandler
|
||||
|
||||
mongo_db_handler = MongoDbHandler(**MONGODB_CONFIG)
|
||||
mongo_db_handler.connect()
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,36 @@
|
||||
from pymongo import MongoClient
|
||||
|
||||
MONGODB_CONFIG = {
|
||||
'host': 'localhost',
|
||||
'port': 27017,
|
||||
'dbname': 'local',
|
||||
'collection': 'messenger'
|
||||
}
|
||||
|
||||
|
||||
class MongoDbHandler:
|
||||
def __init__(self, dbname, collection, host, port):
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.dbname = dbname
|
||||
self.collection_name = collection
|
||||
self.client = None
|
||||
self.collection = None
|
||||
|
||||
def connect(self):
|
||||
try:
|
||||
self.client = MongoClient(self.host, self.port)
|
||||
db = self.client[self.dbname]
|
||||
self.collection = db[self.collection_name]
|
||||
print("Connected to MongoDB")
|
||||
except Exception as e:
|
||||
self.collection = None
|
||||
|
||||
def close_client(self):
|
||||
if self.client:
|
||||
self.client.close()
|
||||
self.collection = None
|
||||
print("MongoDB client closed.")
|
||||
|
||||
def get_collection(self):
|
||||
return self.collection
|
||||
@@ -0,0 +1,4 @@
|
||||
from .connection import POSTGRESQL_CONFIG, PostgreSQLHandler
|
||||
|
||||
postgresql_db_handler = PostgreSQLHandler(**POSTGRESQL_CONFIG)
|
||||
postgresql_db_handler.connect()
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,54 @@
|
||||
import psycopg2
|
||||
|
||||
|
||||
class PostgreSQLHandler:
|
||||
def __init__(self, dbname, user, password, host, port):
|
||||
self.dbname = dbname
|
||||
self.user = user
|
||||
self.password = password
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.connection = None
|
||||
|
||||
def connect(self):
|
||||
try:
|
||||
self.connection = psycopg2.connect(
|
||||
dbname=self.dbname,
|
||||
user=self.user,
|
||||
password=self.password,
|
||||
host=self.host,
|
||||
port=self.port
|
||||
)
|
||||
print("Connected to PostgreSQL.")
|
||||
return self.connection
|
||||
except psycopg2.Error as e:
|
||||
print(f"Error: Unable to connect to the PostgreSQL database\n{e}")
|
||||
return None
|
||||
|
||||
def execute_query(self, query, params=None, fetchall=False):
|
||||
try:
|
||||
with self.connection.cursor() as cursor:
|
||||
cursor.execute(query, params)
|
||||
if fetchall:
|
||||
result = cursor.fetchall()
|
||||
return result
|
||||
else:
|
||||
self.connection.commit() # Commit the transaction for INSERT, UPDATE, DELETE queries
|
||||
except psycopg2.Error as e:
|
||||
print(f"Error: Unable to execute the query\n{e}")
|
||||
return None
|
||||
|
||||
def close(self):
|
||||
if self.connection:
|
||||
self.connection.close()
|
||||
print("PostgreSQL connection closed.")
|
||||
self.connection = None
|
||||
|
||||
|
||||
POSTGRESQL_CONFIG = {
|
||||
'dbname': 'vliwybbf',
|
||||
'user': 'vliwybbf',
|
||||
'password': 'X0fhZ6NT3mjT7rbgZ5lQQ6ZYQpVyUwxq',
|
||||
'host': 'rogue.db.elephantsql.com',
|
||||
'port': '5432'
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,62 @@
|
||||
from database import postgresql_db_handler, mongo_db_handler
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
def create_conversation(user1_id, user2_id):
|
||||
query = '''
|
||||
SELECT conversation_url FROM conversations
|
||||
WHERE id_user1 = %s AND id_user2 = %s
|
||||
'''
|
||||
params = (user1_id, user2_id)
|
||||
existing_conversation = postgresql_db_handler.execute_query(query, params, fetchall=True)
|
||||
|
||||
if existing_conversation:
|
||||
conversation_url = existing_conversation[0][0]
|
||||
else:
|
||||
current_datetime = datetime.now().strftime("%Y%m%d%H%M%S")
|
||||
unique_id = str(uuid.uuid4()).replace('-', '')
|
||||
conversation_url = f"{current_datetime}_{unique_id}"
|
||||
|
||||
query = '''
|
||||
INSERT INTO conversations (id_user1, id_user2, conversation_url)
|
||||
VALUES (%s, %s, %s)
|
||||
'''
|
||||
params = (user1_id, user2_id, conversation_url)
|
||||
postgresql_db_handler.execute_query(query, params)
|
||||
|
||||
return conversation_url
|
||||
|
||||
|
||||
def find_conversation(conversation_url):
|
||||
collection = mongo_db_handler.get_collection()
|
||||
query = {'name': conversation_url}
|
||||
result_set = collection.find_one(query)
|
||||
|
||||
if result_set:
|
||||
return {'chat': result_set['chat']}
|
||||
return None
|
||||
|
||||
|
||||
def send_message_to_mongodb(conversation_url, sender, message):
|
||||
try:
|
||||
collection = mongo_db_handler.get_collection()
|
||||
existing_document = collection.find_one({"name": conversation_url})
|
||||
|
||||
if existing_document is not None:
|
||||
new_message = {"sender": sender, "message": message, "timestamp": datetime.now()}
|
||||
collection.update_one(
|
||||
{"name": conversation_url},
|
||||
{"$push": {"chat": new_message}}
|
||||
)
|
||||
else:
|
||||
collection.insert_one({
|
||||
"name": conversation_url,
|
||||
"chat": [{"sender": sender, "message": message, "timestamp": datetime.now()}]
|
||||
})
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"Unable to send message to MongoDB: {str(e)}")
|
||||
return False
|
||||
@@ -0,0 +1,56 @@
|
||||
from database import postgresql_db_handler
|
||||
|
||||
|
||||
def get_user_by_id(user_id):
|
||||
query = """
|
||||
SELECT * FROM users WHERE id = %s;
|
||||
"""
|
||||
params = (user_id,)
|
||||
result = postgresql_db_handler.execute_query(query, params, fetchall=True)
|
||||
if result:
|
||||
user_data = result[0]
|
||||
return user_data
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
def get_user_by_email(email):
|
||||
query = """
|
||||
SELECT * FROM users WHERE email = %s;
|
||||
"""
|
||||
params = (email,)
|
||||
result = postgresql_db_handler.execute_query(query, params, fetchall=True)
|
||||
if result:
|
||||
user_data = result[0]
|
||||
return user_data
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
def create_user_db(username, password, email):
|
||||
query = """
|
||||
INSERT INTO users (username, password, email)
|
||||
VALUES (%s, %s, %s);
|
||||
"""
|
||||
params = (username, password, email)
|
||||
postgresql_db_handler.execute_query(query, params)
|
||||
|
||||
|
||||
def update_user_db(user_id, new_username, new_password, new_email):
|
||||
query = """
|
||||
UPDATE users
|
||||
SET username = %s, password = %s, email = %s
|
||||
WHERE id = %s;
|
||||
"""
|
||||
params = (new_username, new_password, new_email, user_id)
|
||||
postgresql_db_handler.execute_query(query, params)
|
||||
print(f"User with ID {user_id} updated successfully.")
|
||||
|
||||
|
||||
def delete_user_db(user_id):
|
||||
query = """
|
||||
DELETE FROM users WHERE id = %s;
|
||||
"""
|
||||
params = (user_id,)
|
||||
postgresql_db_handler.execute_query(query, params)
|
||||
print(f"User with ID {user_id} deleted successfully.")
|
||||
Reference in New Issue
Block a user