本文整理汇总了Python中tornado.httputil.format_timestamp函数的典型用法代码示例。如果您正苦于以下问题:Python format_timestamp函数的具体用法?Python format_timestamp怎么用?Python format_timestamp使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了format_timestamp函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get
def get(self, distro=None, comp=None):
db = self.settings['db']
(expired, dt) = yield self._cache_expired('components', {'distro': distro, 'component': comp})
if not expired:
self.set_status(304)
return
if not dt:
self.set_status(404)
return
self.add_header('Last-Modified', httputil.format_timestamp(dt))
self.set_header('Content-Type', 'application/octet-stream')
doc = yield db.cacus.components.find_one({'distro': distro, 'component': comp})
if doc:
s = common.config['repo_daemon']
if s['proxy_storage']:
headers = [ ('Content-Length', doc['size']), ('Last-Modified', httputil.format_timestamp(dt)) ]
yield self.stream_from_storage(doc['sources_file'], headers=headers)
else:
# we use x-accel-redirect instead of direct proxying via storage plugin to allow
# user to offload cacus' StorageHandler if current storage allows it
url = os.path.join(s['repo_base'], s['storage_subdir'], doc['sources_file'])
app_log.info("Redirecting %s/%s/source/Sources to %s", distro, comp, arch, url)
self.add_header("X-Accel-Redirect", url)
self.set_status(200)
else:
self.set_status(404)
示例2: rel_as_dict
def rel_as_dict(self, rel) :
return {"uuid" : None if rel.uuid.startswith("pseudo:") else rel.uuid,
"date_created" : httputil.format_timestamp(rel.date_created),
"deleted" : getattr(rel, "deleted", None),
"name" : rel.name,
"subject" : rel.subject_uuid,
"object" : rel.object_uuid,
"payload" : rel.payload}
示例3: set_cookie
def set_cookie(self, name, value, expires_days=30, version=None,
domain=None, expires=None, path="/", **kwargs):
""" Sets the given cookie name/value with the given options. Set value
to None to clear. The cookie value is secured using
`flexx.config.cookie_secret`; don't forget to set that config
value in your server. Additional keyword arguments are set on
the Cookie.Morsel directly.
"""
# This code is taken (in modified form) from the Tornado project
# Copyright 2009 Facebook
# Licensed under the Apache License, Version 2.0
# Assume tornado is available ...
from tornado.escape import native_str
from tornado.httputil import format_timestamp
from tornado.web import create_signed_value
# Clear cookie?
if value is None:
value = ""
expires = datetime.datetime.utcnow() - datetime.timedelta(days=365)
else:
secret = config.cookie_secret
value = create_signed_value(secret, name, value, version=version,
key_version=None)
# The cookie library only accepts type str, in both python 2 and 3
name = native_str(name)
value = native_str(value)
if re.search(r"[\x00-\x20]", name + value):
# Don't let us accidentally inject bad stuff
raise ValueError("Invalid cookie %r: %r" % (name, value))
if name in self._cookies:
del self._cookies[name]
self._cookies[name] = value
morsel = self._cookies[name]
if domain:
morsel["domain"] = domain
if expires_days is not None and not expires:
expires = datetime.datetime.utcnow() + datetime.timedelta(
days=expires_days)
if expires:
morsel["expires"] = format_timestamp(expires)
if path:
morsel["path"] = path
for k, v in kwargs.items():
if k == 'max_age':
k = 'max-age'
# skip falsy values for httponly and secure flags because
# SimpleCookie sets them regardless
if k in ['httponly', 'secure'] and not v:
continue
morsel[k] = v
self._exec('document.cookie = "%s";' %
morsel.OutputString().replace('"', '\\"'))
示例4: redirect_after
def redirect_after(self, request):
"Perform a redirect to ``target``"
date = request.params.get("date")
if date:
retry_after = str(httputil.format_timestamp(datetime.fromtimestamp(float(date))))
else:
retry_after = "1"
target = request.params.get("target", "/")
headers = [("Location", target), ("Retry-After", retry_after)]
return Response(status="303 See Other", headers=headers)
示例5: blob_as_dict
def blob_as_dict(self, blob, with_content=False) :
ret = {"uuid" : blob.uuid,
"date_created" : httputil.format_timestamp(blob.date_created),
"editor_email" : blob.editor_email,
"content_type" : blob.content_type}
if blob.content_type.startswith("mime:text/") :
ret["summary"] = self.blob_summary(blob)
if with_content :
ret["content"] = blob.content.stuff
return ret
示例6: set_default_headers
def set_default_headers(self):
default_headers = {
"Server": "TornadoServer/%s" % tornado.version,
"Content-Type": "text/event-stream",
"access-control-allow-origin": "*",
"connection": "keep-alive",
"Date": httputil.format_timestamp(time.time()),
}
default_headers.update(self.custom_headers())
self._headers = httputil.HTTPHeaders(default_headers)
示例7: redirect_after
def redirect_after(self, request):
"Perform a redirect to ``target``"
date = request.params.get('date')
if date:
retry_after = str(httputil.format_timestamp(
datetime.fromtimestamp(float(date))))
else:
retry_after = '1'
target = request.params.get('target', '/')
headers = [('Location', target), ('Retry-After', retry_after)]
return Response(status='303 See Other', headers=headers)
示例8: clear
def clear(self):
"""Resets all headers and content for this response."""
self._headers = httputil.HTTPHeaders({
"Server": "Durotar/%s" % durotar.version,
"Content-Type": "text/html; charset=UTF-8",
"Date": httputil.format_timestamp(time.time()),
})
self.set_default_headers()
self._write_buffer = []
self._status_code = 200
self._reason = httputil.responses[200]
示例9: assert_modified
def assert_modified(self, url, mod_date):
response = self.fetch(
url, if_modified_since=(mod_date - timedelta(seconds=1)))
# 200 OK, not 304 Not Modified.
self.assertEqual(200, response.code)
self.assertEqual(
httputil.format_timestamp(mod_date),
response.headers['Last-Modified'])
response = self.fetch(url, if_modified_since=mod_date)
self.assertEqual(304, response.code)
示例10: _convert_header_value
def _convert_header_value(self, value):
if isinstance(value, bytes):
pass
elif isinstance(value, unicode_type):
value = value.encode("utf-8")
elif isinstance(value, numbers.Integral):
return str(value)
elif isinstance(value, datetime.datetime):
return httputil.format_timestamp(value)
else:
raise TypeError("Unsupported header value %r" % value)
if len(value) > 4000 or RequestHandler._INVALID_HEADER_CHAR_RE.search(value):
raise ValueError("Unsafe header value %r", value)
return value
示例11: upload_file
def upload_file(self, file_data, file_path, content_type=None):
"""上传文件到oss服务器上
:param file_data: 文件的数据
:param file_path: 保存到OSS的路径
:return:
"""
oss = OssAPI(self.regional_node, self.id, self.key)
expires = format_timestamp(datetime.datetime.today() + datetime.timedelta(days=+90))
header = {'expires': expires,
'Cache-Control': 'max-age=%s' % (90*24*60*60)}
if content_type:
res = oss.put_object_from_string(self.bucket, file_path, file_data, headers=header, content_type=content_type)
else:
res = oss.put_object_from_string(self.bucket, file_path, file_data)
if 200 == res.status:
return True, file_path
else:
# log
res_message = "OSS ERROR\n%s\n%s" % (res.status, res.read())
logging.info(res_message)
return False, u'上传文件出错!'
示例12: force_clear_cookie
def force_clear_cookie(self, name, path="/", domain=None):
"""Deletes the cookie with the given name.
Tornado's cookie handling currently (Jan 2018) stores cookies in a dict
keyed by name, so it can only modify one cookie with a given name per
response. The browser can store multiple cookies with the same name
but different domains and/or paths. This method lets us clear multiple
cookies with the same name.
Due to limitations of the cookie protocol, you must pass the same
path and domain to clear a cookie as were used when that cookie
was set (but there is no way to find out on the server side
which values were used for a given cookie).
"""
name = escape.native_str(name)
expires = datetime.datetime.utcnow() - datetime.timedelta(days=365)
morsel = Morsel()
morsel.set(name, '', '""')
morsel['expires'] = httputil.format_timestamp(expires)
morsel['path'] = path
if domain:
morsel['domain'] = domain
self.add_header("Set-Cookie", morsel.OutputString())
示例13: check
def check(self, value):
self.assertEqual(format_timestamp(value), self.EXPECTED)
示例14: test_format
def test_format(self):
format = "%A, %d-%b-%y %H:%M:%S GMT"
expected = 'Sunday, 27-Jan-13 18:43:20 GMT'
self.assertEqual(format_timestamp(self.TIMESTAMP, format),
expected)
示例15: fetch
def fetch(self, target, refresh=False, cache=True, delay=None,
follow=True, extract=None, **kwargs):
"""Fetch a URL from the wild, but first check the Cache.
Args:
target (str or HTTPRequest): to be fetched.
refresh (bool, optional): should the CacheClient ask the remote
source to refresh cached files? Defaults to False.
cache (bool, optional): should results be cached? Defaults to True.
delay (int, optional): a period, in seconds, for which the client
should delay before sending the next request after a successful
fetch.
follow (bool, optional): should redirects be followed? If False,
the Response object will only contain a string to the redirect
url target. Defaults to True.
extract (str, optional): if supplied, the Client will try to
extract a filename of `extract` from any resulting compressed
file.
**kwargs (misc., optional): any additional keyword arguments that
should be passed when a new HTTPRequest is initialized.
Returns (/ Raises):
response (cache.Response or None): a named tuple containing values:
- `url` (string): the url of the fetch/cache load.
- `buffer` (BytesIO): the body of the fetch result.
- `fresh` (bool): True if the Response object is the result of
a fresh response from the target server.
or None if an error occurred (which is logged).
"""
request = self._cached_http_request(target, follow_redirects=follow,
**kwargs)
self._log.debug("Fetching file @ {}".format(request.url))
if not refresh and IF_MODIFIED_SINCE in request.headers:
self._log.debug("Have cached file, not asking for a refresh.")
response = self.cache.load(request.url)
raise gen.Return(response)
elif IF_MODIFIED_SINCE in request.headers:
last_mod = request.headers[IF_MODIFIED_SINCE]
age = datetime.datetime.now() - last_mod
if age.seconds < REFRESH_COOLDOWN:
self._log.debug("Have recent cached file, not refreshing.")
raise gen.Return(self.cache.load(request.url))
else:
request.headers[IF_MODIFIED_SINCE] = format_timestamp(last_mod)
try:
response = yield self._client.fetch(request)
except HTTPError as err:
if err.code == FILE_UNCHANGED:
self._log.debug("File unchanged, using cached version.")
raise gen.Return(self.cache.load(request.url))
# If we get a 302, and we're expecting it, return the location and
# fresh to indicate that the destination is a new one (since we
# had to reach out to the server.
elif err.code == SOFT_REDIRECT and not follow:
loc = err.response.headers[LOCATION_HEADER]
self._log.debug('Redirected to {}, not following'.format(loc))
response = Response(BytesIO(loc), request.url, True)
raise gen.Return(response)
else:
self._log.error(
"{0} ({1}) fetching {2}".format(err, err.code, request.url))
raise gen.Return(None)
except Exception as excp:
self._log.exception(excp)
raise gen.Return(None)
else:
self._log.debug("Got fresh file @ {0}".format(request.url))
if extract:
response.buffer = decompress_response(response.buffer, extract)
if cache:
self._log.debug("Caching {0}".format(request.url))
self.cache_response(response, overwrite=True)
response = Response(response.buffer, request.url, True)
raise gen.Return(response)
finally:
if delay:
self._log.debug("Pausing @ {0} for {1} sec(s)".format(
self.ioloop.time(), delay))
yield gen.sleep(delay)