本文整理汇总了Python中webob.Request.response方法的典型用法代码示例。如果您正苦于以下问题:Python Request.response方法的具体用法?Python Request.response怎么用?Python Request.response使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类webob.Request
的用法示例。
在下文中一共展示了Request.response方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _adapter
# 需要导入模块: from webob import Request [as 别名]
# 或者: from webob.Request import response [as 别名]
def _adapter(environ, start_response):
def _attach(resp):
req.response = resp
req = Request(environ)
req.response = exc.HTTPNotImplemented()
task = func(req).bimap(
build_error_response,
build_success_response
)
task.fork(_attach, _attach)
return req.response(environ, start_response)
示例2: dispatch_wsgi
# 需要导入模块: from webob import Request [as 别名]
# 或者: from webob.Request import response [as 别名]
def dispatch_wsgi(self, environ, start_response):
"""
Dispatches a WSGI request.
:param environ: WSGI request environment.
:param start_response: WSGI response callback
:returns: A valid WSGI response content.
"""
req = Request(environ)
req.response = Response()
try:
resp = self.dispatch_request(req)
except HTTPException as e:
resp = e
if inspect.isgenerator(resp):
resp = Response(app_iter=resp)
elif resp is None:
resp = req.response
if isinstance(resp, text_type):
resp = bytes_(resp, req.charset)
if isinstance(resp, bytes):
body = resp
resp = req.response
resp.write(body)
if resp is not req.response:
resp = req.response.merge_cookies(resp)
return resp(environ, start_response)
示例3: replacement_app
# 需要导入模块: from webob import Request [as 别名]
# 或者: from webob.Request import response [as 别名]
def replacement_app(environ, start_response):
req = Request(environ)
res = WebResponse(request=req)
req.response = res
result = func(req)
add_response = None
if result is None:
result = res
elif isinstance(result, Response):
# All good
add_response = res
elif isinstance(result, basestring):
res.body = result
result = res
else:
# WSGI application...
add_response = res
if (add_response is not None
and 'set-cookie' in add_response.headers):
def repl_start_response(status, headers, exc_info=None):
headers.extend(add_response.getall('Set-Cookie'))
return start_response(status, headers, exc_info)
else:
repl_start_response = start_response
return result(environ, repl_start_response)
示例4: __call__
# 需要导入模块: from webob import Request [as 别名]
# 或者: from webob.Request import response [as 别名]
def __call__(self, env, start_response):
self.logger.debug("In cs_auth middleware")
identity = None # the identity we are trying to populate
# Handle s3 connections first because s3 has a unique format/use for the 'HTTP_X_AUTH_TOKEN'.
s3 = env.get("HTTP_AUTHORIZATION", None)
if s3 and s3.startswith("AWS"):
s3_apikey, s3_signature = s3.split(" ")[1].rsplit(":", 1)[:]
if s3_apikey and s3_signature:
# check if we have cached data to validate this request instead of hitting cloudstack.
memcache_client = cache_from_env(env)
memcache_result = memcache_client.get("cs_s3_auth/%s" % s3_apikey)
valid_cache = False
data = None
if memcache_result and self.cs_cache_timeout > 0:
expires, data = memcache_result
if expires > time():
valid_cache = True
if valid_cache:
self.logger.debug("Validating the S3 request via the cached identity")
s3_token = base64.urlsafe_b64decode(env.get("HTTP_X_AUTH_TOKEN", "")).encode("utf-8")
if s3_signature == base64.b64encode(
hmac.new(data.get("secret", ""), s3_token, hashlib.sha1).digest()
):
self.logger.debug("Using cached S3 identity")
identity = data.get("identity", None)
token = identity.get(
"token", None
) # this just simplifies the logical flow, its not really used in this case.
# The swift3 middleware sets env['PATH_INFO'] to '/v1/<aws_secret_key>', we need to map it to the cloudstack account.
if self.reseller_prefix != "":
env["PATH_INFO"] = env["PATH_INFO"].replace(
s3_apikey, "%s_%s" % (self.reseller_prefix, identity.get("account", ""))
)
else:
env["PATH_INFO"] = env["PATH_INFO"].replace(s3_apikey, "%s" % (identity.get("account", "")))
else: # hit cloudstack and populate memcached if valid request
user_list = self.cs_api.request(dict({"command": "listUsers"}))
if user_list:
for user in user_list["user"]:
if user["state"] == "enabled" and "apikey" in user and user["apikey"] == s3_apikey:
# At this point we have found a matching user. Authenticate them.
s3_token = base64.urlsafe_b64decode(env.get("HTTP_X_AUTH_TOKEN", "")).encode("utf-8")
if s3_signature == base64.b64encode(
hmac.new(user["secretkey"], s3_token, hashlib.sha1).digest()
):
expires = time() + self.cs_cache_timeout
timeout = self.cs_cache_timeout
token = hashlib.sha224("%s%s" % (user["secretkey"], user["apikey"])).hexdigest()
if self.reseller_prefix != "":
account_url = "%s/v1/%s_%s" % (
self.storage_url,
self.reseller_prefix,
quote(user["account"]),
)
else:
account_url = "%s/v1/%s" % (self.storage_url, quote(user["account"]))
identity = dict(
{
"username": user["username"],
"account": user["account"],
"token": token,
"account_url": account_url,
"domain": dict({"id": user["domainid"], "name": user["domain"]}),
"roles": [self.cs_roles[user["accounttype"]], user["account"]],
"expires": expires,
}
)
self.logger.debug("Creating S3 identity")
# The swift3 middleware sets env['PATH_INFO'] to '/v1/<aws_secret_key>', we need to map it to the cloudstack account.
if self.reseller_prefix != "":
env["PATH_INFO"] = env["PATH_INFO"].replace(
s3_apikey, "%s_%s" % (self.reseller_prefix, user["account"])
)
else:
env["PATH_INFO"] = env["PATH_INFO"].replace(s3_apikey, "%s" % (user["account"]))
memcache_client = cache_from_env(env)
if memcache_client:
memcache_client.set(
"cs_s3_auth/%s" % s3_apikey,
(expires, dict({"secret": user["secretkey"], "identity": identity})),
timeout=timeout,
)
memcache_client.set("cs_token/%s" % token, (expires, identity), timeout=timeout)
else:
self.logger.debug("S3 credentials are not valid")
env["swift.authorize"] = self.denied_response
return self.app(env, start_response)
else:
self.logger.debug("Errors: %s" % self.cs_api.errors)
env["swift.authorize"] = self.denied_response
return self.app(env, start_response)
else:
self.logger.debug("Invalid credential format")
env["swift.authorize"] = self.denied_response
return self.app(env, start_response)
# If it is not an S3 call, handle the request for authenication, otherwise, use the token.
req = Request(env)
#.........这里部分代码省略.........
示例5: __call__
# 需要导入模块: from webob import Request [as 别名]
# 或者: from webob.Request import response [as 别名]
def __call__(self, env, start_response):
self.logger.debug('In mauth middleware')
identity = None # the identity we are trying to populate
# Handle s3 connections first because s3 has a unique format/use for the 'HTTP_X_AUTH_TOKEN'.
s3 = env.get('HTTP_AUTHORIZATION', None)
if s3 and s3.startswith('AWS'):
s3_apikey, s3_signature = s3.split(' ')[1].rsplit(':', 1)[:]
if s3_apikey and s3_signature:
# check if we have cached data to validate this request instead of hitting cloudstack.
memcache_client = cache_from_env(env)
memcache_result = memcache_client.get('mauth_s3_apikey/%s' % s3_apikey)
valid_cache = False
data = None
if memcache_result and self.cache_timeout > 0:
expires, data = memcache_result
if expires > time():
valid_cache = True
if valid_cache:
self.logger.debug('Validating the S3 request via the cached identity')
s3_token = base64.urlsafe_b64decode(env.get('HTTP_X_AUTH_TOKEN', '')).encode("utf-8")
if s3_signature == base64.b64encode(hmac.new(data.get('secret', ''), s3_token, hashlib.sha1).digest()):
self.logger.debug('Using cached S3 identity')
identity = data.get('identity', None)
# The swift3 middleware sets env['PATH_INFO'] to '/v1/<aws_secret_key>', we need to map it to the cloudstack account.
if self.reseller_prefix != '':
env['PATH_INFO'] = env['PATH_INFO'].replace(s3_apikey, '%s_%s' % (self.reseller_prefix, identity.get('account', '')))
else:
env['PATH_INFO'] = env['PATH_INFO'].replace(s3_apikey, '%s' % (identity.get('account', '')))
else: # hit cloudstack and populate memcached if valid request
identity, secret_key = self.get_s3_identity(env, start_response, s3_apikey, s3_signature);
if identity:
if self.reseller_prefix != '':
account_url = '%s/v1/%s_%s' % (self.storage_url, self.reseller_prefix, quote(identity.get('account', '')))
else:
account_url = '%s/v1/%s' % (self.storage_url, quote(identity.get('account', '')))
identity['account_url'] = account_url
# The swift3 middleware sets env['PATH_INFO'] to '/v1/<aws_secret_key>', we need to map it to the cloudstack account.
if self.reseller_prefix != '':
env['PATH_INFO'] = env['PATH_INFO'].replace(s3_apikey, '%s_%s' % (self.reseller_prefix, identity.get('account', '')))
else:
env['PATH_INFO'] = env['PATH_INFO'].replace(s3_apikey, '%s' % (identity.get('account', '')))
memcache_client = cache_from_env(env)
if memcache_client:
memcache_client.set('mauth_s3_apikey/%s' % s3_apikey, (expires, dict({'secret':secret_key, 'identity':identity})), timeout=self.cache_timeout)
memcache_client.set('mauth_token/%s' % token, (expires, identity), timeout=self.cache_timeout)
else:
self.logger.debug('No identity for this request')
env['swift.authorize'] = self.denied_response
return self.app(env, start_response)
else:
self.logger.debug('Invalid credential format')
env['swift.authorize'] = self.denied_response
return self.app(env, start_response)
# If it is not an S3 call, handle the request for authenication, otherwise, use the token.
req = Request(env)
if not s3:
try:
auth_url_piece, rest_of_url = split_path(req.path_info, minsegs=1, maxsegs=2, rest_with_last=True)
except ValueError:
return HTTPNotFound(request=req)
# Check if the request is for authentication (to get a token).
if auth_url_piece in (self.auth_prefix, 'v1.0'): # valid auth urls
auth_user = env.get('HTTP_X_AUTH_USER', None)
auth_key = env.get('HTTP_X_AUTH_KEY', None)
if auth_user and auth_key:
# check if we have this user and key cached.
memcache_client = cache_from_env(env)
memcache_result = memcache_client.get('mauth_creds/%s/%s' % (auth_user, auth_key))
valid_cache = False
data = None
if memcache_result and self.cache_timeout > 0 and env.get('HTTP_X_AUTH_TTL', 1) > 0:
expires, data = memcache_result
if expires > time():
valid_cache = True
if valid_cache:
self.logger.debug('Using cached identity via creds')
identity = data
self.logger.debug("Using identity: %r" % (identity))
req.response = Response(request=req,
headers={'x-auth-token':identity.get('token', None),
'x-storage-token':identity.get('token', None),
'x-storage-url':identity.get('account_url', None)})
return req.response(env, start_response)
else: # hit cloudstack for the details.
self.logger.debug("Calling get_identity...")
identity = self.get_identity(env, start_response, auth_user, auth_key)
if identity:
if self.reseller_prefix != '':
account_url = '%s/v1/%s_%s' % (self.storage_url, self.reseller_prefix, quote(identity.get('account', '')))
else:
account_url = '%s/v1/%s' % (self.storage_url, quote(identity.get('account', '')))
identity['account_url'] = account_url
#.........这里部分代码省略.........
示例6: __call__
# 需要导入模块: from webob import Request [as 别名]
# 或者: from webob.Request import response [as 别名]
def __call__(self, env, start_response):
self.logger.debug('In cs_auth middleware')
identity = None # the identity we are trying to populate
# Handle s3 connections first because s3 has a unique format/use for the 'HTTP_X_AUTH_TOKEN'.
s3 = env.get('HTTP_AUTHORIZATION', None)
if s3 and s3.startswith('AWS'):
self.logger.debug('A s3 request: %s' % s3)
s3_apikey, s3_signature = s3.split(' ')[1].rsplit(':', 1)[:]
if s3_apikey and s3_signature:
# check if we have cached data to validate this request instead of hitting cloudstack.
memcache_client = cache_from_env(env)
memcache_result = memcache_client.get('cs_s3_auth/%s' % s3_apikey)
valid_cache = False
data = None
if memcache_result and self.cs_cache_timeout > 0:
expires, data = memcache_result
if expires > time():
valid_cache = True
if valid_cache:
self.logger.debug('Validating the S3 request via the cached identity')
s3_token = base64.urlsafe_b64decode(env.get('HTTP_X_AUTH_TOKEN', '')).encode("utf-8")
self.logger.debug('s3token: %s' % s3_token)
self.logger.debug('Secret is: %s' % data.get('secret', 'NO SECRET FOUND'))
self.logger.debug('s3_signature: %s' % s3_signature)
self.logger.debug('calculated signature: %s' % base64.b64encode(hmac.new(data.get('secret', ''), s3_token, hashlib.sha1).digest()))
if s3_signature == base64.b64encode(hmac.new(data.get('secret', ''), s3_token, hashlib.sha1).digest()):
self.logger.debug('Using cached S3 identity')
identity = data.get('identity', None)
token = identity.get('token', None) # this just simplifies the logical flow, its not really used in this case.
# The swift3 middleware sets env['PATH_INFO'] to '/v1/<aws_secret_key>', we need to map it to the cloudstack account.
if self.reseller_prefix != '':
env['PATH_INFO'] = env['PATH_INFO'].replace(s3_apikey, '%s_%s' % (self.reseller_prefix, identity.get('account', '')))
else:
env['PATH_INFO'] = env['PATH_INFO'].replace(s3_apikey, '%s' % (identity.get('account', '')))
else: # hit cloudstack and populate memcached if valid request, this will fail if number of users is greater than max pagesize in cs.
user_response = self.cs_api.request(dict({'command':'getUser', 'userapikey': s3_apikey}))
self.logger.debug('cloudstack response: %s' % user_response)
if user_response:
if 'secretkey' in user_response['user'].keys(): # TODO: This is really not needed...
user = user_response['user']
if 'apikey' in user and user['apikey'] == s3_apikey:
self.logger.debug('Found user, trying to authenticate')
# At this point we have found a matching user. Authenticate them.
s3_token = base64.urlsafe_b64decode(env.get('HTTP_X_AUTH_TOKEN', '')).encode("utf-8")
if s3_signature == base64.b64encode(hmac.new(user['secretkey'], s3_token, hashlib.sha1).digest()):
self.logger.debug('Creating token')
expires = time() + self.cs_cache_timeout
timeout = self.cs_cache_timeout
token = hashlib.sha224('%s%s' % (user['secretkey'], user['apikey'])).hexdigest()
if self.reseller_prefix != '':
account_url = '%s/v1/%s_%s' % (self.storage_url, self.reseller_prefix, quote(user['account']))
else:
account_url = '%s/v1/%s' % (self.storage_url, quote(user['account']))
identity = dict({
'username':user['username'],
'account':user['account'],
'accountid':user['accountid'],
'token':token,
'account_url':account_url,
'domain':dict({'id':user['domainid'], 'name':user['domain']}),
'roles':[self.cs_roles[user['accounttype']], user['account']],
'expires':expires
})
self.logger.debug('Creating S3 identity')
# The swift3 middleware sets env['PATH_INFO'] to '/v1/<aws_secret_key>', we need to map it to the cloudstack account.
if self.reseller_prefix != '':
env['PATH_INFO'] = env['PATH_INFO'].replace(s3_apikey, '%s_%s' % (self.reseller_prefix, user['account']))
else:
env['PATH_INFO'] = env['PATH_INFO'].replace(s3_apikey, '%s' % (user['account']))
memcache_client = cache_from_env(env)
if memcache_client:
memcache_client.set('cs_s3_auth/%s' % s3_apikey, (expires, dict({'secret':user['secretkey'], 'identity':identity})), timeout=timeout)
memcache_client.set('cs_token/%s' % token, (expires, identity), timeout=timeout)
else:
self.logger.debug('S3 credentials are not valid')
env['swift.authorize'] = self.denied_response
return self.app(env, start_response)
else:
self.logger.debug('Errors: %s' % self.cs_api.errors)
env['swift.authorize'] = self.denied_response
return self.app(env, start_response)
else:
self.logger.debug('Invalid credential format')
env['swift.authorize'] = self.denied_response
return self.app(env, start_response)
# If it is not an S3 call, handle the request for authenication, otherwise, use the token.
req = Request(env)
if not s3:
try:
auth_url_piece, rest_of_url = split_path(req.path_info, minsegs=1, maxsegs=2, rest_with_last=True)
except ValueError:
return HTTPNotFound(request=req)
# Check if the request is for authentication (to get a token).
if auth_url_piece in ('auth', 'v1.0'): # valid auth urls
auth_account_user = env.get('HTTP_X_AUTH_USER', None)
auth_key = env.get('HTTP_X_AUTH_KEY', None)
#.........这里部分代码省略.........