Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
# Reference: Database Using Python Pandas
# https://www.youtube.com/watch?v=_nYbrut66cc
# Reference: Miscellaneous operating system interfaces
# https://docs.python.org/3/library/os.html
import pandas as pd # to manipulate data in .csv format
import os # to create directories and check their existence
class DatabaseManager:
"""
Method: checkDatabaseExists.
Checks if the .csv files that contain user and subscription data exist in the script folder.
If they do not exist:
- Creates a ./data folder
- Creates two Pandas Dataframes that will contain user and subscription data.
- Saves the Dataframes in two separate .csv files inside the ./data folder
"""
def checkDatabaseExists(self):
# creates data folder if it doesn't exist
if not os.path.exists("./data"):
print("Creating data folder...")
os.mkdir("data")
# database files
files = ["users.csv", 'subscriptions.csv'] # Declare a list of strings with the names of the files it wants to use
for file in files:
# checks if files exist, otherwise it creates them
if not os.path.exists(f"./data/{file}"):
print(f"{file} Not Exists")
print(f"Creating {file}...")
if 'users' in file:
# Creates the Pandas Dataframe and saves it in the users.csv file
df = pd.DataFrame({
"name": [],
"username": [],
"password": [],
})
# saves the dataframe into users.csv
df.to_csv("./data/users.csv", index=False)
elif 'subscriptions' in file:
# Creates the Pandas Dataframe and saves it in the subscriptions.csv file
df = pd.DataFrame({
"username": [],
"email": [],
"business": [],
"finance": [],
"computer": [],
"games": [],
"entertainment": [],
"music": [],
"currentAffairs": [],
"health": [],
"lifestyle": [],
"sports": [],
"culture": [],
"religion": [],
})
# saves the dataframe into subscriptions.csv
df.to_csv("./data/subscriptions.csv", index=False)
'''
Method: getUsersDF
- Calls the checkDatabaseExists method
- Reads and returns the dataframe containing the user data
'''
def getUsersDF(self):
self.checkDatabaseExists()
df = pd.read_csv("./data/users.csv")
return df
'''
Method: getSubscriptionsDF
- Calls the checkDatabaseExists method
- Reads and returns the dataframe containing the subscriptions data
'''
def getSubscriptionsDF(self):
self.checkDatabaseExists()
df = pd.read_csv("./data/subscriptions.csv")
return df
'''
Method: printSubscriptions
- Calls the getSubscriptionsDF method
- Prints the subscriptions table
'''
def printSubscriptions(self):
print(self.getSubscriptionsDF())
'''
Method: deleteUser
Param: username
- Checks if username is contained in the users.csv table
- Delete the username records from files
- Saves the changes made
'''
def deleteUser(self, uname):
dfSub = self.getSubscriptionsDF()
dfUsers = self.getUsersDF()
if dfSub['username'].str.contains(uname).any(): # if username exists in any record
# print("Username found in database")
# Deletes the row from the dfSub table that contains 'uname' in the username field.
# With inplace = True the table is modified without creating a copy
dfSub.drop(dfSub[dfSub['username'] == uname].index, inplace=True)
# Deletes the row from the dfUsers table that contains 'uname' in the username field.
dfUsers.drop(dfUsers[dfUsers['username'] == uname].index, inplace=True)
# saves the new .csv files
dfSub.to_csv("./data/subscriptions.csv", index=False)
dfUsers.to_csv("./data/users.csv", index=False)
print(f"User {uname} deleted successfully")
else: # if user is not found
print("username not found")
'''
Method: getSubscriptionsFor
Param: username
- Returns the Dataframe record that contains the entered username and all its subscriptions
'''
def getSubscriptionsFor(self,uname):
df = self.getSubscriptionsDF()
data = df[df['username'] == uname]
return data
'''
Method: getSubscriptionsCategories
- Returns the columns of the subscriptions table starting from the third
'''
def getSubscriptionsCategories(self):
return self.getSubscriptionsDF().columns[2:]
'''
Method: subscribeUserToCategory
- Inserts the 'y' character in the column indicated by the category parameter
- Save the dataframe in the appropriate file.
'''
def subscribeUserToCategory(self,uname,category):
df = self.getSubscriptionsDF() # # gets the subscriptions dataframe
df.loc[df.username == uname, category] = 'y'# property that allows to locate the desired cell
# Inserts the 'y' character in the column indicated by the category parameter
self.__saveSubscriptionsDF(df) # calls the function to save the file (to_csv)
print(f"{uname} successfully subscribed to {category}")
'''
Method: unsubscribeUserFromCategory
- Inserts the 'n' character in the column indicated by the category parameter
- Save the dataframe in the appropriate file.
'''
def unsubscribeUserFromCategory(self, uname, category):
df = self.getSubscriptionsDF() # gets the subscriptions dataframe
df.loc[df.username == uname, category] = 'n' # property that allows to locate the desired cell
# Inserts the 'n' character in the column indicated by the category parameter
self.__saveSubscriptionsDF(df)
print("you unsubscribed successfully from this category")
def __saveSubscriptionsDF(self,df):
df.to_csv("./data/subscriptions.csv", index=False)
def __saveUsersDF(self,df):
df.to_csv("./data/users.csv", index=False)
'''
Method: unsubscribefromAll
- Inserts the character 'n' in all columns of the row referring to the user.
- Save the dataframe in the appropriate file.
'''
def unsubscribeFromAll(self, uname):
df = self.getSubscriptionsDF() # gets the subscriptions dataframe
for category in self.getSubscriptionsCategories(): # for each column in the table
df.loc[df.username == uname, category] = 'n' # property that allows to locate the desired cell
# Inserts the 'n' character in the column indicated by the category parameter
self.__saveSubscriptionsDF(df) # saves changes
print("you unsubscribed successfully from all news categories")
'''
Method: userExists
Param: uname
- Checks if the entered username is contained in at least one record of the table
'''
def userExists(self,uname):
df = self.getUsersDF()
return df['username'].str.contains(uname).any()
# any () is used to determine if there is at least one element where the contains () condition is true
'''
Method: regUser
Param: uname , name, email, password
- Checks if the username entered is contained in at least one record of the table
- Creates the dictionaries related to the users table and to the subscriptions table
- Sets initial values
- Inserts the two records with the user's data and his subscriptions using the append() method
- Save the two csv files
'''
def regUser(self, uname,name, email,password):
if not self.userExists(uname):
# Creates the dictionary that represents the record with the user data (it will go into the DFUsers table)
udata = {
"username": uname,
"name": name,
"password": password,
}
# Creates the dictionary that represents the record with the subscriptions data (it will go into the DFSubscriptions table)
sdata = {
"username": uname,
"email": email,
"business": 'n',
"finance": 'n',
"computer": 'n',
"games": 'n',
"entertainment": 'n',
"music": 'n',
"currentAffairs": 'n',
"health": 'n',
"lifestyle": 'n',
"sports": 'n',
"culture": 'n',
"religion": 'n',
}
dfUsers = self.getUsersDF() # It takes a reference to the DFUsers table
dfSub = self.getSubscriptionsDF() # It takes a reference to the DFSubscriptions table
# Inserts the user data records by using the append() method
dfUsers = dfUsers.append(udata, ignore_index=True)
self.__saveUsersDF(dfUsers) #salva
# # Inserts the subscriptions data records by using the append() method
dfSub = dfSub.append(sdata, ignore_index=True)
self.__saveSubscriptionsDF(dfSub) #salva
# output if everything completes
print("You are successfully registed but not subscribed to any list. Please, login to your account to select any subscription.")
else:
print("Username already exists")