本文整理汇总了Python中werkzeug.wrappers.Response类的典型用法代码示例。如果您正苦于以下问题:Python Response类的具体用法?Python Response怎么用?Python Response使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Response类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: xml_response
def xml_response(doc):
pywps_version_comment = '<!-- PyWPS %s -->\n' % __version__
xml = lxml.etree.tostring(doc, pretty_print=True)
response = Response(pywps_version_comment.encode('utf8') + xml,
content_type='text/xml')
response.status_percentage = 100;
return response
示例2: redirect
def redirect(location, code=302):
"""Return a response object (a WSGI application) that, if called,
redirects the client to the target location. Supported codes are 301,
302, 303, 305, and 307. 300 is not supported because it's not a real
redirect and 304 because it's the answer for a request with a request
with defined If-Modified-Since headers.
.. versionadded:: 0.6
The location can now be a unicode string that is encoded using
the :func:`iri_to_uri` function.
:param location: the location the response should redirect to.
:param code: the redirect status code. defaults to 302.
"""
from werkzeug.wrappers import Response
display_location = escape(location)
if isinstance(location, text_type):
from werkzeug.urls import iri_to_uri
location = iri_to_uri(location)
response = Response(
'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n'
'<title>Redirecting...</title>\n'
'<h1>Redirecting...</h1>\n'
'<p>You should be redirected automatically to target URL: '
'<a href="%s">%s</a>. If not click the link.' %
(escape(location), display_location), code, mimetype='text/html')
response.headers['Location'] = location
return response
示例3: wsgi_app
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.
"""
urls = self._url_map.bind_to_environ(environ)
try:
endpoint, args = urls.match()
except HTTPException as exc:
return exc
assert endpoint == "get"
request = Request(environ)
request.encoding_errors = "strict"
response = Response()
result = dict()
for task_type in self._task_types:
result[task_type.__name__] = \
list(p.describe() for p in task_type.ACCEPTED_PARAMETERS)
response.status_code = 200
response.mimetype = "application/json"
response.data = json.dumps(result)
return response
示例4: _try_special_request
def _try_special_request(self, environ, request):
static_mount = '/__piecrust_static/'
if request.path.startswith(static_mount):
rel_req_path = request.path[len(static_mount):]
mount = os.path.join(RESOURCES_DIR, 'server')
full_path = os.path.join(mount, rel_req_path)
try:
response = self._make_wrapped_file_response(
environ, request, full_path)
return response
except OSError:
pass
debug_mount = '/__piecrust_debug/'
if request.path.startswith(debug_mount):
rel_req_path = request.path[len(debug_mount):]
if rel_req_path == 'pipeline_status':
from piecrust.serving.procloop import (
PipelineStatusServerSideEventProducer)
provider = PipelineStatusServerSideEventProducer(
self._proc_loop.status_queue)
it = ClosingIterator(provider.run(), [provider.close])
response = Response(it)
response.headers['Cache-Control'] = 'no-cache'
if 'text/event-stream' in request.accept_mimetypes:
response.mimetype = 'text/event-stream'
response.direct_passthrough = True
response.implicit_sequence_conversion = False
return response
return None
示例5: test_proxy_fix
def test_proxy_fix(self):
@Request.application
def app(request):
return Response('%s|%s' % (
request.remote_addr,
# do not use request.host as this fixes too :)
request.environ['HTTP_HOST']
))
app = fixers.ProxyFix(app, num_proxies=2)
environ = dict(
create_environ(),
HTTP_X_FORWARDED_PROTO="https",
HTTP_X_FORWARDED_HOST='example.com',
HTTP_X_FORWARDED_FOR='1.2.3.4, 5.6.7.8',
REMOTE_ADDR='127.0.0.1',
HTTP_HOST='fake'
)
response = Response.from_app(app, environ)
assert response.get_data() == b'1.2.3.4|example.com'
# And we must check that if it is a redirection it is
# correctly done:
redirect_app = redirect('/foo/bar.hml')
response = Response.from_app(redirect_app, environ)
wsgi_headers = response.get_wsgi_headers(environ)
assert wsgi_headers['Location'] == 'https://example.com/foo/bar.hml'
示例6: test_date_no_clobber
def test_date_no_clobber(self):
r = Response()
r.date = 0
r.last_modified = 0
v.add_date_fields(r)
self.assertEquals(r.date.year, 1970)
self.assertEquals(r.last_modified.year, 1970)
示例7: handle
def handle(self, request):
request.app = self
response = self.dashboard(request)
if isinstance(response, str):
response = Response(response)
response.headers['Content-Type'] = 'text/html'
return response
示例8: wsgi_app
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(environ, start_response)
assert endpoint == "sublist"
request = Request(environ)
request.encoding_errors = "strict"
if request.accept_mimetypes.quality("application/json") <= 0:
raise NotAcceptable()
result = list()
for task_id in self.task_store._store.keys():
result.extend(
self.scoring_store.get_submissions(
args["user_id"], task_id
).values()
)
result.sort(key=lambda x: (x.task, x.time))
result = list(a.__dict__ for a in result)
response = Response()
response.status_code = 200
response.mimetype = "application/json"
response.data = json.dumps(result)
return response(environ, start_response)
示例9: wsgi_app
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
request = Request(environ)
request.encoding_errors = "strict"
response = Response()
response.headers[b'X-Frame-Options'] = b'SAMEORIGIN'
try:
if endpoint == "get":
self.get(request, response, args["key"])
elif endpoint == "get_list":
self.get_list(request, response)
elif endpoint == "put":
self.put(request, response, args["key"])
elif endpoint == "put_list":
self.put_list(request, response)
elif endpoint == "delete":
self.delete(request, response, args["key"])
elif endpoint == "delete_list":
self.delete_list(request, response)
else:
raise RuntimeError()
except HTTPException as exc:
return exc
return response
示例10: wsgi_app
def wsgi_app(self, environ, start_response):
"""
Main WSGI Interface
"""
request = Request(environ)
for route in self._routes:
log.debug("Attempting route: %s", route)
method = route.match(request.path, request.method)
if method is None:
continue
### EEW. Not sure I like this.
extra_params = self._extract_params_from_request(method, request)
value_map = method(**extra_params)
if value_map is not None:
# for now, we're doing dict only
response = Response(mimetype="application/json")
# EEW. It doesn't get any better on the response.
self.apply_consumer_mutations(value_map, response)
json_dump = json.dumps(value_map)
response.data = json_dump
return response(environ, start_response)
raise NotFound()
示例11: cookie_app
def cookie_app(environ, start_response):
"""A WSGI application which sets a cookie, and returns as a response any
cookie which exists.
"""
response = Response(environ.get("HTTP_COOKIE", "No Cookie"), mimetype="text/plain")
response.set_cookie("test", "test")
return response(environ, start_response)
示例12: application
def application(request):
logger = logging.getLogger('presence_detection')
logger.setLevel(logging.INFO)
fh = logging.FileHandler(os.path.expanduser('~/presence2/log/presence_detection.log'),mode='a', encoding=None, delay=False)
formatter = logging.Formatter('%(asctime)s - %(levelname)r - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
rsa_key='AAAAB3NzaC1yc2EAAAADAQABAAAAgwCjvHkbqL/V0ytnfa5pIak7bxBfj6nF4S7vy51ZG8LlWYAXcQ9WGfUGfhG+l1GW9hPeQzQbeRyNiQM+ufue/M9+JKCXTIugksAnN3W+NV/DeDcq9sKR9MiiNH3ZeNtGSyPGYjcLVmK6aSVTUoEO2yRrha9fiWBy5hb93UdmJX+QguC9'
router_address='makerbar.berthartm.org'
router_port = 2222
stdin, stdout, stderr =get_router_mac_addresses(rsa_key,router_address,router_port)
usermap = get_dict()
attendance = set()
for line in stdout:
MAC = line[10:27]
if MAC in usermap:
attendance.add(usermap[MAC])
logger.info('%s (%s) is at the MakerBar.' % (usermap[MAC],MAC))
else:
logger.info('Unknown user(%s) is at the MakerBar.' % MAC)
output = ''
for user in attendance:
output += user + '\n'
response = Response(output)
if output == '':
response.status_code = 204 # No content
fh.close()
return response
示例13: dispatch_request
def dispatch_request(self, urls, request):
"""Dispatch the incoming *request* to the given view function or class.
If the "request" is a socket.io message, route it to the registered
namespace.
:param urls: The URLs parsed by binding the URL map to the environment.
:param request: The current HTTP request.
:type request :class:`werkzeug.Request`:
"""
if request.path.startswith('/socket.io'):
try:
socketio_manage(request.environ, self._namespaces, request)
except:
print("Exception while handling socketio connection")
return Response()
else:
response = urls.dispatch(
lambda e, v: self._routes[e](
request, **v))
if isinstance(response, (unicode, str)):
headers = {'Content-type': 'text/html'}
response = Response(response, headers=headers)
if not response:
headers = {'Content-type': 'text/html'}
response = Response('404 Not Found', headers=headers)
response.status_code = 404
return response
示例14: index
def index(self, request, file_name, file_data):
pdf_data = open(file_data,'rb').read()
response = Response(pdf_data)
response.headers['Content-Type'] = 'application/pdf'
#response.headers['Content-Disposition'] = 'attachment; filename="%s.pdf"'%file_name
response.headers['Content-Disposition'] = content_disposition(file_name, request)
return response
示例15: __build_response
def __build_response(self, output):
res = Response(output)
res.content_type = self.content_type
res.expires = datetime.today() + timedelta(7)
for header, value in self.__headers:
res.headers[header] = value
return res