本文整理汇总了Python中werkzeug.wrappers.Response类的典型用法代码示例。如果您正苦于以下问题:Python Response类的具体用法?Python Response怎么用?Python Response使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Response类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:kalxas,项目名称:pywps,代码行数:7,代码来源:basic.py
示例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
开发者ID:08haozi,项目名称:uliweb,代码行数:28,代码来源:utils.py
示例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
开发者ID:acube-unipi,项目名称:oii-web,代码行数:30,代码来源:task_type_api.py
示例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
开发者ID:sinistersnare,项目名称:PieCrust2,代码行数:31,代码来源:server.py
示例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'
开发者ID:2009bpy,项目名称:werkzeug,代码行数:30,代码来源:test_fixers.py
示例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)
开发者ID:fangbei,项目名称:flask-webcache,代码行数:7,代码来源:test_validation.py
示例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
开发者ID:jdotpy,项目名称:watchtower,代码行数:7,代码来源:web.py
示例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)
开发者ID:cms-dev,项目名称:cms,代码行数:31,代码来源:RankingWebServer.py
示例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
开发者ID:alex-liao,项目名称:cms,代码行数:32,代码来源:RankingWebServer.py
示例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()
开发者ID:justinabrahms,项目名称:pisces,代码行数:25,代码来源:__init__.py
示例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)
开发者ID:pallets,项目名称:werkzeug,代码行数:7,代码来源:test_test.py
示例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
开发者ID:eabraham,项目名称:Presence-Detector,代码行数:32,代码来源:presence.py
示例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
开发者ID:AaronLaw,项目名称:omega,代码行数:28,代码来源:core.py
示例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
开发者ID:hoangtk,项目名称:metro-test,代码行数:7,代码来源:controllers.py
示例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
开发者ID:AKST,项目名称:wiki-timelapse,代码行数:7,代码来源:handle_base.py
示例16: send_private_file
def send_private_file(path):
path = os.path.join(frappe.local.conf.get(
'private_path', 'private'), path.strip("/"))
filename = os.path.basename(path)
if frappe.local.request.headers.get('X-Use-X-Accel-Redirect'):
path = '/protected/' + path
response = Response()
response.headers[b'X-Accel-Redirect'] = frappe.utils.encode(path)
else:
filepath = frappe.utils.get_site_path(path)
try:
f = open(filepath, 'rb')
except IOError:
raise NotFound
response = Response(
wrap_file(frappe.local.request.environ, f), direct_passthrough=True)
# no need for content disposition and force download. let browser handle its opening.
# response.headers.add(b'Content-Disposition', b'attachment', filename=filename.encode("utf-8"))
response.mimetype = mimetypes.guess_type(
filename)[0] or b'application/octet-stream'
return response
开发者ID:vhrspvl,项目名称:vhrs-frappe,代码行数:27,代码来源:response.py
示例17: application
def application(request):
if request.method == 'GET':
path = list(filter((lambda x: len(x) > 0), re.split('/+', request.path)))
if len(path) == 0:
return view_root(request)
elif len(path) >= 1 and path[0] == 'messages':
if len(path) == 1:
return view_messages_list(request)
elif len(path) == 2:
return view_message(request, path[1])
elif len(path) == 3 and path[2] == 'editor':
return edit_message(request, path[1])
else:
return NotFound()
elif len(path) >= 1 and path[0] == 'services':
if len(path) == 1:
return view_services_list(request)
elif len(path) == 2:
return view_ports_list(request, path[1])
elif len(path) == 3:
return view_operations_list(request, path[1], path[2])
else:
return NotFound()
else:
return NotFound()
elif request.method == 'POST':
return Response('post')
else:
response = Response()
response.status_code = 400
return response
开发者ID:Torlus,项目名称:soapyfy,代码行数:31,代码来源:soapyfy.py
示例18: as_binary
def as_binary():
response = Response()
response.mimetype = 'application/octet-stream'
response.headers[b"Content-Disposition"] = (
"filename=\"%s\"" % frappe.response['filename'].replace(' ', '_')).encode("utf-8")
response.data = frappe.response['filecontent']
return response
开发者ID:vhrspvl,项目名称:vhrs-frappe,代码行数:7,代码来源:response.py
示例19: ignored_callback
def ignored_callback(environ, start_response):
response = Response('{"Error":"NotAuthenticated"}')
# response.status = '401 Unauthorized'
response.status = '200 OK'
response.headers['Content-Type'] = 'application/json'
return response(environ, start_response)
开发者ID:wrighting,项目名称:cas_wsgi_middleware,代码行数:7,代码来源:test.py
示例20: __get_response
def __get_response(self, environ, args, kwargs, endpoint):
if endpoint.__name__ == "service_check":
result = endpoint(*args, **kwargs)
response = Response(result['body'])
response.status_code = result['status']
return response
response = {
'server_info': {
'http_headers': dict(EnvironHeaders(environ)),
'response_id': 0,
'arguments': repr(args) if args else repr(kwargs),
'processing_time': 0.0
},
'response': {}
}
start_time = time.time()
# Make the call
result = endpoint(*args, **kwargs)
# Send the API call response
response['response'] = result
response['server_info']['processing_time'] = 1000*(time.time() - start_time)
try:
response = json.dumps(response)
except (TypeError, UnicodeError):
return InternalServerError(description = "Could not encode service response")
response = Response(response)
response.headers['content-type'] = 'application/json'
return response
开发者ID:codemartial,项目名称:wsloader,代码行数:32,代码来源:wsloader.py
注:本文中的werkzeug.wrappers.Response类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论