/
settingsConfig.py
199 lines (139 loc) · 6.23 KB
/
settingsConfig.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import re,consts,os,random
from utilities import tupleEntrys
from utilities import showDatabaseDictionary as showDD
from subprocess import call
from utilities import writeFile
def handleContextProcessors(settings,properties):
"""Generate the list of context processors"""
processors = """TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages",
"main.context_processors.loginForm",
"main.context_processors.logoutForm",
"main.context_processors.signupForm",
"django.core.context_processors.request"
)"""
return "%s\n\n#Context Processors\n%s" % (settings,processors)
def handleMiddleware(settings,properties):
"""Generate the list of middlware classes to be used"""
middle = """MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)"""
return "%s\n\n#Middleware classes\n%s" % (settings,middle)
def generateSecretKey(settings):
"""Makes and adds a secretkey to the settings file"""
key = ''.join([random.SystemRandom().choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])
return "%s\nSECRET_KEY = '%s'" % (settings,key)
def handleStatic(settings,properties):
"""Add static settings"""
lines = settings.split("\n")
mark = 2
for line in lines:
if "STATIC_URL" in line:
break
mark += 1
newLines = ["STATIC_ROOT = os.path.join(BASE_DIR,'static')", "", "STATICFILE_DIRS = ("]
for app in iter(properties["apps"]):
newLines.append(" os.path.join(BASE_DIR,'%s/static/')," % app)
newLines += [")"]
result = lines[:mark] + newLines + lines[mark:]
return "\n".join(result)
def handleTemplates(settings,properties):
"""Generates the template names"""
settings += "\n"
apps = properties["apps"]
result = "\n#Template directories\nTEMPLATE_DIRS = (\n"
apps = map(lambda x: "os.path.join(BASE_DIR, '%s/templates')" % (x), apps)
apps = tupleEntrys(apps,True) #encode for tuple
result += "\n".join(apps) + "\n)"
return settings + result
def handleApps(settings,properties):
"""Adds south and whatever other apps necessary"""
apps = ['south','main','django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.sites','django.contrib.messages','django.contrib.staticfiles'] #always include south and main
try:
for app in iter(properties["apps"]):
apps.append(app)
except KeyError:
pass #no apps, we will get an error about this in the appsConfig
apps = map(lambda x:" '%s'," % x, apps)
settings += "\nINSTALLED_APPS = (\n" + '\n'.join(apps) + ")"
return settings
def handleDatabase(settings,properties):
"""Configure the datbase settings"""
#cut out default database
lines = settings.split("\n")
mark = 0
for line in lines:
if line.startswith("# Database"):
break
mark += 1
lines = lines[:mark] + lines[mark+9:]
settings = "\n".join(lines)
try:
newDict = {}
for key in iter(properties["database"]):
newDict[key.upper()] = properties["database"][key]
except KeyError:
return settings
return "%s\nDATABASES = { 'default': %s }\n" % (settings, showDD(newDict))
def handleAdmins(settings,properties):
"""Configures admins in the settings file"""
website = properties["website"] #this is ensured by the parser
print "Adding administrators"
addstring = "\n#Administrators\nADMINS = (\n"
try:
admins = website["admins"]
adminList = []
for key in admins:
name, email = admins[key]['name'], admins[key]['email']
print "Found admin: %s" % name
adminList.append("('%s', '%s')" % (name, email))
adminList = tupleEntrys(adminList,True)
addstring += "\n".join(adminList) + "\n"
except KeyError:
print "No administrators specified."
addstring += ")\n"
return settings + "\n" + addstring
def handleSettings(settings_file, properties):
"""Reads the settings file and calls functions to edit it using properties
Once this is done it writes any changes and closes the file"""
#important basics might be editable later for now constant
contents = "import os\n"
contents += "BASE_DIR = os.path.dirname(os.path.abspath(__file__))\n\n"
contents += "SITE_ID = 1\n"
contents += "DEBUG = True\nTEMPLATE_DEBUG=DEBUG\n" #different in different sub settings files
contents += "ALLOWED_HOSTS = ['']\n\n" #this needs to be changable
contents += "ROOT_URLCONF = '%s.urls'\n" % properties['website']['name']
contents += "STATIC_URL = '/static/'\n"
contents += "WSGI_APPLICATION = '%s.wsgi.application'" % properties['website']['name'] #this is only for testing env
#middleware
contents = handleMiddleware(contents,properties)
#handle
contents = handleContextProcessors(contents,properties)
#generate secret key
contents = generateSecretKey(contents)
#add administrators
contents = handleAdmins(contents,properties)
contents += "MANAGERS = ADMINS\n"
#add installed apps and south
contents = handleApps(contents,properties)
#add in template dirs at the end
contents = handleTemplates(contents,properties)
#add static dirs and root
contents = handleStatic(contents,properties)
#setup the database
contents = handleDatabase(contents,properties)
#rewite changes
writeFile(settings_file,contents)
#last thing is to delete the pyc of the settings file otherwise it will be out of date
call(["rm", settings_file + "c"])