comparison plugins/cherrypy/_cpdefaults.py @ 0:4385a7d0efd1 grumpy-goblin

Deleted and repushed it with the 'grumpy-goblin' branch. I forgot a y
author sirebral
date Tue, 14 Jul 2009 16:41:58 -0500
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:4385a7d0efd1
1 """
2 Copyright (c) 2004, CherryPy Team (team@cherrypy.org)
3 All rights reserved.
4
5 Redistribution and use in source and binary forms, with or without modification,
6 are permitted provided that the following conditions are met:
7
8 * Redistributions of source code must retain the above copyright notice,
9 this list of conditions and the following disclaimer.
10 * Redistributions in binary form must reproduce the above copyright notice,
11 this list of conditions and the following disclaimer in the documentation
12 and/or other materials provided with the distribution.
13 * Neither the name of the CherryPy Team nor the names of its contributors
14 may be used to endorse or promote products derived from this software
15 without specific prior written permission.
16
17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
18 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
21 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
24 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 """
28
29
30 """
31 A module containing a few utility classes/functions used by CherryPy
32 """
33
34 import time, thread, os, cpg
35 import cPickle as pickle
36
37 def _cpLogMessage(msg, context = '', severity = 0):
38 """ Default method for logging messages """
39
40 nowTuple = time.localtime(time.time())
41 nowStr = '%04d/%02d/%02d %02d:%02d:%02d' % (nowTuple[:6])
42 if severity == 0:
43 level = "INFO"
44 elif severity == 1:
45 level = "WARNING"
46 elif severity == 2:
47 level = "ERROR"
48 else:
49 lebel = "UNKNOWN"
50 try:
51 logToScreen = int(cpg.configOption.logToScreen)
52 except:
53 logToScreen = True
54 s = nowStr + ' ' + context + ' ' + level + ' ' + msg
55 if logToScreen:
56 print s
57 if cpg.configOption.logFile:
58 f = open(cpg.configOption.logFile, 'ab')
59 f.write(s + '\n')
60 f.close()
61
62 def _cpOnError():
63 """ Default _cpOnError method """
64
65 import traceback, StringIO
66 bodyFile = StringIO.StringIO()
67 traceback.print_exc(file = bodyFile)
68 cpg.response.body = [bodyFile.getvalue()]
69 cpg.response.headerMap['Content-Type'] = 'text/plain'
70
71 def _cpSaveSessionData(sessionId, sessionData, expirationTime,
72 threadPool = None, sessionStorageType = None,
73 sessionStorageFileDir = None):
74 """ Save session data if needed """
75
76 if threadPool is None:
77 threadPool = cpg.configOption.threadPool
78 if sessionStorageType is None:
79 sessionStorageType = cpg.configOption.sessionStorageType
80 if sessionStorageFileDir is None:
81 sessionStorageFileDir = cpg.configOption.sessionStorageFileDir
82
83 t = time.localtime(expirationTime)
84 if sessionStorageType == 'file':
85 fname=os.path.join(sessionStorageFileDir,sessionId)
86 if threadPool > 1:
87 cpg._sessionFileLock.acquire()
88 f = open(fname,"wb")
89 pickle.dump((sessionData, expirationTime), f)
90 f.close()
91 if threadPool > 1:
92 cpg._sessionFileLock.release()
93
94 elif sessionStorageType=="ram":
95 # Update expiration time
96 cpg._sessionMap[sessionId] = (sessionData, expirationTime)
97
98 """ TODO: implement cookie storage type
99 elif sessionStorageType == "cookie":
100
101 TODO: set siteKey in _cpConfig
102 # Get site key from config file or compute it
103 try: cpg._SITE_KEY_ = configFile.get('server','siteKey')
104 except:
105 _SITE_KEY_ = ''
106 for i in range(30):
107 _SITE_KEY_ += random.choice(string.letters)
108
109 # Update expiration time
110 sessionData = (sessionData, expirationTime)
111 dumpStr = pickle.dumps(_sessionData)
112 try: dumpStr = zlib.compress(dumpStr)
113 except: pass # zlib is not available in all python distros
114 dumpStr = binascii.hexlify(dumpStr) # Need to hexlify it because it will be stored in a cookie
115 cpg.response.simpleCookie['CSession'] = dumpStr
116 cpg.response.simpleCookie['CSession-sig'] = md5.md5(dumpStr + cpg.configOption.siteKey).hexdigest()
117 cpg.response.simpleCookie['CSession']['path'] = '/'
118 cpg.response.simpleCookie['CSession']['max-age'] = sessionTimeout * 60
119 cpg.response.simpleCookie['CSession-sig']['path'] = '/'
120 cpg.response.simpleCookie['CSession-sig']['max-age'] = sessionTimeout * 60
121 """
122
123 def _cpLoadSessionData(sessionId, threadPool = None, sessionStorageType = None,
124 sessionStorageFileDir = None):
125 """ Return the session data for a given sessionId.
126 The _expirationTime will be checked by the caller of this function
127 """
128
129 if threadPool is None:
130 threadPool = cpg.configOption.threadPool
131 if sessionStorageType is None:
132 sessionStorageType = cpg.configOption.sessionStorageType
133 if sessionStorageFileDir is None:
134 sessionStorageFileDir = cpg.configOption.sessionStorageFileDir
135
136 if sessionStorageType == "ram":
137 if cpg._sessionMap.has_key(sessionId):
138 return cpg._sessionMap[sessionId]
139 else: return None
140
141 elif sessionStorageType == "file":
142 fname = os.path.join(sessionStorageFileDir, sessionId)
143 if os.path.exists(fname):
144 if threadPool > 1:
145 cpg._sessionFileLock.acquire()
146 f = open(fname, "rb")
147 sessionData = pickle.load(f)
148 f.close()
149 if threadPool > 1:
150 cpg._sessionFileLock.release()
151 return sessionData
152 else: return None
153
154 """ TODO: implement cookie storage type
155 elif _sessionStorageType == "cookie":
156 if request.simpleCookie.has_key('CSession') and request.simpleCookie.has_key('CSession-sig'):
157 data = request.simpleCookie['CSession'].value
158 sig = request.simpleCookie['CSession-sig'].value
159 if md5.md5(data + cpg.configOption.siteKey).hexdigest() == sig:
160 try:
161 dumpStr = binascii.unhexlify(data)
162 try: dumpStr = zlib.decompress(dumpStr)
163 except: pass # zlib is not available in all python distros
164 dumpStr = pickle.loads(dumpStr)
165 return dumpStr
166 except: pass
167 return None
168 """
169
170 def _cpCleanUpOldSessions(threadPool = None, sessionStorageType = None,
171 sessionStorageFileDir = None):
172 """ Clean up old sessions """
173
174 if threadPool is None:
175 threadPool = cpg.configOption.threadPool
176 if sessionStorageType is None:
177 sessionStorageType = cpg.configOption.sessionStorageType
178 if sessionStorageFileDir is None:
179 sessionStorageFileDir = cpg.configOption.sessionStorageFileDir
180
181 # Clean up old session data
182 now = time.time()
183 if sessionStorageType == "ram":
184 sessionIdToDeleteList = []
185 for sessionId, (dummy, expirationTime) in cpg._sessionMap.items():
186 if expirationTime < now:
187 sessionIdToDeleteList.append(sessionId)
188 for sessionId in sessionIdToDeleteList:
189 del cpg._sessionMap[sessionId]
190
191 elif sessionStorageType=="file":
192 # This process is very expensive because we go through all files, parse them and then delete them if the session is expired
193 # One optimization would be to just store a list of (sessionId, expirationTime) in *one* file
194 sessionFileList = os.listdir(sessionStorageFileDir)
195 for sessionId in sessionFileList:
196 try:
197 dummy, expirationTime = _cpLoadSessionData(sessionId)
198 if expirationTime < now:
199 os.remove(os.path.join(sessionStorageFileDir, sessionId))
200 except:
201 pass
202
203 elif sessionStorageType == "cookie":
204 # Nothing to do in this case: the session data is stored on the client
205 pass
206
207 _cpFilterList = []