"""WSGI request adapter for cubicwebNOTE: each docstring tagged with ``COME FROM DJANGO`` means thatthe code has been taken (or adapted) from Djanco source code : http://www.djangoproject.com/:organization: Logilab:copyright: 2008-2009 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2.:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses"""__docformat__="restructuredtext en"fromStringIOimportStringIOfromurllibimportquotefromlogilab.common.decoratorsimportcachedfromcubicweb.web.requestimportCubicWebRequestBasefromcubicweb.wsgiimport(pformat,qs2dict,safe_copyfileobj,parse_file_upload,normalize_header)classCubicWebWsgiRequest(CubicWebRequestBase):"""most of this code COMES FROM DJANO """def__init__(self,environ,vreg,base_url=None):self.environ=environself.path=environ['PATH_INFO']self.method=environ['REQUEST_METHOD'].upper()self._headers=dict([(normalize_header(k[5:]),v)fork,vinself.environ.items()ifk.startswith('HTTP_')])https=environ.get("HTTPS")in('yes','on','1')self._base_url=base_urlorself.application_uri()post,files=self.get_posted_data()super(CubicWebWsgiRequest,self).__init__(vreg,https,post)iffilesisnotNone:forfdefinfiles.itervalues():fdef[0]=unicode(fdef[0],self.encoding)self.form.update(files)# prepare output headersself.headers_out={}def__repr__(self):# Since this is called as part of error handling, we need to be very# robust against potentially malformed input.form=pformat(self.form)meta=pformat(self.environ)return'<CubicWebWsgiRequest\FORM:%s,\nMETA:%s>'% \(form,meta)## cubicweb request interface ################################################defbase_url(self):returnself._base_urldefhttp_method(self):"""returns 'POST', 'GET', 'HEAD', etc."""returnself.methoddefrelative_path(self,includeparams=True):"""return the normalized path of the request (ie at least relative to the application's root, but some other normalization may be needed so that the returned path may be used to compare to generated urls :param includeparams: boolean indicating if GET form parameters should be kept in the path """path=self.environ['PATH_INFO']path=path[1:]# remove leading '/'ifincludeparams:qs=self.environ.get('QUERY_STRING')ifqs:return'%s?%s'%(path,qs)returnpathdefget_header(self,header,default=None):"""return the value associated with the given input HTTP header, raise KeyError if the header is not set """returnself._headers.get(normalize_header(header),default)defset_header(self,header,value,raw=True):"""set an output HTTP header"""assertraw,"don't know anything about non-raw headers for wsgi requests"self.headers_out[header]=valuedefadd_header(self,header,value):"""add an output HTTP header"""self.headers_out[header]=valuedefremove_header(self,header):"""remove an output HTTP header"""self.headers_out.pop(header,None)defheader_if_modified_since(self):"""If the HTTP header If-modified-since is set, return the equivalent mx date time value (GMT), else return None """returnNone## wsgi request helpers ###################################################defapplication_uri(self):"""Return the application's base URI (no PATH_INFO or QUERY_STRING) see python2.5's wsgiref.util.application_uri code """environ=self.environurl=environ['wsgi.url_scheme']+'://'ifenviron.get('HTTP_HOST'):url+=environ['HTTP_HOST']else:url+=environ['SERVER_NAME']ifenviron['wsgi.url_scheme']=='https':ifenviron['SERVER_PORT']!='443':url+=':'+environ['SERVER_PORT']else:ifenviron['SERVER_PORT']!='80':url+=':'+environ['SERVER_PORT']url+=quote(environ.get('SCRIPT_NAME')or'/')returnurldefget_full_path(self):return'%s%s'%(self.path,self.environ.get('QUERY_STRING','')and('?'+self.environ.get('QUERY_STRING',''))or'')defis_secure(self):return'wsgi.url_scheme'inself.environ \andself.environ['wsgi.url_scheme']=='https'defget_posted_data(self):files=Noneifself.method=='POST':ifself.environ.get('CONTENT_TYPE','').startswith('multipart'):header_dict=dict((normalize_header(k[5:]),v)fork,vinself.environ.items()ifk.startswith('HTTP_'))header_dict['Content-Type']=self.environ.get('CONTENT_TYPE','')post,files=parse_file_upload(header_dict,self.raw_post_data)else:post=qs2dict(self.raw_post_data)else:# The WSGI spec says 'QUERY_STRING' may be absent.post=qs2dict(self.environ.get('QUERY_STRING',''))returnpost,files@property@cacheddefraw_post_data(self):buf=StringIO()try:# CONTENT_LENGTH might be absent if POST doesn't have content at all (lighttpd)content_length=int(self.environ.get('CONTENT_LENGTH',0))exceptValueError:# if CONTENT_LENGTH was empty string or not an integercontent_length=0ifcontent_length>0:safe_copyfileobj(self.environ['wsgi.input'],buf,size=content_length)postdata=buf.getvalue()buf.close()returnpostdatadef_validate_cache(self):"""raise a `DirectResponse` exception if a cached page along the way exists and is still usable """# XXX# if self.get_header('Cache-Control') in ('max-age=0', 'no-cache'):# # Expires header seems to be required by IE7# self.add_header('Expires', 'Sat, 01 Jan 2000 00:00:00 GMT')# return# try:# http.checkPreconditions(self._twreq, _PreResponse(self))# except http.HTTPError, ex:# self.info('valid http cache, no actual rendering')# raise DirectResponse(ex.response)# Expires header seems to be required by IE7self.add_header('Expires','Sat, 01 Jan 2000 00:00:00 GMT')