-
Notifications
You must be signed in to change notification settings - Fork 0
/
configuration.py
100 lines (64 loc) · 2.22 KB
/
configuration.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#! /usr/bin/python
################################################################################
# configuration.py - Oct-3-2014 by aldeba
#
# Class for the webServer's configuration attributes
################################################################################
import json
# Configuration attributes class
class Configuration:
def __init__( self, name, description, portNumber ):
self.name = name
self.description = description
self.portNumber = portNumber
def __str__( self ):
return '{0.name!s}: {0.description!s}\nListening Port: {0.portNumber!s}'.format( self )
@classmethod
def serialize( cls, ref ):
attributes = {
'name': ref.name
, 'description': ref.description
, 'portNumber': ref.portNumber
}
return json.dumps( attributes )
@classmethod
def unserialize( cls, stream ):
attributes = json.loads( stream )
name = attributes[ 'name' ]
description = attributes[ 'description' ]
portNumber = attributes[ 'portNumber' ]
configurationAux = Configuration( name, description, portNumber )
return configurationAux
# ConfigurationFile class
class ConfigurationFile:
def __init__( self, fileName ):
self.fileName = fileName
def load( self ):
with open( self.fileName, 'r' ) as fileHandler:
attributes = json.load( fileHandler )
return Configuration.unserialize( attributes )
def save( self, configurationRef ):
with open( self.fileName, 'w' ) as fileHandler:
json.dump( Configuration.serialize( configurationRef ), fileHandler )
# unit test code
if( __name__ == '__main__' ):
# Configuration class unit test
print '[Configuration] unit test'
myConfiguration = Configuration( 'unit', 'Unit test configuration', 8080 )
print myConfiguration
print
attributes = Configuration.serialize( myConfiguration )
print attributes
print
myConfigurationAux = Configuration.unserialize( attributes )
print myConfigurationAux
print
# ConfigurationFile class unit test
print '[ConfigurationFile] unit test'
myConfigurationFile = ConfigurationFile( 'unitTest.config' )
myConfigurationFile.save( myConfiguration )
print 'Configuration file saved'
myConfigurationAux = myConfigurationFile.load()
print 'Configuration file loaded'
print myConfigurationAux
print