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


webui
Author(s): Scott Hassan
autogenerated on Mon Jun 10 2019 15:51:24