本文整理汇总了Python中werkzeug.wrappers.Response.response方法的典型用法代码示例。如果您正苦于以下问题:Python Response.response方法的具体用法?Python Response.response怎么用?Python Response.response使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类werkzeug.wrappers.Response
的用法示例。
在下文中一共展示了Response.response方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: dbfile_handler
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import response [as 别名]
def dbfile_handler(self, environ, args):
try:
fobj = self.file_cacher.get_file(args['digest'])
except KeyError:
raise NotFound()
response = Response()
response.status_code = 200
response.mimetype = 'application/octet-stream'
if 'name' in args:
if args["name"].endswith(".pdf"):
# Add header to allow the official pdf.js to work
response.headers.add_header(b'Access-Control-Allow-Origin',
b'https://mozilla.github.io')
else:
# Don't do this on pdf files because it breaks the native pdf reader
response.headers.add_header(
b'Content-Disposition', b'attachment',
filename=args['name'])
mimetype = mimetypes.guess_type(args['name'])[0]
if mimetype is not None:
response.mimetype = mimetype
response.response = wrap_file(environ, fobj)
response.direct_passthrough = True
response.cache_control.max_age = 31536000
response.cache_control.public = True
return response
示例2: get_file_response
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import response [as 别名]
def get_file_response(self, path, request):
try:
full_path = find_file(self.search_paths, path)
if full_path is None:
raise NotFound()
file_obj = open(full_path, 'rb')
mtime = get_file_mtime(full_path)
fsize = os.path.getsize(full_path)
except (ValueError, IOError, OSError):
raise Forbidden()
mimetype, encoding = mimetypes.guess_type(full_path)
if not mimetype:
peeked = peek_file(file_obj, 1024)
is_binary = is_binary_string(peeked)
if peeked and is_binary:
mimetype = self.default_binary_mime
else:
mimetype = self.default_text_mime # TODO: binary
resp = Response('')
cached_mtime = request.if_modified_since
if self.cache_timeout:
resp.cache_control.public = True
if mtime == cached_mtime:
file_obj.close()
resp.status_code = 304
resp.cache_control.max_age = self.cache_timeout
return resp
file_wrapper = request.environ.get('wsgi.file_wrapper', FileWrapper)
resp.response = file_wrapper(file_obj)
resp.content_type = mimetype
resp.content_length = fsize
resp.last_modified = mtime
return resp
示例3: test_wrapper_internals
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import response [as 别名]
def test_wrapper_internals():
"""Test internals of the wrappers"""
from werkzeug.wrappers import Request
req = Request.from_values(data={'foo': 'bar'}, method='POST')
req._load_form_data()
assert req.form.to_dict() == {'foo': 'bar'}
# second call does not break
req._load_form_data()
assert req.form.to_dict() == {'foo': 'bar'}
# check reprs
assert repr(req) == "<Request 'http://localhost/' [POST]>"
resp = Response()
assert repr(resp) == '<Response 0 bytes [200 OK]>'
resp.data = 'Hello World!'
assert repr(resp) == '<Response 12 bytes [200 OK]>'
resp.response = iter(['Test'])
assert repr(resp) == '<Response streamed [200 OK]>'
# unicode data does not set content length
response = Response([u'Hällo Wörld'])
headers = response.get_wsgi_headers(create_environ())
assert 'Content-Length' not in headers
response = Response(['Hällo Wörld'])
headers = response.get_wsgi_headers(create_environ())
assert 'Content-Length' in headers
# check for internal warnings
print 'start'
filterwarnings('error', category=Warning)
response = Response()
environ = create_environ()
response.response = 'What the...?'
assert_raises(Warning, lambda: list(response.iter_encoded()))
assert_raises(Warning, lambda: list(response.get_app_iter(environ)))
response.direct_passthrough = True
assert_raises(Warning, lambda: list(response.iter_encoded()))
assert_raises(Warning, lambda: list(response.get_app_iter(environ)))
resetwarnings()
示例4: get
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import response [as 别名]
def get(self):
path = self.kwargs['path']
filename = os.path.join(self.static_dir, path)
if not os.path.isfile(filename):
raise NotFound
type, encoding = guess_type(filename)
type = type or 'application/octet-stream'
expiry = time.asctime(time.gmtime(time.time() + 3600))
response = Response(mimetype=type)
response.headers['Expires'] = expiry
response.headers['Cache-Control'] = 'public'
response.response = open(filename, 'rb')
return response
示例5: file_handler
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import response [as 别名]
def file_handler(self, environ, filename):
path = os.path.join(pkg_resources.resource_filename("cms.web", "practice"), filename)
response = Response()
response.status_code = 200
response.mimetype = "application/octet-stream"
mimetype = mimetypes.guess_type(filename)[0]
if mimetype is not None:
response.mimetype = mimetype
response.last_modified = datetime.utcfromtimestamp(os.path.getmtime(path)).replace(microsecond=0)
response.response = wrap_file(environ, io.open(path, "rb"))
response.direct_passthrough = True
return response
示例6: wsgi_app
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import response [as 别名]
def wsgi_app(self, environ, start_response):
"""Execute this instance as a WSGI application.
See the PEP for the meaning of parameters. The separation of
__call__ and wsgi_app eases the insertion of middlewares.
"""
original_response = Response.from_app(self.wrapped_app, environ)
# We send relative locations to play nice with reverse proxies
# but Werkzeug by default turns them into absolute ones.
original_response.autocorrect_location_header = False
if self.DIGEST_HEADER not in original_response.headers:
return original_response
digest = original_response.headers.pop(self.DIGEST_HEADER)
filename = original_response.headers.pop(self.FILENAME_HEADER, None)
mimetype = original_response.mimetype
try:
fobj = self.file_cacher.get_file(digest)
size = self.file_cacher.get_size(digest)
except KeyError:
return NotFound()
except TombstoneError:
return ServiceUnavailable()
request = Request(environ)
request.encoding_errors = "strict"
response = Response()
response.status_code = 200
response.mimetype = mimetype
if filename is not None:
response.headers.add(
"Content-Disposition", "attachment", filename=filename)
response.set_etag(digest)
response.cache_control.max_age = SECONDS_IN_A_YEAR
response.cache_control.private = True
response.response = \
wrap_file(environ, fobj, buffer_size=FileCacher.CHUNK_SIZE)
response.direct_passthrough = True
try:
# This takes care of conditional and partial requests.
response.make_conditional(
request, accept_ranges=True, complete_length=size)
except HTTPException as exc:
return exc
return response
示例7: test_wrapper_internals
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import response [as 别名]
def test_wrapper_internals():
req = Request.from_values(data={"foo": "bar"}, method="POST")
req._load_form_data()
assert req.form.to_dict() == {"foo": "bar"}
# second call does not break
req._load_form_data()
assert req.form.to_dict() == {"foo": "bar"}
# check reprs
assert repr(req) == "<Request 'http://localhost/' [POST]>"
resp = Response()
assert repr(resp) == "<Response 0 bytes [200 OK]>"
resp.set_data("Hello World!")
assert repr(resp) == "<Response 12 bytes [200 OK]>"
resp.response = iter(["Test"])
assert repr(resp) == "<Response streamed [200 OK]>"
# unicode data does not set content length
response = Response([u"Hällo Wörld"])
headers = response.get_wsgi_headers(create_environ())
assert u"Content-Length" not in headers
response = Response([u"Hällo Wörld".encode("utf-8")])
headers = response.get_wsgi_headers(create_environ())
assert u"Content-Length" in headers
# check for internal warnings
filterwarnings("error", category=Warning)
response = Response()
environ = create_environ()
response.response = "What the...?"
pytest.raises(Warning, lambda: list(response.iter_encoded()))
pytest.raises(Warning, lambda: list(response.get_app_iter(environ)))
response.direct_passthrough = True
pytest.raises(Warning, lambda: list(response.iter_encoded()))
pytest.raises(Warning, lambda: list(response.get_app_iter(environ)))
resetwarnings()
示例8: wsgi_app
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import response [as 别名]
def wsgi_app(self, environ, start_response):
request = Request(environ)
request.encoding_errors = "strict"
response = Response()
response.status_code = 200
response.mimetype = "text/html"
response.last_modified = \
datetime.utcfromtimestamp(os.path.getmtime(self.path))\
.replace(microsecond=0)
# TODO check for If-Modified-Since and If-None-Match
response.response = wrap_file(environ, open(self.path, 'rb'))
response.direct_passthrough = True
return response
示例9: render_keystone
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import response [as 别名]
def render_keystone(self, request, template):
response = Response(mimetype='text/html')
viewlocals = {
'request': request,
'http': http,
'headers': response.headers,
'set_cookie': response.set_cookie,
'delete_cookie': response.delete_cookie,
'return_response': return_response,
'app_dir': self.app_dir,
}
try:
response.response = self.engine.render(template, viewlocals)
except HTTPException, ex:
return ex.get_response(request.environ)
示例10: dbfile_handler
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import response [as 别名]
def dbfile_handler(self, environ, args):
try:
fobj = self.file_cacher.get_file(args['digest'])
except KeyError:
raise NotFound()
response = Response()
response.status_code = 200
response.mimetype = 'application/octet-stream'
if 'filename' in args:
response.headers.add_header(
b'Content-Disposition', b'attachment',
filename=args['filename'])
mimetype = mimetypes.guess_type(args['filename'])[0]
if mimetype is not None:
response.mimetype = mimetype
response.response = wrap_file(environ, fobj)
response.direct_passthrough = True
return response
示例11: dbfile_handler
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import response [as 别名]
def dbfile_handler(self, environ, args):
try:
fobj = self.file_cacher.get_file(args["digest"])
except KeyError:
raise NotFound()
response = Response()
response.status_code = 200
response.mimetype = "application/octet-stream"
if "name" in args:
if not args["name"].endswith(".pdf"):
# Don't do this on pdf files because it breaks the native pdf reader
response.headers.add_header(b"Content-Disposition", b"attachment", filename=args["name"])
mimetype = mimetypes.guess_type(args["name"])[0]
if mimetype is not None:
response.mimetype = mimetype
response.response = wrap_file(environ, fobj)
response.direct_passthrough = True
return response
示例12: wsgi_app
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import response [as 别名]
def wsgi_app(self, environ, start_response):
route = self.router.bind_to_environ(environ)
try:
endpoint, args = route.match()
except HTTPException as exc:
return exc
location = self.location % args
request = Request(environ)
request.encoding_errors = "strict"
response = Response()
available = list()
for extension, mimetype in self.EXT_TO_MIME.iteritems():
if os.path.isfile(location + '.' + extension):
available.append(mimetype)
mimetype = request.accept_mimetypes.best_match(available)
if mimetype is not None:
path = "%s.%s" % (location, self.MIME_TO_EXT[mimetype])
else:
path = self.fallback
mimetype = 'image/png' # FIXME Hardcoded type.
response.status_code = 200
response.mimetype = mimetype
response.last_modified = \
datetime.utcfromtimestamp(os.path.getmtime(path))\
.replace(microsecond=0)
# TODO check for If-Modified-Since and If-None-Match
response.response = wrap_file(environ, io.open(path, 'rb'))
response.direct_passthrough = True
return response