class Request(object): def __init__(self,environ): self.environ = environ self.path = environ.get('PATH_INFO','').decode('utf8') self.method = environ.get('REQUEST_METHOD','') self.cookies = Cookie.SimpleCookie(str(environ.get('HTTP_COOKIE',''))) self.GET = MultiDict(cgi.parse_qsl(urllib2.unquote(environ.get('QUERY_STRING','')).decode('utf8'),keep_blank_values=1)) self.POST = {} self.FILES = {} if self.method == 'POST': post = cgi.FieldStorage(fp=environ.get('wsgi.input',''),environ=environ,keep_blank_values=1) self.POST = MultiDict([(item.name,item.value) for item in post.list if not item.filename]) self.FILES = MultiDict([(item.name,item) for item in post.list if item.filename]) self.REQUEST = MultiDict(self.GET.items() + self.POST.items()) # + self.FILES.items())
class Response(object): def __init__(self,body='',content_type='text/html',charset='utf8',redirect=None,status_code=None,status_msg=None): self.headers = MultiDict() self.content_type = content_type self.charset = charset self.body = body self.redirect = redirect self.status_code = status_code self.status_msg = status_msg self.cookies = Cookie.SimpleCookie() @property def status(self): status_map = {200:'OK',301:'Moved Permanently',302:'Found',404:'Not Found',500:'Internal Server Error'} if not self.status_msg: self.status_msg = status_map.get(self.status_code,'') return "%s %s" % (self.status_code,self.status_msg) def finalize(self): self.headers['Content-Type'] = '%s; charset=%s' % (self.content_type, self.charset) self.headers['Content-Length'] = len(self.body) if self.redirect: self.headers['Location'] = self.redirect self.status_code = self.status_code or 302 for key in self.cookies: self.cookies[key]['path'] = self.cookies[key]['path'] or '/' self.headers['Set-Cookie'] = self.cookies[key].OutputString() self.status_code = self.status_code or 200 self.headers = MultiDict([(safestr(k,self.charset),safestr(v,self.charset)) for (k,v) in self.headers.items()])