本文整理汇总了Python中webob.Response.last_modified方法的典型用法代码示例。如果您正苦于以下问题:Python Response.last_modified方法的具体用法?Python Response.last_modified怎么用?Python Response.last_modified使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类webob.Response
的用法示例。
在下文中一共展示了Response.last_modified方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: make_response
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import last_modified [as 别名]
def make_response(file, content_type):
response = Response(content_type=content_type)
response.app_iter = FileIterable(file)
stat = os.fstat(file.fileno())
response.content_length = stat.st_size
response.last_modified = stat.st_mtime
response.etag = '%s-%s' % (stat.st_mtime, stat.st_size)
return response
示例2: make_response
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import last_modified [as 别名]
def make_response(filename):
res = Response(content_type=get_mimetype(filename),
conditional_response=True)
res.app_iter = FileIterable(filename)
res.content_length = os.path.getsize(filename)
res.last_modified = os.path.getmtime(filename)
res.etag = '%s-%s-%s' % (os.path.getmtime(filename),
os.path.getsize(filename), hash(filename))
return res
示例3: file_response
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import last_modified [as 别名]
def file_response(filename):
"""return a webob response object appropriate to a file name"""
res = Response(content_type=get_mimetype(filename),
conditional_response=True)
res.app_iter = FileIterable(filename)
res.content_length = os.path.getsize(filename)
res.last_modified = os.path.getmtime(filename)
res.etag = '%s-%s-%s' % (os.path.getmtime(filename),
os.path.getsize(filename), hash(filename))
return res
示例4: asset_view_factory
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import last_modified [as 别名]
def asset_view_factory(body, content_type, last_modified, http_cache=None):
""" Returns an asset_view function that returns a SimpleResponse object"""
response = Response()
response.body = body
response.content_type = content_type
response.last_modified = last_modified
response.cache_expires = http_cache
def asset_view(context, request):
return response
return asset_view
示例5: process
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import last_modified [as 别名]
def process(self, req, environ):
# Check if we're authenticated
if not self.check_cookie(environ):
raise exc.HTTPUnauthorized(
"Please use the login method to authorize yourself.",
allow='POST').exception
# Strip leading part of the path
path = environ['PATH_INFO'][len(self.__path):].strip(os.sep)
# Extract cache entry uuid, attribute, index and subindex
try:
uuid, attribute, index, subindex = path.split(os.sep)
except:
raise exc.HTTPNotFound().exception
# Check if we're authorized
info = extract_cookie("ClacksRPC", self.__secret, environ['HTTP_COOKIE'])
# Query type and dn from uuid
tmp = self.db.index.find_one({'_uuid': uuid}, {'dn': 1, '_type': 1})
if not tmp:
raise exc.HTTPNotFound().exception
aclresolver = PluginRegistry.getInstance("ACLResolver")
topic = "%s.objects.%s.attributes.%s" % (self.env.domain, tmp['_type'], attribute)
if not aclresolver.check(info['REMOTE_USER'], topic, "r", base=tmp['dn']):
raise exc.HTTPForbidden().exception
# Remove extension from subindex
subindex = os.path.splitext(subindex)[0]
# Load the cached binary data and serve it
data = self.db.cache.find_one({'uuid': uuid, 'attribute': attribute,
subindex: {'$exists': True},
"%s.%s" % (subindex, index): {'$exists': True}}, {subindex: 1, 'modified': 1})
if not data:
raise exc.HTTPNotFound().exception
# Tell the client that we've no modification?
lm = req.headers.get('If-Modified-Since')
if lm:
lm = datetime(*rfc822.parsedate(lm)[0:6])
if data['modified'] > lm:
raise exc.HTTPNotModified().exception
resp = Response(
content_type='image/jpeg',
body=str(data[subindex][int(index)]))
resp.cache_control.max_age = 3600
resp.cache_control.private = 1
resp.last_modified = data['modified']
return resp
示例6: __call__
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import last_modified [as 别名]
def __call__(self, req):
fp = open(self.path, 'rb')
resp = Response()
resp.content_type = 'application/octet-stream'
resp.last_modified = os.path.getmtime(self.path)
for line in fp:
line = line.strip()
if not line:
break
name, value = line.split(':')
resp.headers[name] = value.strip()
resp.body = fp.read()
return resp
示例7: index
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import last_modified [as 别名]
def index(self, req):
""" Handle GET and HEAD requests for static files. Directory requests are not allowed"""
static_dir = os.path.normpath(os.path.join(os.path.dirname(__file__), '../static/'))
# filter out ..
try:
static_path = req.urlvars['path'].replace('/..', '')
except:
return HTTPForbidden()
path = os.path.join(static_dir, static_path)
if os.path.isdir(path):
return HTTPForbidden()
if req.method == 'GET' or req.method == 'HEAD':
if os.path.isfile(path):
etag, modified, mime_type, size = self._get_stat(path)
res = Response()
res.headers['content-type'] = mime_type
res.date = rfc822.formatdate(time.time())
res.last_modified = modified
res.etag = etag
if_modified_since = req.headers.get('HTTP_IF_MODIFIED_SINCE')
if if_modified_since:
if rfc822.parsedate(if_modified_since) >= rfc822.parsedate(last_modified):
return HTTPNotModified()
if_none_match = req.headers.get('HTTP_IF_NONE_MATCH')
if if_none_match:
if if_none_match == '*' or etag in if_none_match:
return HTTPNotModified()
# set the response body
if req.method == 'GET':
fd = open(path, 'rb')
if 'wsgi.file_wrapper' in req.environ:
res.app_iter = req.environ['wsgi.file_wrapper'](fd)
res.content_length = size
else:
res.app_iter = iter(lambda: fd.read(8192), '')
res.content_length = size
else:
res.body = ''
return res
else:
return None
else:
return None
示例8: send_file
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import last_modified [as 别名]
def send_file(self, path, mimetype):
"""Send the file located at 'path' back to the user
"""
response = Response(content_type=mimetype,
conditional_response=True)
response.last_modified = os.path.getmtime(path)
response.app_iter = FileIterable(path)
with open(path) as f:
response.body = f.read()
response.content_length = os.path.getsize(path)
# do not accept ranges, since this does not work reliable
# with acrobat IE plugin
response.headers['Accept-Ranges'] = 'none'
return response
示例9: __call__
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import last_modified [as 别名]
def __call__(self, environ, start_response):
req = Request(environ)
resp = Response()
filename = req.path_info.strip('/')
lfilename = filename.lower()
if not req.path_info.strip('/') or os.path.isdir(filename):
if filename:
filename = path(filename, 'index.html')
else:
filename = 'index.html'
body = open(filename, 'rb').read()
resp.body = body
elif os.path.isfile(filename):
if req.method.lower() == 'delete':
sh.rm(filename + '*', shell=True)
resp = exc.HTTPNoContent()
return resp(environ, start_response)
if req.path_info.endswith('.metadata'):
cfg = ConfigObject(filename=filename)
if req.method.lower() == 'get':
resp.content_type = 'application/json'
elif req.method.lower() == 'put':
data = json.loads(req.body)
cfg.metadata.update(data)
cfg.write()
metadata = dict(cfg.metadata.items())
metadata.update(tags=cfg.metadata.tags.as_list())
resp.body = json.dumps(metadata)
elif req.path_info.endswith('.js'):
resp.content_type = 'text/javascript'
elif req.path_info.endswith('.json'):
resp.content_type = 'application/json'
elif req.path_info.endswith('.css'):
resp.content_type = 'text/css'
elif lfilename.endswith('.jpg'):
resp.charset = None
resp.content_type = 'image/jpeg'
print(filename)
if not resp.content_length:
resp.app_iter = fd(filename)
elif req.path_info.startswith('/delete/'):
filename = req.path_info[8:-1]
self.delete(filename)
resp.status_int = 302
resp.location = '/' + path.dirname(filename)
else:
resp.body = str(req.path_info)
resp.last_modified = datetime.now()
return resp(environ, start_response)
示例10: action_view_GET
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import last_modified [as 别名]
def action_view_GET(self, req, page):
if not page.exists:
return exc.HTTPTemporaryRedirect(location=req.url + "?action=edit")
if req.cookies.get("message"):
message = req.cookies["message"]
else:
message = None
text = self.view_template.substitute(page=page, req=req, message=message)
resp = Response(text)
if message:
resp.delete_cookie("message")
else:
resp.last_modified = page.mtime
resp.conditional_response = True
return resp
示例11: make_response
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import last_modified [as 别名]
def make_response(uri, environ):
res = Response(conditional_response=True)
# check if the host is online. If not raise an http error
if not pingSMB( parseSMBuri(uri)["host"] ):
return HTTPGatewayTimeout("Host is currently offline. You may try again at a later time.")
try:
f = c.open(uri)
except smbc.NoEntryError:
return HTTPNotFound("The file you requested is no longer available!")
fs = f.fstat()
filesize = fs[6]
last_modified = fs[8] # mtime
filename = uri.split("/")[-1]
req = Request(environ)
log.debug("Incoming request: \n" + str(req))
if req.range:
log.debug("begin ranged transfer")
res.status_int = 206
res.content_range = req.range.content_range(filesize)
(start, stop) = req.range.range_for_length(filesize)
log.debug("filesize: " + str(filesize))
log.debug("start: " + str(start) + " stop: " + str(stop))
log.debug("Content-Range: " + str(res.content_range))
res.app_iter = FileIterable(uri, start=start, stop=stop)
res.content_length = stop - start
else:
log.debug("begin normal transfer")
res.app_iter = FileIterable(uri)
res.content_length = filesize
log.debug("Content-Length: " + str(res.content_length))
res.server_protocol = "HTTP/1.1"
# Make sure the file gets downloaded and not played live
res.content_type = "application/octet-stream"
res.last_modified = last_modified
res.etag = '%s-%s-%s' % (fs[8], fs[6], hash(f))
res.headers.add("Content-Disposition", 'attachment; filename="%s"' % str(filename) )
res.headers.add("Accept-Ranges", "bytes")
return res
示例12: sendRawResponse
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import last_modified [as 别名]
def sendRawResponse(status, filename, lastmod):
"""Send data. Assume status is a number and filename is the name of a file
containing the body of the response."""
resp = Response(status=status, content_type='text/html')
resp.headers['Access-Control-Allow-Origin'] = '*'
if lastmod and status != 304:
resp.last_modified = lastmod
fp = open(filename)
fp.seek(0, 2)
size = fp.tell()
fp.seek(0)
resp.content_length = size
resp.app_iter = Chunked(fp)
return resp
示例13: __after__
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import last_modified [as 别名]
def __after__(self, result, *args, **kw):
"""Generate the JSON response and sign."""
key = SigningKey.from_string(unhexlify(request.service.key.private), curve=NIST256p, hashfunc=sha256)
response = Response(status=200, charset='utf-8')
response.date = datetime.utcnow()
response.last_modified = result.pop('updated', None)
ct, body = render('json:', result)
response.headers[b'Content-Type'] = str(ct) # protect against lack of conversion in Flup
response.body = body
canon = "{req.service.id}\n{resp.headers[Date]}\n{req.url}\n{resp.body}".format(
req = request,
resp = response
示例14: sendJsonResponse
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import last_modified [as 别名]
def sendJsonResponse(status, data, lastmod):
"""Send data. Assume status is a number and data is a dictionary that can
be written via json.write."""
resp = Response(status=status, content_type='text/html')
resp.headers['Access-Control-Allow-Origin'] = '*'
if lastmod and status != 304:
resp.last_modified = lastmod
def convert_set(obj):
if isinstance(obj, set):
return list(obj)
raise TypeError
if data:
data = json.dumps(data, separators=(',', ':'),
default=convert_set)
resp.body = data
return resp
示例15: serve_file
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import last_modified [as 别名]
def serve_file(filename):
if os.path.exists(filename):
basename = urlutils.basename(filename)
content_type = mimetypes.guess_type(basename)[0]
res = Response(content_type=content_type, conditional_response=True)
res.app_iter = FileIterable(filename)
res.content_length = os.path.getsize(filename)
res.last_modified = os.path.getmtime(filename)
# Todo: is this the best value for the etag?
# perhaps md5 would be a better alternative
res.etag = '%s-%s-%s' % (os.path.getmtime(filename),
os.path.getsize(filename),
hash(filename))
return res
else:
return HTTPNotFound()