def generate_headers(self): """generate_headers() -> [(name:string, value:string)] Generate a list of headers to be returned as part of the response. """ headers = [] # "Status" header must come first. headers.append( ("Status", "%03d %s" % (self.status_code, self.reason_phrase))) for name, value in self.headers.items(): headers.append((name.title(), value)) # All the "Set-Cookie" headers. if self.cookies: headers.extend(self._gen_cookie_headers()) # Date header now = time.time() if not self.headers.has_key("date"): headers.append(("Date", formatdate(now))) # Cache directives if self.cache is None: pass # don't mess with the expires header elif not self.headers.has_key("expires"): if self.cache > 0: expire_date = formatdate(now + self.cache) else: expire_date = "-1" # allowed by HTTP spec and may work better # with some clients headers.append(("Expires", expire_date)) return headers
def __call__(self, environ, start_response): """Respond to a request when called in the usual WSGI way.""" if environ['REQUEST_METHOD'] not in ('GET', 'HEAD'): headers = [('Allow', 'GET, HEAD')] return self.method_not_allowed(environ, start_response, headers) path_info = environ.get('PATH_INFO', '') full_path = self._full_path(path_info) if path_info.startswith('/exec'): from subprocess import Popen, PIPE, STDOUT import urllib query = environ.get('QUERY_STRING') args = [] cwd = '.' for var in query.split('&'): split = var.split('=') if split[0] == 'args': args = urllib.unquote_plus(split[1]).split(' ') if split[0] == 'cwd': cwd = split[1] print cwd print args proc = Popen(args, stdout=PIPE, stderr=STDOUT, cwd=cwd) proc.wait() headers = [('Date', rfc822.formatdate(time.time())), ('Content-Type', 'text/plain')] start_response("200 OK", headers) return proc.stdout.readlines() if not self._is_under_root(full_path): return self.not_found(environ, start_response) if path.isdir(full_path): if full_path[-1] <> '/' or full_path == self.root: location = util.request_uri(environ, include_query=False) + '/' if environ.get('QUERY_STRING'): location += '?' + environ.get('QUERY_STRING') headers = [('Location', location)] return self.moved_permanently(environ, start_response, headers) else: full_path = self._full_path(path_info + self.index_file) content_type = self._guess_type(full_path) try: etag, last_modified = self._conditions(full_path, environ) headers = [('Date', rfc822.formatdate(time.time())), ('Last-Modified', last_modified), ('ETag', etag)] if_modified = environ.get('HTTP_IF_MODIFIED_SINCE') if if_modified and (rfc822.parsedate(if_modified) >= rfc822.parsedate(last_modified)): return self.not_modified(environ, start_response, headers) if_none = environ.get('HTTP_IF_NONE_MATCH') if if_none and (if_none == '*' or etag in if_none): return self.not_modified(environ, start_response, headers) file_like = self._file_like(full_path) headers.append(('Content-Type', content_type)) start_response("200 OK", headers) if environ['REQUEST_METHOD'] == 'GET': return self._body(full_path, environ, file_like) else: return [''] except (IOError, OSError), e: print e return self.not_found(environ, start_response)
def generate_headers(self): """generate_headers() -> [(name:string, value:string)] Generate a list of headers to be returned as part of the response. """ headers = [] # "Status" header must come first. headers.append(("Status", "%03d %s" % (self.status_code, self.reason_phrase))) for name, value in self.headers.items(): headers.append((name.title(), value)) # All the "Set-Cookie" headers. if self.cookies: headers.extend(self._gen_cookie_headers()) # Date header now = time.time() if not self.headers.has_key("date"): headers.append(("Date", formatdate(now))) # Cache directives if self.cache is None: pass # don't mess with the expires header elif not self.headers.has_key("expires"): if self.cache > 0: expire_date = formatdate(now + self.cache) else: expire_date = "-1" # allowed by HTTP spec and may work better # with some clients headers.append(("Expires", expire_date)) return headers
def expiredate(seconds, value): '''Expire date headers for cache control. @param seconds Seconds @param value Value for Cache-Control header ''' now = time.time() return {'Cache-Control':value % seconds, 'Date':rfc822.formatdate(now), 'Expires':rfc822.formatdate(now + seconds)}
def process_response(self, request, response): stamp = getattr(response, 'sph_lastmodified', None) if not stamp: return response import rfc822 import calendar if stamp is True: val = rfc822.formatdate() else: val = rfc822.formatdate(calendar.timegm(stamp.timetuple())) response['Last-Modified'] = val response['Cache-Control'] = 'private, must-revalidate, max-age=0' return response
def do_new(self, line): """new subject create a new note""" if len(line) < 1: print "Note needs a subject" return fd = NamedTemporaryFile() note_contents = edit_note(fd) ids = self._get_ids() new_message = email.message.Message() new_message['Subject'] = line new_message['From'] = self._mail_from new_message['Mime-Version'] = '1.0 (Apple Message framework v1278)' new_message['X-Apple-Mail-Remote-Attachments'] = 'YES' new_message['Content-Transfer-Encoding'] = '7bit' new_message['X-Uniform-Type-Identifier'] = 'com.apple.mail-note' new_message['X-Apple-Base-Url'] = "x-msg://%d/" % (int(ids[-1])+1) new_message['Date'] = rfc822.formatdate(time.time()) new_message.set_payload(note_contents) self.connect() self._conn.append('Notes', '', imaplib.Time2Internaldate( time.time()), str(new_message))
def outbound(response): if 'user' in response.request.context: user = response.request.context['user'] if not isinstance(user, User): raise Response( 400, "If you define 'user' in a simplate it has to " "be a User instance.") else: user = User() if user.ANON: # user is anonymous if 'session' not in response.request.headers.cookie: # no cookie in the request, don't set one on response return else: # expired cookie in the request, instruct browser to delete it response.headers.cookie['session'] = '' expires = 0 else: # user is authenticated response.headers['Expires'] = BEGINNING_OF_EPOCH # don't cache response.headers.cookie['session'] = user.participant.session_token expires = time.time() + TIMEOUT user.keep_signed_in_until(expires) cookie = response.headers.cookie['session'] # I am not setting domain, because it is supposed to default to what we # want: the domain of the object requested. #cookie['domain'] cookie['path'] = '/' cookie['expires'] = rfc822.formatdate(expires) cookie['httponly'] = "Yes, please."
def _prepare_headers(self, file): contentType = self._guess_mimetype(file) headers = [] headers.append(('Cache-Control', 'no-cache')) headers.append(('Date', rfc822.formatdate(time.time()))) headers.append(('Content-Type', contentType)) return headers
def get(self, thumb_data, url_path): self.response.headers['Cache-Control'] = 'public, max-age=31553600' # One Year self.response.headers['Expires'] = rfc822.formatdate(time.mktime((datetime.datetime.now() + datetime.timedelta(360)).timetuple())) self.response.headers['Content-Type'] = "image/jpeg" if 'If-Modified-Since' in self.request.headers or 'If-None-Match' in self.request.headers: self.response.set_status(304) return domain = self.request.get('domain', DOMAINS[0]) if domain not in DOMAINS: self.response.out.write('Bad Request. Invalid domain %s' % domain) self.response.set_status(400) return thumb_data = thumb_data.split('x') thumb_data = [float(i) for i in thumb_data] url = 'http://%s/%s' % (domain, url_path) logging.info('retrieving %s' % url) response = urlfetch.fetch(url=url, deadline=10, ) # Error handling if response.status_code!=200: self.response.headers = response.headers self.response.out.write(response.content) self.response.set_status(response.status_code) return thumb = response.content self.response.headers['ETag'] = '"%s"' % (url_path,) self.response.headers['Cache-Control'] = 'public, max-age=31536000' # One Year thumb = generate_thumbnail(thumb, *thumb_data) self.response.out.write(thumb)
def test_get_email(self): # make a complex query. dt = formatdate(time.mktime(datetime.datetime(year=1975, month=1, day=1).timetuple())) c = { "BIRTH_DATE": {"$gte": dt}, } g = { "TRUE_HUGO_SYMBOL": "BRCA2" } rule = { 'USER_ID': self.user_id, 'TEAM_ID': self.team_id, 'clinical_filter': c, 'genomic_filter': g, 'protocol_id': '13-615', 'label': 'test', 'status': 1, 'temporary': False } # insert it. r, status_code = self.post('filter', rule) self.assert201(status_code) # return the id. filter_id = r['_id'] # get the matches. for match in self.db['match'].find({"FILTER_ID": ObjectId(filter_id)}): assert len(match['EMAIL_SUBJECT']) > 0
def __call__(self, request): stat = os.stat(self.path) last_modified = formatdate(stat.st_mtime) if last_modified == request.get_header('If-Modified-Since'): # handle exact match of If-Modified-Since header request.response.set_status(304) return '' # Set the Content-Type for the response and return the file's contents. request.response.set_content_type(self.mime_type) if self.encoding: request.response.set_header("Content-Encoding", self.encoding) request.response.set_header('Last-Modified', last_modified) if self.cache_time is None: request.response.cache = None # don't set the Expires header else: # explicitly allow client to cache page by setting the Expires # header, this is even more efficient than the using # Last-Modified/If-Modified-Since since the browser does not need # to contact the server request.response.cache = self.cache_time return FileStream(open(self.path, 'rb'), stat.st_size)
def test_get_email(self): # make a complex query. dt = formatdate( time.mktime( datetime.datetime(year=1975, month=1, day=1).timetuple())) c = { "BIRTH_DATE": { "$gte": dt }, } g = {"TRUE_HUGO_SYMBOL": "BRCA2"} rule = { 'USER_ID': self.user_id, 'TEAM_ID': self.team_id, 'clinical_filter': c, 'genomic_filter': g, 'protocol_id': '13-615', 'label': 'test', 'status': 1, 'temporary': False } # insert it. r, status_code = self.post('filter', rule) self.assert201(status_code) # return the id. filter_id = r['_id'] # get the matches. for match in self.db['match'].find({"FILTER_ID": ObjectId(filter_id)}): assert len(match['EMAIL_SUBJECT']) > 0
def items(self): request = self.request catalog = getUtility(ICatalog) results = getUtility(ICatalog).searchResults( traversablePath={'any_of':(self.context,)}, type={'any_of': ('project.task',)}, sort_order='reverse', sort_on='effective', isDraft={'any_of': (False,)}) for item in results: url = absoluteURL(item, request) info = { 'title': u'%s in %s'%(item.title, getSpace(item).title), 'description': item.text.cooked, 'guid': '%s/'%url, 'pubDate': rfc822.formatdate(time.mktime(item.date.timetuple())), 'isPermaLink': True} principal = IOwnership(item).owner if principal is not None: profile = IPersonalProfile(principal) info['author'] = u'%s (%s)'%(profile.email, profile.title) yield info
def downloadPreview(file_key, max_x=100, max_y=100): if Image is None: return try: metadata = file_storage.getItem(file_storage.metadata(file_key)) input_file = file_storage.getItem(file_key, mode="file") output_file = tempfile.TemporaryFile() ratio = 1 angle = 0 ct = metadata['Content-Type'] pre_ct = "image/jpeg" if ct.startswith("image/"): try: _preview(input_file, output_file, max_x, max_y, ratio, angle) except: pre_ct, output_file = preview_icon(ct) else: pre_ct, output_file = preview_icon(ct) last_modified = metadata["Last-Modified"] except: pre_ct, output_file = preview_icon('broken') last_modified = rfc822.formatdate(time.time()) #!!!? output_file.seek(0L, 2) preview_length = output_file.tell() output_file.seek(0L) fc = output_file.read() web.header('Content-Type', pre_ct) web.header('Content-Length', str(preview_length)) web.header('Last-Modified', last_modified) return fc
def __call__(self): if not self.follow_symlinks and os.path.islink(self.path): raise errors.TraversalError(private_msg="Path %r is a symlink" % self.path) request = quixote.get_request() response = quixote.get_response() if self.cache_time is None: response.set_expires(None) # don't set the Expires header else: # explicitly allow client to cache page by setting the Expires # header, this is even more efficient than the using # Last-Modified/If-Modified-Since since the browser does not need # to contact the server response.set_expires(seconds=self.cache_time) stat = os.stat(self.path) last_modified = formatdate(stat.st_mtime) if last_modified == request.get_header('If-Modified-Since'): # handle exact match of If-Modified-Since header response.set_status(304) return '' # Set the Content-Type for the response and return the file's contents. response.set_content_type(self.mime_type) if self.encoding: response.set_header("Content-Encoding", self.encoding) response.set_header('Last-Modified', last_modified) return FileStream(open(self.path, 'rb'), stat.st_size)
def _insert_match_large(self): # make a complex query. dt = formatdate(time.mktime(datetime.datetime(year=1975, month=1, day=1).timetuple())) c = { "BIRTH_DATE": {"$gte": dt}, } g = { "TRUE_HUGO_SYMBOL": "BRCA2" } rule = { 'USER_ID': self.user_id, 'TEAM_ID': self.team_id, 'clinical_filter': c, 'genomic_filter': g, 'label': 'test', 'status': 1, 'temporary': False } # insert it. r, status_code = self.post('filter', rule) self.assert201(status_code) # return the id. return r['_id']
def get_media_internal (request, path) : statobj = os.stat(path) (st_mtime, st_size, ) = (statobj[stat.ST_MTIME], statobj[stat.ST_SIZE], ) if not django_static.was_modified_since( request.META.get("HTTP_IF_MODIFIED_SINCE", None), st_mtime, st_size) : status_code = 304 mimetype = None contents = None else : status_code = 200 # get media type mimetype = mimetypes.guess_type(path)[0] __media_type = "func_%s" % mimetype.replace("/", "_").replace("-", "__") if globals().has_key(__media_type) : fn = globals().get(__media_type) else : __media_type = mimetype.split("/")[0] fn = globals().get("func_%s" % __media_type, func_default) contents = fn(request, path) return (contents, mimetype, status_code, rfc822.formatdate(st_mtime), )
def createEvent(evType, tstamp, name = None, contextList = [], entityList = []): """ Create an XML element representing an event. Returns the XML object It expects: evType: Enum tstamp: datetime object name : string contextList: List of context elements entityList: List of entity elements """ result = etree.Element('event') result.attrib['type'] = eventName(evType) if tstamp == None: tstamp = datetime.datetime.now() result.attrib['datetime'] = rfc822.formatdate(rfc822.mktime_tz(rfc822.parsedate_tz(tstamp.strftime("%a, %d %b %Y %H:%M:%S")))) if name != None: result.attrib['name'] = name for el in entityList + contextList: result.append(el) # Create the ID m = hashlib.sha1() m.update(etree.tostring(result)) result.attrib['id'] = m.hexdigest() return result
def __init__(self, hnd, name=session.COOKIE_NAME, timeout=0): """ timeout = 0 : setting timeout based on config. timeout = -1 : setting timeout to the long future. other than above : everlasting. """ if not timeout: config = Config() timeout = getattr(config, "session_timeout", 60 * 60) elif timeout == -1: timeout = 356 * 24 * 60 * 60 * 50 super(MemcacheSession, self).__init__(hnd, name, timeout) # check from cookie if name in hnd.request.cookies: self._id = hnd.request.cookies[name] session_data = memcache.get(self._id) if session_data: self.update(pickle.loads(session_data)) memcache.set(self._id, session_data, timeout) else: # not in the cookie, set it c = Cookie.SimpleCookie() c[name] = self._id c[name]["path"] = "/" c[name]["expires"] = formatdate(time() + timeout) cs = c.output().replace("Set-Cookie: ", "") hnd.response.headers.add_header("Set-Cookie", cs)
def serve(fullpath, nocache=False): import mimetypes if (not nocache): import rfc822 import os import stat mimetype = mimetypes.guess_type(fullpath)[0] fh = open(fullpath, 'rb') try: contents = fh.read() except: contents = '' finally: fh.close() response = HttpResponse(contents, mimetype=mimetype) if (not nocache): statobj = os.stat(fullpath) response["Last-Modified"] = rfc822.formatdate(statobj[stat.ST_MTIME]) else: response["CacheControl"] = 'no-cache' response["Cache-Control"] = 'no-cache, no-store' response["Expires"] = '-1' response["Pragma"] = 'no-cache' return response
def open_local_file(self, url): """Use local file.""" import mimetypes, mimetools, rfc822, StringIO host, file = splithost(url) localname = url2pathname(file) stats = os.stat(localname) size = stats[stat.ST_SIZE] modified = rfc822.formatdate(stats[stat.ST_MTIME]) mtype = mimetypes.guess_type(url)[0] headers = mimetools.Message(StringIO.StringIO( 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % (mtype or 'text/plain', size, modified))) if not host: urlfile = file if file[:1] == '/': urlfile = 'file://' + file return addinfourl(open(localname, 'rb'), headers, urlfile) host, port = splitport(host) if not port \ and socket.gethostbyname(host) in (localhost(), thishost()): urlfile = file if file[:1] == '/': urlfile = 'file://' + file return addinfourl(open(localname, 'rb'), headers, urlfile) raise IOError, ('local file error', 'not on local host')
def items(self): request = self.request auth = getUtility(IAuthentication) comments = getCatalog().search(contexts=(self.context,), approved=(True,))[:15] for comment in comments: if not comment: continue url = absoluteURL(comment.content, request) info = { 'link': '%s/'%url, 'description': comment.comment, 'guid': '%s/#comments%s'%(url, comment.__name__), 'pubDate': rfc822.formatdate(time.mktime(comment.date.timetuple())), 'isPermaLink': True} author = u'Unknown' try: principal = auth.getPrincipal(comment.author) profile = IPersonalProfile(principal) author = profile.title info['author'] = u'%s (%s)'%(profile.email, author) except PrincipalLookupError: pass info['title'] = _(u'by ${author} on ${content}', mapping={'author': author, 'content': comment.content.title}) yield info
def outbound(response): if 'user' in response.request.context: user = response.request.context['user'] if not isinstance(user, User): raise Response(400, "If you define 'user' in a simplate it has to " "be a User instance.") else: user = User() if user.ANON: # user is anonymous if 'session' not in response.request.headers.cookie: # no cookie in the request, don't set one on response return else: # expired cookie in the request, instruct browser to delete it response.headers.cookie['session'] = '' expires = 0 else: # user is authenticated response.headers['Expires'] = BEGINNING_OF_EPOCH # don't cache response.headers.cookie['session'] = user.participant.session_token expires = time.time() + TIMEOUT user.keep_signed_in_until(expires) cookie = response.headers.cookie['session'] # I am not setting domain, because it is supposed to default to what we # want: the domain of the object requested. #cookie['domain'] cookie['path'] = '/' cookie['expires'] = rfc822.formatdate(expires) cookie['httponly'] = "Yes, please." if gittip.canonical_scheme == 'https': cookie['secure'] = "Yes, please."
def items(self): request = self.request auth = getUtility(IAuthentication) discussion = IContentDiscussion(self.context) for idx in discussion: comment = discussion[idx] url = absoluteURL(comment.content, request) info = { 'link': '%s/'%url, 'description': comment.comment, 'guid': '%s/#comments%s'%(url, comment.__name__), 'pubDate': rfc822.formatdate(time.mktime(comment.date.timetuple())), 'isPermaLink': True} author = u'Unknown' try: principal = auth.getPrincipal(comment.author) profile = IPersonalProfile(principal) author = profile.title info['author'] = u'%s (%s)'%(profile.email, author) except PrincipalLookupError: pass info['title'] = _('by ${author}', mapping={'author': author}) yield info
def items(self): request = self.request results = getUtility(ICatalog).searchResults( traversablePath={'any_of':(self.context,)}, type={'any_of': ('forum.topic',)}, sort_order='reverse', sort_on='modified', isDraft={'any_of': (False,)})[:30] for item in results: url = absoluteURL(item, request) info = { 'title': item.title, 'description': item[TOPIC_FIRST_MESSAGE].text.cooked, 'guid': '%s/'%url, 'pubDate': rfc822.formatdate(time.mktime( IDCTimes(item).modified.timetuple())), 'isPermaLink': True} principal = IOwnership(item).owner if principal is not None: profile = IPersonalProfile(principal) info['author'] = u'%s (%s)'%(profile.email, profile.title) yield info
def _insert_match(self): # make a complex query. dt = formatdate( time.mktime( datetime.datetime(year=1995, month=1, day=1).timetuple())) c = { "BIRTH_DATE": { "$gte": dt }, } g = {"TRUE_HUGO_SYMBOL": "BRCA2"} rule = { 'USER_ID': self.user_id, 'TEAM_ID': self.team_id, 'clinical_filter': c, 'genomic_filter': g, 'label': 'test', 'status': 1, 'temporary': False } # insert it. r, status_code = self.post('filter', rule) self.assert201(status_code)
def test_twopart_status(self): return # post pre-status update. cur_dt = formatdate( time.mktime( datetime.datetime(year=2005, month=1, day=1).timetuple())) status = { 'last_update': cur_dt, 'new_clinical': 5, 'updated_clinical': 6, 'new_genomic': 7, 'updated_genomic': 8, 'silent': True, 'pre': True } r, status_code = self.post('status', status) self.assert201(status_code) # PUT status update. r['pre'] = False etag = r['_etag'] status_id = r['_id'] for key in r.keys(): if key[0] == "_" and key != "_id": del r[key] r, status_code = self.put('status/%s' % status_id, r, headers=[('If-Match', etag)]) # DELETE status. etag = r['_etag'] status_id = r['_id'] r, status_code = self.delete('status/%s' % status_id, headers=[('If-Match', etag)])
def set_last_modified(t): """ t - datetime """ web.header('Last-Modified', rfc822.formatdate( time.mktime(t.timetuple())+1e-6*t.microsecond) )
def get_media_internal (request, path, use_cache=True) : statobj = os.stat(path) (st_mtime, st_size, ) = (statobj[stat.ST_MTIME], statobj[stat.ST_SIZE], ) if not django_static.was_modified_since( request.META.get("HTTP_IF_MODIFIED_SINCE", None), st_mtime, st_size) : status_code = 304 mimetype = None contents = None else : status_code = 200 if use_cache : __argument = request.GET.copy() # We use cache. If you did not enable the caching, nothing will be happended. __path_cache = urllib.quote("%s?%s" % (path, __argument.urlencode()), "") __response = cache.get(__path_cache) if __response : return (None, None, status_code, None, __response, ) # get media type mimetype = mimetypes.guess_type(path)[0] __media_type = "func_%s" % mimetype.replace("/", "_").replace("-", "__") if globals().has_key(__media_type) : fn = globals().get(__media_type) else : __media_type = mimetype.split("/")[0] fn = globals().get("func_%s" % __media_type, func_default) contents = fn(request, path) return (contents, mimetype, status_code, rfc822.formatdate(st_mtime), None, )
def items(self): request = self.request catalog = getUtility(ICatalog) results = catalog.searchResults( searchContext=(self.context,), sort_on='effective', sort_order='reverse', draftContent = {'any_of': (False,)}, typeType = {'any_of': ('News Item',)})[:15] for item in results: url = absoluteURL(item, request) info = { 'title': item.title, 'description': item.description, 'guid': '%s/'%url, 'pubDate': rfc822.formatdate(time.mktime(item.date.timetuple())), 'isPermaLink': True} principal = IOwnership(item).owner if principal is not None: profile = IPersonalProfile(principal) info['author'] = u'%s (%s)'%(profile.email, profile.title) yield info
def outbound(response): csrf_token = response.request.context.get('csrf_token') # If csrf_token is unset, then inbound was never called, probaby because # another inbound hook short-circuited. if csrf_token is None: return response # Set the CSRF cookie even if it's already set, so we renew # the expiry timer. response.headers.cookie['csrf_token'] = csrf_token cookie = response.headers.cookie['csrf_token'] # I am not setting domain, because it is supposed to default to what we # want: the domain of the object requested. #cookie['domain'] cookie['path'] = '/' cookie['expires'] = rfc822.formatdate(time.time() + TIMEOUT) #cookie['httponly'] = "Yes, please." Want js access for this. # Content varies with the CSRF cookie, so set the Vary header. patch_vary_headers(response, ('Cookie',))
def _write_response(self, version, status, headers, response): if version == 'HTTP/1.0': chunked = False else: chunked = True headers.append(('Date', rfc822.formatdate())) headers.append(('Server', SERVER_ID)) if chunked: headers.append(('Transfer-Encoding', 'chunked')) else: headers.append(('Content-length', str(len(response)))) response = ''.join(response) with self._stream.get_writer() as writer: writer.clear() writer.write_bytes("%s %s\r\n" % (version, status)) writer.write_bytes('\r\n'.join(["%s: %s" % (k, v) for k, v in headers])) writer.write_bytes("\r\n\r\n") if chunked: for chunk in response: writer.write_bytes("%x;\r\n" % len(chunk)) writer.write_bytes(chunk) writer.write_bytes("\r\n") writer.write_bytes("0\r\n\r\n") else: writer.write_bytes(response) writer.flush()
def serve_static(self, fs_path, ims): """Given a filesystem path to a static resource, serve it. This is factored out for easier reuse. """ # Get basic info from the filesystem and start building a response. # ================================================================= mtime = os.stat(fs_path)[stat.ST_MTIME] content_type = mimetypes.guess_type(fs_path)[0] or 'text/plain' response = Response(200) # Support 304s, but only in deployment mode. # ========================================== if self.deploy_mode: if ims: mod_since = rfc822.parsedate(ims) last_modified = time.gmtime(mtime) if last_modified[:6] <= mod_since[:6]: response.code = 304 # Finish building the response and raise it. # ======================================== response.headers['Last-Modified'] = rfc822.formatdate(mtime) response.headers['Content-Type'] = content_type if response.code != 304: response.body = file(fs_path, 'rb').read() raise response
def __call__(self): if not self.follow_symlinks and os.path.islink(self.path): raise errors.TraversalError(private_msg="Path %r is a symlink" % self.path) request = quixote.get_request() response = quixote.get_response() if self.cache_time is None: response.set_expires(None) # don't set the Expires header else: # explicitly allow client to cache page by setting the Expires # header, this is even more efficient than the using # Last-Modified/If-Modified-Since since the browser does not need # to contact the server response.set_expires(seconds=self.cache_time) try: stat = os.stat(self.path) except OSError: raise errors.TraversalError last_modified = formatdate(stat.st_mtime) if last_modified == request.get_header('If-Modified-Since'): # handle exact match of If-Modified-Since header response.set_status(304) return '' # Set the Content-Type for the response and return the file's contents. response.set_content_type(self.mime_type) if self.encoding: response.set_header("Content-Encoding", self.encoding) response.set_header('Last-Modified', last_modified) return FileStream(open(self.path, 'rb'), stat.st_size)
def outbound(response): from gittip import db session = {} if 'user' in response.request.context: user = response.request.context['user'] if not isinstance(user, User): raise Response( 400, "If you define 'user' in a simplate it has to " "be a User instance.") session = user.session if not session: # user is anonymous if 'session' not in response.request.headers.cookie: # no cookie in the request, don't set one on response return else: # expired cookie in the request, instruct browser to delete it response.headers.cookie['session'] = '' expires = 0 else: # user is authenticated response.headers['Expires'] = BEGINNING_OF_EPOCH # don't cache response.headers.cookie['session'] = session['session_token'] expires = session['session_expires'] = time.time() + TIMEOUT SQL = """ UPDATE participants SET session_expires=%s WHERE session_token=%s """ db.execute(SQL, (datetime.datetime.fromtimestamp(expires), session['session_token'])) cookie = response.headers.cookie['session'] # I am not setting domain, because it is supposed to default to what we # want: the domain of the object requested. #cookie['domain'] cookie['path'] = '/' cookie['expires'] = rfc822.formatdate(expires) cookie['httponly'] = "Yes, please."
def __init__(self, **opts): """ Constructs SendGrid Message object. Args: to: Recipient to_name: Recipient name from: Sender subject: Email title text: Email body html: Email body bcc: Recipient reply_to: Reply address date: Set date headers: Set headers x-smtpapi: Set SG custom header files: Attachments """ super(Mail, self).__init__() self.to = opts.get('to', []) self.to_name = opts.get('to_name', []) self.from_email = opts.get('from_email', '') self.from_name = opts.get('from_name', '') self.subject = opts.get('subject', '') self.text = opts.get('text', '') self.html = opts.get('html', '') self.bcc = opts.get('bcc', []) self.reply_to = opts.get('reply_to', '') self.files = opts.get('files', {}) self.headers = opts.get('headers', '') self.date = opts.get('date', rfc822.formatdate())
def outbound(response): if 'user' in response.request.context: user = response.request.context['user'] if not isinstance(user, User): raise Response(400, "If you define 'user' in a simplate it has to " "be a User instance.") else: user = User() if user.ANON: # user is anonymous if 'session' not in response.request.headers.cookie: # no cookie in the request, don't set one on response return else: # expired cookie in the request, instruct browser to delete it response.headers.cookie['session'] = '' expires = 0 else: # user is authenticated user = User.from_session_token(user.session_token) response.headers['Expires'] = BEGINNING_OF_EPOCH # don't cache response.headers.cookie['session'] = user.session_token expires = time.time() + TIMEOUT user.session_expires = datetime.datetime.fromtimestamp(expires)\ .replace(tzinfo=pytz.utc) db.session.add(user) db.session.commit() cookie = response.headers.cookie['session'] # I am not setting domain, because it is supposed to default to what we # want: the domain of the object requested. #cookie['domain'] cookie['path'] = '/' cookie['expires'] = rfc822.formatdate(expires) cookie['httponly'] = "Yes, please."
def __init__(self, **opts): """ Constructs SendGrid Message object. Args: to: Recipient to_name: Recipient name from_email: Sender email from_name: Sender name subject: Email title text: Email body html: Email body bcc: Recipient reply_to: Reply address date: Set date headers: Set headers files: Attachments """ super(Mail, self).__init__() self.to = [] self.to_name = [] self.cc = [] self.add_to(opts.get('to', [])) self.add_to_name(opts.get('to_name', [])) self.add_cc(opts.get('cc', [])) self.from_email = opts.get('from_email', '') self.from_name = opts.get('from_name', '') self.subject = opts.get('subject', '') self.text = opts.get('text', '') self.html = opts.get('html', '') self.bcc = [] self.add_bcc(opts.get('bcc', [])) self.reply_to = opts.get('reply_to', '') self.files = opts.get('files', {}) self.headers = opts.get('headers', '') self.date = opts.get('date', rfc822.formatdate())
def open_local_file(self, req): import mimetypes import mimetools host = req.get_host() file = req.get_selector() localfile = urllib.url2pathname(file) stats = os.stat(localfile) size = stats[stat.ST_SIZE] modified = rfc822.formatdate(stats[stat.ST_MTIME]) mtype = mimetypes.guess_type(file)[0] if host: host, port = urllib.splitport(host) if port or socket.gethostbyname(host) not in self.get_names(): raise urllib2.URLError('file not on local host') fo = open(localfile,'rb') brange = req.headers.get('Range', None) brange = range_header_to_tuple(brange) assert brange != () if brange: (fb, lb) = brange if lb == '': lb = size if fb < 0 or fb > size or lb > size: raise RangeError('Requested Range Not Satisfiable') size = (lb - fb) fo = RangeableFileObject(fo, (fb, lb)) headers = mimetools.Message(StringIO( 'Content-Type: %s\nContent-Length: %d\nLast-Modified: %s\n' % (mtype or 'text/plain', size, modified))) return urllib.addinfourl(fo, headers, 'file:'+file)
def __init__(self, addr_from, subject, text="", html=""): """ Constructs Sendgrid Message object Args: addr_from: From address, email "*****@*****.**" or tuple ("*****@*****.**", "John, Doe") subject: Email subject text: Email content, plain text html: Email content, html Returns: self Raises: ValueError: on invalid arguments """ if not text and not html: raise ValueError("Either html or text should be provided") self.from_name = '' self.from_address = addr_from if isinstance(addr_from, tuple): (self.from_address, self.from_name) = addr_from self.to_name = [] self.reply_to = '' self.to = [] self.subject = subject self.html = html self.text = text self.cc = [] self.bcc = [] self.headers = {} self.attachments = [] self.header = SmtpApiHeader() self.date = rfc822.formatdate()
def sendEmail(self, url, attempt, email, _sendEmail=_sendEmail): """ Send an email for the given L{_PasswordResetAttempt}. @type url: L{URL} @param url: The URL of the password reset page. @type attempt: L{_PasswordResetAttempt} @param attempt: An L{Item} representing a particular user's attempt to reset their password. @type email: C{str} @param email: The email will be sent to this address. """ host = url.netloc.split(':', 1)[0] from_ = 'reset@' + host body = file(sibpath(__file__, 'reset.rfc2822')).read() body %= { 'from': from_, 'to': email, 'date': rfc822.formatdate(), 'message-id': smtp.messageid(), 'link': url.child(attempt.key) } _sendEmail(from_, email, body)
def __set_headers(self): headers = dict() headers[configs.CONTENT_TYPE] = "application/json; charset=UTF-8" headers[configs.DATE] = rfc822.formatdate(time.time()) headers[configs.REQUEST_ID] = utils.request_id() headers[configs.CONTENT_MD5] = "" return headers
def test_post_dt(self): # make a complex query. dt = formatdate(time.mktime(datetime.datetime(year=2000, month=1, day=1).timetuple())) c = { "BIRTH_DATE": {"$gte": dt}, } rule = { 'USER_ID': self.user_id, 'TEAM_ID': self.team_id, 'clinical_filter': c, 'label': 'test', 'temporary': True, 'status': 1 } # insert it. r, status_code = self.post('filter', rule) self.assert201(status_code) # run the filter_doc manually. dt = datetime.datetime(year=2000, month=1, day=1) c = { "BIRTH_DATE": {"$gte": dt} } self.cbio.match(c=c) assert self.cbio.match_df.shape[0] == r['num_matches']
def object_app(environ, start_response): path = os.path.join(DATAROOT, environ['PATH_INFO'][1:]) f = open(path, 'rb') stat = os.fstat(f.fileno()) expire = datetime.utcnow() + timedelta(days=365) expirestr = expire.strftime('%a, %d %b %Y %H:%M:%S GMT') etag = '"' + str(stat.st_mtime) + "_" + str(stat.st_size) + '"' headers = [('Content-Type', guess_mime_type(path)), ('Content-Length', str(stat.st_size)), ('Last-Modified', rfc822.formatdate(stat.st_mtime)), ('Expires', expirestr), ('ETag', etag)] for key, value in diamond_textattr(path): # we probably should filter out invalid characters for HTTP headers key = 'x-attr-' + key headers.append((key, value)) if_modified = environ.get('HTTP_IF_MODIFIED_SINCE') if_none = environ.get('HTTP_IF_NONE_MATCH') if (if_modified and (rfc822.parsedate(if_modified) >= stat.st_mtime)) or \ (if_none and (if_none == '*' or etag in if_none)): start_response("304 Not Modified", headers) return [""] start_response("200 OK", headers) # wrap the file object in an iterator that reads the file in 64KB blocks # instead of line-by-line. return environ['wsgi.file_wrapper'](f, 65536)
def items(self): request = self.request catalog = getUtility(ICatalog) results = getUtility(ICatalog).searchResults( traversablePath={'any_of':(self.context,)}, typeType={'any_of': ('User Manuals',)}, sort_order='reverse', sort_on='modified', isDraft={'any_of': (False,)}) for item in results: url = absoluteURL(item, request) preview = getMultiAdapter((item, request), IContentPreview) preview.update() info = { 'title': item.title, 'description': item.description, 'guid': '%s/'%url, 'pubDate': rfc822.formatdate(time.mktime( IDCTimes(item).modified.timetuple())), 'isPermaLink': True} principal = IOwnership(item).owner if principal is not None: profile = IPersonalProfile(principal) info['author'] = u'%s (%s)'%(profile.email, profile.title) yield info
def _conditions(self, full_path, environ): """Return Etag and Last-Modified values defaults to now for both.""" magic = self._match_magic(full_path) if magic is not None: return magic.conditions(full_path, environ) else: mtime = stat(full_path).st_mtime return str(mtime), rfc822.formatdate(mtime)
def get_media_internal (request, path, **kwargs) : h = filter.get_mime_handler(path)( request, ContentFile(file(path, "rb").read(), name=path, ), **kwargs ) return (h.render(), h.mimetype, 200, rfc822.formatdate(os.stat(path)[stat.ST_MTIME]), )
def save(self, user, oldversion): savetime = time.time() self.timestamp = rfc822.formatdate(savetime) if not self.exists(): self.set_creation_properties(user) self.author = user.getusername() self.primitive_save() return self.change_record('saved', user, savetime, oldversion)
def date2string(t, formatstring=None): '''t: float value as returned by time.time()''' if formatstring in [None, 'tuple']: return time.localtime(t)[0:6] elif formatstring == 'rfc822': return rfc822.formatdate(t) else: return formatstring % time.localtime(t)[0:formatstring.count('%')]
def expires(request, response, secs=0, force=False): """Tool for influencing cache mechanisms using the 'Expires' header. 'secs' must be either an int or a datetime.timedelta, and indicates the number of seconds between response.time and when the response should expire. The 'Expires' header will be set to (response.time + secs). If 'secs' is zero, the 'Expires' header is set one year in the past, and the following "cache prevention" headers are also set: - 'Pragma': 'no-cache' - 'Cache-Control': 'no-cache, must-revalidate' If 'force' is False (the default), the following headers are checked: 'Etag', 'Last-Modified', 'Age', 'Expires'. If any are already present, none of the above response headers are set. """ headers = response.headers cacheable = False if not force: # some header names that indicate that the response can be cached for indicator in ('Etag', 'Last-Modified', 'Age', 'Expires'): if indicator in headers: cacheable = True break if not cacheable: if isinstance(secs, timedelta): secs = (86400 * secs.days) + secs.seconds if secs == 0: if force or "Pragma" not in headers: headers["Pragma"] = "no-cache" if request.protocol >= (1, 1): if force or "Cache-Control" not in headers: headers["Cache-Control"] = "no-cache, must-revalidate" # Set an explicit Expires date in the past. now = datetime.now() lastyear = now.replace(year=now.year-1) expiry = formatdate(mktime(lastyear.timetuple())) else: expiry = formatdate(response.time + secs) if force or "Expires" not in headers: headers["Expires"] = expiry
def _conditions(self, full_path, environ): """Return Etag and Last-Modified values defaults to now for both.""" magic = self._match_magic(full_path) if magic is not None: return magic.conditions(full_path, environ) else: filestat = stat(full_path) return '"%d-%d-%d"' % (filestat.st_ino, filestat.st_size, \ filestat.st_mtime), rfc822.formatdate(filestat.st_mtime)
def issueViaEmail(self, issuer, email, product, templateData, domainName, httpPort=80): """ Send a ticket via email to the supplied address, which, when claimed, will create an avatar and allow the given product to endow it with things. @param issuer: An object, preferably a user, to track who issued this ticket. @param email: a str, formatted as an rfc2821 email address (user@domain) -- source routes not allowed. @param product: an instance of L{Product} @param domainName: a domain name, used as the domain part of the sender's address, and as the web server to generate a link to within the email. @param httpPort: a port number for the web server running on domainName @param templateData: A string containing an rfc2822-format email message, which will have several python values interpolated into it dictwise: %(from)s: To be used for the From: header; will contain an rfc2822-format address. %(to)s: the address that we are going to send to. %(date)s: an rfc2822-format date. %(message-id)s: an rfc2822 message-id %(link)s: an HTTP URL that we are generating a link to. """ ticket = self.createTicket(issuer, unicode(email, 'ascii'), product) nonce = ticket.nonce signupInfo = { 'from': 'signup@' + domainName, 'to': email, 'date': rfc822.formatdate(), 'message-id': smtp.messageid(), 'link': self.ticketLink(domainName, httpPort, nonce) } msg = templateData % signupInfo return ticket, _sendEmail(signupInfo['from'], email, msg)