cgistarter.py
Go to the documentation of this file.
1 #! /usr/bin/env python
2 
3 import os, sys, string, time, string
4 from pyclearsilver.log import *
5 
6 #debugfull()
7 debugoff()
8 
9 import gc
10 
11 try:
12  import warnings
13  warnings.resetwarnings()
14  warnings.filterwarnings("ignore")
15 except ImportError:
16  pass
17 
18 import neo_cgi, neo_cs, neo_util
19 
20 from pyclearsilver import CSPage
21 
22 import mimetypes
23 mimetypes.init(["/etc/mime.types"])
24 
25 
26 gConfig = None
27 def setConfig(config):
28  global gConfig
29  gConfig = config
30 
31  if not hasattr(gConfig, "gRequireUsername"): gConfig.gRequireUsername = 0
32  if not hasattr(gConfig, "gDataFilePaths"): gConfig.gDataFilePaths = []
33 
34 
35 def split_path(path):
36  # strip off leading slash, it's no fun!
37  return string.split(path, '/')[1:]
38 
39 
40 class Page:
41  def __init__(self, context):
42  self.context = context
43 
44  def setupvars(self):
45 
46  self.path = self.context.environ.get("PATH_INFO", '')
47 
48  script_name = self.context.environ.get("SCRIPT_NAME",'')
49 
50  ## handle the case where the site is located at '/'
51  if not self.path:
52  self.path = script_name
53  script_name = '/'
54 
55 
56  def start(self):
57  self.setupvars()
58 
59  self._path = self.path
60 
61  rpath = self._path
62  if not rpath: rpath = '/'
63 
64  if rpath == "/": rpath = gConfig.gDefaultPage
65 
66  self.path = split_path(rpath)
67 
68  username = None
69 
70  if len(self.path) == 0:
71  warn("no such path", self.path)
72  self.error(404)
73  return 404
74 
75  ## the url form should be:
76  ## /baseuri/username/module/script.py
77 
78  cwd = os.getcwd()
79  debug("CWD", cwd)
80 
81  module = gConfig.gDefaultModule
82 
83  if hasattr(gConfig, "gDataFilePaths"):
84  if self.path[0] in gConfig.gDataFilePaths:
85  fn = apply(os.path.join, [cwd,] + self.path)
86  return outputFile(self.context, fn)
87 
88  if gConfig.gRequireUsername:
89  username = self.path[0]
90  n = 1
91  else:
92  n = 0
93 
94  debug("self.path", self.path)
95 
96  if len(self.path) > 1:
97  module = self.path[n]
98  n = n + 1
99 
100  moduleRootPath = apply(os.path.join, ["mod", module])
101  handlerRoot = apply(os.path.join, ["mod", module, "cgibin"])
102  moduleTemplatePath = apply(os.path.join, [cwd, "mod", module, "templates"])
103  systemTemplatePath = apply(os.path.join, [cwd, "templates"])
104  systemJLIBPath = apply(os.path.join, [cwd, "jslib"])
105 
106  fn = apply(os.path.join, [cwd, moduleRootPath,] + self.path[n:])
107  debug("fn", fn)
108 
109  ## if requesting a file, then just output it to the browser.
110  if os.path.isfile(fn):
111  return outputFile(self.context, fn)
112 
113  ## manage the Python module Path
114  sys.path.insert(0, os.path.abspath(cwd))
115  sys.path.insert(0, os.path.abspath(moduleRootPath))
116 
117  debug("sys.path", sys.path)
118 
119  handlerPath = ''
120 
121  ## find the first *real* file in the path
122  ## the rest of the path becomes the pathinfo.
123  m = n
124  for m in range(len(self.path)-1, n-2, -1):
125  handlerPath = apply(os.path.join, [handlerRoot, ] + self.path[n:m+1])
126 # warn(m, len(self.path), handlerPath)
127 
128  if os.path.isdir(handlerPath):
129  sys.path.insert(0, handlerPath)
130  if os.path.isfile(handlerPath): break
131  if os.path.isdir(handlerPath): break
132 
133  if m+1 == len(self.path):
134  pathinfo = ''
135  else:
136  pathinfo = apply(os.path.join, self.path[m+1:])
137 
138  if os.path.isdir(handlerPath):
139  modulePath = handlerPath
140  moduleFilename = module + "_index.py"
141  handlerPath = os.path.join(modulePath, moduleFilename)
142  else:
143  modulePath, moduleFilename = os.path.split(handlerPath)
144 
145  debug(handlerPath, pathinfo)
146  #warn("PATH", handlerPath, pathinfo, modulePath, moduleFilename)
147  #warn("PATH", self.path)
148 
149  if not os.path.isfile(handlerPath):
150  self.error(404, handlerPath + " doesn't exist")
151  return 404
152 
153  import imp
154 
155  moduleName, ext = os.path.splitext(moduleFilename)
156 
157  #module = __import__(moduleName)
158  module = __import__("mod.%s.cgibin.%s" % (module, moduleName), {}, {}, (None,))
159 
160  os.chdir(modulePath)
161 # debug(mod)
162  page = module.run(self.context)
163  page.ncgi.hdf.setValue("CGI.BaseURI", gConfig.gBaseURL)
164 
165  if gConfig.gRequireUsername:
166  page.ncgi.hdf.setValue("CGI.Username", username)
167  page.username = username
168 
169  if hasattr(page, "checkLoginCookie"):
170  if not page._pageparms.has_key("nologin"):
171  try:
172  page.checkLoginCookie()
173  except CSPage.Redirected:
174  return
175 
176  page.ncgi.hdf.setValue("CGI.PathInfo", pathinfo)
177  page.clearPaths()
178  page.setPaths([moduleTemplatePath, systemTemplatePath, systemJLIBPath])
179  ret = page.start()
180 
181  try:
182  page.db.close()
183  except AttributeError: pass
184 
185  page = None
186 
187  return ret
188 
189  def error(self, ecode, reason=None):
190  import httpResponses
191  message = httpResponses.gHTTPResponses[ecode]
192 
193  template = httpResponses.errorMessage_Default
194  if ecode == 404:
195  template = httpResponses.errorMessage_404
196 
197  hdf = neo_util.HDF()
198  hdf.setValue("code", str(ecode))
199  if message: hdf.setValue("message", message)
200  if reason: hdf.setValue("reason", reason)
201 
202  for key,val in self.context.environ.items():
203  hdf.setValue("environ." + key, str(val))
204 
205  self.context.stdout.write("Content-Type: text/html\r\n")
206  self.context.setStatus(None, ecode)
207  self.context.stdout.write("Status: %s\r\n" % ecode)
208  self.context.stdout.write("\r\n")
209 
210  cs = neo_cs.CS(hdf)
211  cs.parseStr(template)
212  page = cs.render()
213 
214  self.context.stdout.write(page)
215 
216  warn("Error", message, reason)
217 
218 
219 def outputFile(context, fn):
220  fp = open(fn, "rb")
221  data = fp.read()
222  fp.close()
223 
224  context.setStatus(None, 200)
225 
226  imagetype, encoding = mimetypes.guess_type(fn)
227  debug("imagetype = %s fn = %s" % (imagetype,fn))
228 
229  lines = []
230 
231  if imagetype:
232  lines.append("Content-Type: %s" % imagetype)
233 
234  lines.append("Content-Length: %d" % len(data))
235 
236  stat = os.stat(fn)
237  mtime = stat.st_mtime
238  mod_str = time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime(mtime))
239 
240  lines.append('Last-Modified: %s GMT' % mod_str)
241 
242  expire_time = time.gmtime(time.time() + (360*24*3600))
243  expire_str = time.strftime("%a, %d %b %Y %H:%M:%S", expire_time)
244  lines.append('Expires: %s GMT' % expire_str)
245 
246  lines.append("\r\n")
247 
248  headers = string.join(lines, "\r\n")
249  context.stdout.write(headers)
250 
251  context.stdout.write(data)
252 
253  return 200
254 
255 
256 class FakeError:
257  def write(self, s):
258  apache.log_error(s, apache.APLOG_STARTUP)
259 
261  def __init__ (self, req):
262 
263  from mod_python import apache
264 
265  self.stdout = apache.CGIStdout(req)
266  self.stdin = apache.CGIStdin(req)
267 
268  self.stderr = FakeError()
269  env = apache.build_cgi_env(req)
270 
271  self.environ = env
272 
273  scriptFilename = self.environ.get("SCRIPT_FILENAME", "")
274  if scriptFilename:
275  path, fn = os.path.split(scriptFilename)
276  os.chdir(path)
277 
278  def setStatus(self, request, status):
279  if request:
280  request['status'] = str(status)
281 
282 
283 
284 def handler(req):
285  start = time.time()
286 
287  from mod_python import apache
288 
289  if 1:
290  context = ModPythonContext(req)
291  page = Page(context)
292  page.mod_python_req = req
293 
294  gc.enable()
295  ret = page.start()
296  gc.collect()
297 
298  ret = apache.OK
299 
300  end = time.time()
301  #sys.stderr.write("handler time %s\n" % int((end-start)*1000))
302 
303  return ret
304 
305 
306 def main(argv, stdout, environ):
307  context = CSPage.Context()
308  page = Page(context)
309  page.start()
310 
311 
312 if __name__ == "__main__":
313  main(sys.argv, sys.stdout, os.environ)
def warn(args)
Definition: log.py:100
def debugoff()
Definition: log.py:128
path
handle the case where the site is located at '/'
Definition: cgistarter.py:46
def __init__(self, context)
Definition: cgistarter.py:41
def setStatus(self, request, status)
Definition: cgistarter.py:278
def main(argv, stdout, environ)
Definition: cgistarter.py:306
def outputFile(context, fn)
Definition: cgistarter.py:219
def debug(args)
Definition: log.py:116
def error(self, ecode, reason=None)
Definition: cgistarter.py:189


pyclearsilver
Author(s): Scott Noob Hassan
autogenerated on Mon Jun 10 2019 15:51:13