I have a web app that I run at work for the IT department. It just displays laptops that are ready for collection. The head office saw it and want me to build it so that it can be used across multiple sites, some of which have multiple campuses. I had it setup so the settings for the site were just global variables and they were saved to an .ini file and loaded when the app started. This isn't going to work now and I decided to make those settings properties of a class and depending on the path the client goes to will make an instance of the class and load the value of the properties from the section of the .ini file. This seems easy enough, however as not every site has more than one campus, I need to somehow not load information that isn't there. I'm not even sure what I'm looking for is called so i can't do a decent enough search to see if this has been resolved before. Below is some code as to what I'm trying to do:
# Site class
class site:
name = "" # Name of the site
siteID = "" # Site ID (also path of site specific noticeboard).
key = "" # Helpdesk API Key
url = "" # Helpdesk URL
campusCount = "" # Number of campuses
XCampusName = "" # Name of campus "X".
XCampusApprover = "" # Name of campus "X" return approver.
collectionName = "" # Name of collection status in helpdesk.
approvalName = "" # Name of approval status in helpdesk.
I thought I might need to have a secondary class that had the name of the campus and the name of the person who authorizes the return of devices, that somehow linked to the site instance but I can't figure out what to call that or how to phrase it to be able to google it. And being somewhat of a beginner who is doing this because it made my life easier, I'm not even sure if this is the right way to go about it. Any info would help.
Cheers!
The approach you're discussing is good. In which you'll need to create two separate classes named Site
and Campus
. Then, use campuses
as instance variable of the Site
class to reference Campus
class.
Here's the implementation:
class Campus:
def __init__(self, name, approver):
self.name = name
self.approver = approver
def __str__(self):
return self.name
class Site:
def __init__(self, name, site_id, key, url, collection_name, approval_name):
self.name = name
self.site_id = site_id
self.key = key
self.url = url
self.collection_name = collection_name
self.approval_name = approval_name
self.campuses = []
def add_campus(self, campus):
self.campuses.append(campus)
def get_campuses_count(self):
return len(self.campuses)
Now, define site classes, and add as many campuses as you want
site1 = Site("Site1", "ID1", "Key1", "URL1", "CollectionName1", "ApprovalName1")
campus1 = Campus("CampusName1", "Approver1")
site1.add_campus(campus1)
print(site1.campuses[0]) # will print "CampusName1"
print(site1.get_campuses_count()) # will print 1