summaryrefslogtreecommitdiffstats
path: root/py-bin/utils.py
blob: b13949ec4ecc9bcb8185480600172a19003ea294 (plain)
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
#helper functions/classes

import string, logging, re, os, urllib
import lib.jon.cgi as cgi, lib.jon.session as session
import lib.em as em
import config

def xmap(function, data):
	if isinstance(data, str):
		return function(data)
	if isinstance(data, int) or isinstance(data, long) or isinstance(data, float):
		return function(str(data))
	if isinstance(data, list):
		return map(lambda x: xmap(function, x), data)
	if isinstance(data, tuple):
		return tuple(xmap(function, list(data)))

def html_encode_struct(data):
	return xmap(cgi.html_encode, data)

def __empy_render_step(interpreter, filename, context_raw):
	path = os.path.join(config.template_dir, filename)
	out = interpreter.expand(file(path).read(), context_raw)
	if "em_inherit" in context_raw:
		filename = context_raw["em_inherit"]
		del(context_raw["em_inherit"])
		context_raw["em_child_content"] = out
		out = __empy_render_step(interpreter, filename, context_raw)
	return out

def empy_render(filename, context={}, context_raw={}):
	for k in context.keys():
		context[k] = html_encode_struct(context[k])
	context_raw.update(context)
	interpreter = em.Interpreter()
	out = __empy_render_step(interpreter, filename, context_raw)
	interpreter.shutdown()
	return out

if config.debugmode:
	HandlerBaseClass = cgi.DebugHandler
else:
	HandlerBaseClass = cgi.Handler
class BasicHandler(HandlerBaseClass):
	def process(self, req):
		self.session = session.FileSession(req, config.the_secret, config.session_dir)
		req.set_header("Content-Type", "text/html; charset=utf-8")	
		self.do_process(req)
		self.session.save()
		
	def render_template(self, req, filename, context={}, context_raw={}):
		req.write(empy_render(filename, context, context_raw))

	def error_page(self, req, message):
		self.render_template(req, "error.em", dict(message=message))
	
	def make_url(self, params):
		return config.script_url + "?" + urllib.urlencode(params)
				
	def redirect_to(self, req, url):
		req.set_header("Status", "302 Temporarily moved")
		req.set_header("Location", url)

def process_request(handler):
	cgi.CGIRequest(handler).process()
	
def set_logging_defaults():
	logging.basicConfig(level=logging.DEBUG,
		format='%(asctime)s %(levelname)-8s %(message)s',
		datefmt='%d.%m.%Y %H:%M:%S',
		filename=config.logfile_path)