import html
import urllib.parse
from translator import Translator
class Result:
def __init__(self, code, headers, data):
assert(type(code) is str)
assert(type(headers) is list)
self.code = code
self.headers = headers
self.data = data
def complete(self, start_response):
start_response(self.code, self.headers)
return self.data
class Answer(Translator):
def __init__(self, request):
super().__init__()
self.request = request
self.urlprefix = self.request.server.config['urlprefix']
self.urldataprefix = self.request.server.config['urldataprefix']
self.status = "200 OK"
self.headers = list()
self.datalist = None
self.data = None
self.text = ''
self.html = ''
self.uipath = list()
self.content = ''
self.errors = list()
self.fields = dict()
self.template = None
self.objects = dict()
def htmlescape(self, text):
return html.escape(str('' if text is None else text))
def urlescape(self, text):
return urllib.parse.quote(str('' if text is None else text))
def e(self, text):
return self.htmlescape(text)
def ue(self, text):
return self.urlescape(text)
def te(self, text):
return self.e( self.t(text) )
def encodedfield(self, name):
return self.e( self.fields.get(str(name), '') )
def add_uipath_entry(self, title, path):
assert(type(title) is str)
assert(type(path) is list)
self.uipath.append((title, path))
def complete_redirect(self, path = None):
self.status = '303 See Other'
self.headers.append( ('Location', self.request.get_urlpath_escaped(path)) )
return Result(self.status, self.headers, list())
def complete_error(self, status = None):
if not status is None:
self.status = status
return Result(self.status, list(), list())
def complete_data(self, data = None):
if not data is None:
self.data = data
if self.data is None:
self.data = bytes()
if not type(self.data) is bytes:
self.data = bytes(str(self.data), "utf8")
if not self.data and self.status == "200 OK":
self.status = "204 No Content"
size = 65536
self.datalist = []
for i in range(0, len(self.data), size):
self.datalist.append(self.data[i:i + size])
return Result(self.status, self.headers, self.datalist)
def complete_text(self, text = None):
if not text is None:
self.text = text
if self.text is None:
self.text = ""
return self.complete_data(text)
def complete_html(self, html = None):
if not html is None:
self.html = html
self.headers.append( ('Content-Type','text/html') );
return self.complete_text( self.html )
def complete_content(self, content = None, template = None):
if not content is None:
self.content = content
if not template is None:
self.template = template
return self.complete_html( self.template.wrap(self) if self.template else self.content )