本文整理汇总了Python中werkzeug.wrappers.Response.from_app方法的典型用法代码示例。如果您正苦于以下问题:Python Response.from_app方法的具体用法?Python Response.from_app怎么用?Python Response.from_app使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类werkzeug.wrappers.Response
的用法示例。
在下文中一共展示了Response.from_app方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_proxy_fix
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import from_app [as 别名]
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'
示例2: test_cgi_root_fix_custom_app_root
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import from_app [as 别名]
def test_cgi_root_fix_custom_app_root(self):
app = fixers.CGIRootFix(path_check_app, app_root='/baz/poop/')
response = Response.from_app(app, dict(create_environ(),
SCRIPT_NAME='/foo',
PATH_INFO='/bar'
))
self.assert_equal(response.get_data(), b'PATH_INFO: /foo/bar\nSCRIPT_NAME: baz/poop')
示例3: test_path_info_from_request_uri_fix
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import from_app [as 别名]
def test_path_info_from_request_uri_fix(self):
app = fixers.PathInfoFromRequestUriFix(path_check_app)
for key in 'REQUEST_URI', 'REQUEST_URL', 'UNENCODED_URL':
env = dict(create_environ(), SCRIPT_NAME='/test', PATH_INFO='/?????')
env[key] = '/test/foo%25bar?drop=this'
response = Response.from_app(app, env)
assert response.get_data() == b'PATH_INFO: /foo%bar\nSCRIPT_NAME: /test'
示例4: test_lighttpd_cgi_root_fix
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import from_app [as 别名]
def test_lighttpd_cgi_root_fix(self):
app = fixers.LighttpdCGIRootFix(path_check_app)
response = Response.from_app(app, dict(create_environ(),
SCRIPT_NAME='/foo',
PATH_INFO='/bar',
SERVER_SOFTWARE='lighttpd/1.4.27'
))
assert response.data == 'PATH_INFO: /foo/bar\nSCRIPT_NAME: '
示例5: test_lighttpd_cgi_root_fix
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import from_app [as 别名]
def test_lighttpd_cgi_root_fix():
"""Test the LighttpdCGIRootFix fixer"""
app = fixers.LighttpdCGIRootFix(path_check_app)
response = Response.from_app(app, dict(create_environ(),
SCRIPT_NAME='/foo',
PATH_INFO='/bar'
))
assert response.data == 'PATH_INFO: /foo/bar\nSCRIPT_NAME: '
示例6: test_cgi_root_fix
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import from_app [as 别名]
def test_cgi_root_fix(self):
app = fixers.CGIRootFix(path_check_app)
response = Response.from_app(app, dict(create_environ(),
SCRIPT_NAME='/foo',
PATH_INFO='/bar',
SERVER_SOFTWARE='lighttpd/1.4.27'
))
self.assert_equal(response.get_data(),
b'PATH_INFO: /foo/bar\nSCRIPT_NAME: ')
示例7: test_header_rewriter_fix
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import from_app [as 别名]
def test_header_rewriter_fix(self):
@Request.application
def application(request):
return Response("", headers=[
('X-Foo', 'bar')
])
application = fixers.HeaderRewriterFix(application, ('X-Foo',), (('X-Bar', '42'),))
response = Response.from_app(application, create_environ())
assert response.headers['Content-Type'] == 'text/plain; charset=utf-8'
assert 'X-Foo' not in response.headers
assert response.headers['X-Bar'] == '42'
示例8: test_proxy_fix_weird_enum
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import from_app [as 别名]
def test_proxy_fix_weird_enum(self):
@fixers.ProxyFix
@Request.application
def app(request):
return Response(request.remote_addr)
environ = dict(create_environ(),
HTTP_X_FORWARDED_FOR=',',
REMOTE_ADDR='127.0.0.1',
)
response = Response.from_app(app, environ)
self.assert_equal(response.data, '127.0.0.1')
示例9: __call__
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import from_app [as 别名]
def __call__(self, environ, start_response):
"""Process a request"""
# Set up the request and do our pre-processing
request = Request(environ)
self.before(request)
# Defer to the wrapped app, then do our cleanup n stuff
response = Response.from_app(self.app, environ)
self.after(request, response)
release_local(self.local)
# finally, blah
return response(environ, start_response)
示例10: wsgi_app
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import from_app [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
示例11: test_proxy_fix
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import from_app [as 别名]
def test_proxy_fix():
"""Test the ProxyFix fixer"""
@fixers.ProxyFix
@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']
))
response = Response.from_app(app, dict(create_environ(),
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'
))
assert response.data == '1.2.3.4|example.com'
示例12: test_fix_headers_in_response
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import from_app [as 别名]
def test_fix_headers_in_response(self):
# ignore some warnings werkzeug emits for backwards compat
for msg in ['called into deprecated fix_headers',
'fix_headers changed behavior']:
warnings.filterwarnings('ignore', message=msg,
category=DeprecationWarning)
class MyResponse(Response):
def fix_headers(self, environ):
Response.fix_headers(self, environ)
self.headers['x-foo'] = "meh"
myresp = MyResponse('Foo')
resp = Response.from_app(myresp, create_environ(method='GET'))
assert resp.headers['x-foo'] == 'meh'
assert resp.data == 'Foo'
warnings.resetwarnings()
示例13: handler
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import from_app [as 别名]
def handler(self, event, context):
"""
An AWS Lambda function which parses specific API Gateway input into a
WSGI request, feeds it to our WSGI app, procceses the response, and returns
that back to the API Gateway.
"""
time_start = datetime.datetime.now()
settings = self.settings
# The app module
app_module = importlib.import_module(settings.APP_MODULE)
# The application
app_function = getattr(app_module, settings.APP_FUNCTION)
app = ZappaWSGIMiddleware(app_function)
# This is a normal HTTP request
if event.get('method', None):
# If we just want to inspect this,
# return this event instead of processing the request
# https://your_api.aws-api.com/?event_echo=true
event_echo = getattr(settings, "EVENT_ECHO", True)
if event_echo:
if 'event_echo' in list(event['params'].values()):
return {'Content': str(event) + '\n' + str(context), 'Status': 200}
# Create the environment for WSGI and handle the request
environ = create_wsgi_request(event, script_name='',
trailing_slash=False)
# We are always on https on Lambda, so tell our wsgi app that.
environ['wsgi.url_scheme'] = 'https'
response = Response.from_app(app, environ)
zappa_returndict = dict()
if response.data:
zappa_returndict['Content'] = response.data
# Pack the WSGI response into our special dictionary.
for (header_name, header_value) in response.headers:
zappa_returndict[header_name] = header_value
zappa_returndict['Status'] = response.status_code
# To ensure correct status codes, we need to
# pack the response as a deterministic B64 string and raise it
# as an error to match our APIGW regex.
# The DOCTYPE ensures that the page still renders in the browser.
exception = None
if response.status_code in [400, 401, 403, 404, 500]:
content = "<!DOCTYPE html>" + str(response.status_code) + response.data
exception = base64.b64encode(content)
# Internal are changed to become relative redirects
# so they still work for apps on raw APIGW and on a domain.
elif response.status_code in [301, 302]:
# Location is by default relative on Flask. Location is by default
# absolute on Werkzeug. We can set autocorrect_location_header on
# the response to False, but it doesn't work. We have to manually
# remove the host part.
location = response.location
hostname = 'https://' + environ['HTTP_HOST']
if location.startswith(hostname):
exception = location[len(hostname):]
# Calculate the total response time,
# and log it in the Common Log format.
time_end = datetime.datetime.now()
delta = time_end - time_start
response_time_ms = delta.total_seconds() * 1000
response.content = response.data
common_log(environ, response, response_time=response_time_ms)
# Finally, return the response to API Gateway.
if exception: # pragma: no cover
raise Exception(exception)
else:
return zappa_returndict
示例14: handler
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import from_app [as 别名]
def handler(self, event, context):
"""
An AWS Lambda function which parses specific API Gateway input into a
WSGI request, feeds it to our WSGI app, procceses the response, and returns
that back to the API Gateway.
"""
# TODO If this is invoked from a non-APIGW/Scheduled event source,
# extract the method and process separately.
if event.get('detail-type', None) == u'Scheduled Event':
whole_function = event['resources'][0].split('/')[-1]
module, function = whole_function.rsplit('.', 1)
app_module = importlib.import_module(module)
app_function = getattr(app_module, function)
# Execute the function!
app_function()
return
try:
# Timing
time_start = datetime.datetime.now()
settings = self.settings
# Custom log level
if settings.LOG_LEVEL:
level = logging.getLevelName(settings.LOG_LEVEL)
logger.setLevel(level)
# The app module
app_module = importlib.import_module(settings.APP_MODULE)
# The application
app_function = getattr(app_module, settings.APP_FUNCTION)
app = ZappaWSGIMiddleware(app_function)
# This is a normal HTTP request
if event.get('method', None):
# If we just want to inspect this,
# return this event instead of processing the request
# https://your_api.aws-api.com/?event_echo=true
event_echo = getattr(settings, "EVENT_ECHO", True)
if event_echo and 'event_echo' in event['params'].values():
return {'Content': str(event) + '\n' + str(context), 'Status': 200}
if settings.DOMAIN:
# If we're on a domain, we operate normally
script_name = ''
else:
# But if we're not, then our base URL
# will be something like
# https://blahblahblah.execute-api.us-east-1.amazonaws.com/dev
# So, we need to make sure the WSGI app knows this.
script_name = '/' + settings.API_STAGE
# Create the environment for WSGI and handle the request
environ = create_wsgi_request(event,
script_name=script_name,
trailing_slash=False
)
# We are always on https on Lambda, so tell our wsgi app that.
environ['wsgi.url_scheme'] = 'https'
# Execute the application
response = Response.from_app(app, environ)
# This is the object we're going to return.
# Pack the WSGI response into our special dictionary.
zappa_returndict = dict(response.headers)
if 'Content' not in zappa_returndict and response.data:
zappa_returndict['Content'] = response.data
zappa_returndict['Status'] = response.status_code
# To ensure correct status codes, we need to
# pack the response as a deterministic B64 string and raise it
# as an error to match our APIGW regex.
# The DOCTYPE ensures that the page still renders in the browser.
exception = None
if response.status_code in [400, 401, 403, 404, 500]:
content = "<!DOCTYPE html>" + str(response.status_code) + response.data
exception = base64.b64encode(content)
# Internal are changed to become relative redirects
# so they still work for apps on raw APIGW and on a domain.
elif response.status_code in [301, 302]:
# Location is by default relative on Flask. Location is by default
# absolute on Werkzeug. We can set autocorrect_location_header on
# the response to False, but it doesn't work. We have to manually
# remove the host part.
location = response.location
hostname = 'https://' + environ['HTTP_HOST']
if location.startswith(hostname):
exception = location[len(hostname):]
#.........这里部分代码省略.........
示例15: test_wsgi_middleware_realcall
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import from_app [as 别名]
def test_wsgi_middleware_realcall(self):
print("1: Setting the cookies.")
event = {
u'method': u'POST',
u'params': {u'parameter_1': u'set_cookie'},
u'body': u'foo=xxx&bar=yyy',
u'headers': {},
u'query': {}}
def set_cookies(environ, start_response):
status = '200 OK'
print environ
response_headers = [('Set-Cookie', 'foo=123'),
('Set-Cookie', 'bar=456'),
('Set-Cookie', 'baz=789')]
start_response(status, response_headers)
return ['Set cookies!']
app = ZappaWSGIMiddleware(set_cookies)
environ = create_wsgi_request(event, script_name='http://zappa.com/',
trailing_slash=False)
response = Response.from_app(app, environ)
# Filter the headers for Set-Cookie header
zappa_cookie = [x[1] for x in response.headers if x[0] == 'Set-Cookie']
self.assertEqual(len(zappa_cookie), 1)
zappa_cookie0 = zappa_cookie[0]
self.assertTrue(zappa_cookie0.startswith('zappa='))
print("2: Changing 1 cookie")
event = {
u'method': u'POST',
u'params': {u'parameter_1': u'set_cookie'},
u'body': u'foo=qwe',
u'headers': {
u'Cookie': zappa_cookie0
},
u'query': {}
}
environ = create_wsgi_request(event, script_name='http://zappa.com/',
trailing_slash=False)
def change_cookie(environ, start_response):
status = '200 OK'
print 'environ', environ
response_headers = [('Set-Cookie', 'foo=new_value')]
start_response(status, response_headers)
return ['Set cookies!']
app = ZappaWSGIMiddleware(change_cookie)
response = Response.from_app(app, environ)
# Filter the headers for Set-Cookie header
zappa_cookie = [x[1] for x in response.headers if x[0] == 'Set-Cookie']
self.assertEqual(len(zappa_cookie), 1)
zappa_cookie1 = zappa_cookie[0]
self.assertTrue(zappa_cookie1.startswith('zappa='))
zdict = parse_cookie(zappa_cookie1)
print 'zdict', zdict
zdict2 = json.loads(base58.b58decode(zdict['zappa']))
print 'zdict2', zdict2
self.assertEqual(len(zdict2), 3)
self.assertEqual(zdict2['foo'], 'new_value')
self.assertEqual(zdict2['bar'], '456')
self.assertEqual(zdict2['baz'], '789')
# We have changed foo, so they should be different
self.assertNotEqual(zappa_cookie0, zappa_cookie1)
print("3: Reading the cookies")
event['headers']['Cookie'] = zappa_cookie1
def read_cookies(environ, start_response):
status = '200 OK'
print 'environ', environ
response_headers = []
start_response(status, response_headers)
return [environ['HTTP_COOKIE']]
app = ZappaWSGIMiddleware(read_cookies)
environ = create_wsgi_request(event, script_name='http://zappa.com/',
trailing_slash=False)
response = Response.from_app(app, environ)
print "response", response
# Filter the headers for Set-Cookie header
zappa_cookie = [x[1] for x in response.headers if x[0] == 'Set-Cookie']
self.assertEqual(len(zappa_cookie), 1)
zappa_cookie1 = zappa_cookie[0]
self.assertTrue(zappa_cookie1.startswith('zappa='))
zdict = parse_cookie(zappa_cookie1)
print 'zdict', zdict
cookies = json.loads(base58.b58decode(zdict['zappa']))
self.assertEqual(cookies['foo'], 'new_value')
self.assertEqual(cookies['bar'], '456')
#.........这里部分代码省略.........