无论我们看openstack的哪个模块,在很多调用的函数参数中总能看到context的身影,context顾名思义是上下文,在调用时除了self,恐怕见到最多的是这个词,
很多时候并不知道context是什么,更不知道怎么用,从nova进去看看:
以/v2 rest 为例,
[composite:openstack_compute_api_v2]
use = call:nova.api.auth:pipeline_factory
noauth = compute_req_id faultwrap sizelimit noauth ratelimit osapi_compute_app_v2
keystone = compute_req_id faultwrap sizelimit authtoken
keystonecontext ratelimit osapi_compute_app_v2
keystone_nolimit = compute_req_id faultwrap sizelimit authtoken
keystonecontext osapi_compute_app_v2
这个keystonecontext作为一个middleware,定义在:
[filter:keystonecontext]
paste.filter_factory = nova.api.auth:NovaKeystoneContext.factory
作为一个middleware继承自wsgi.Middleware
class NovaKeystoneContext(wsgi.Middleware):
和其他middle一样,NovaKeystoneContext实现__call__函数:
ctx = context.RequestContext(user_id,
project_id,
user_name=user_name,
project_name=project_name,
roles=roles,
auth_token=auth_token,
remote_address=remote_address, #可以在request的header中指定,或者client时生成
service_catalog=service_catalog,
request_id=req_id)
req.environ['nova.context'] = ctx
return self.application
在controller中,执行具体相应时候,参数中有req,这时要使用时从req中取出即可
其他的模块都有类似的,比如keystone中:
[pipeline:admin_api]
# The last item in this pipeline must be admin_service or an equivalent
# application. It cannot be a filter.
pipeline = sizelimit url_normalize build_auth_context token_auth admin_token_auth xml_body_v2 json_body ec2_extension s3_extension crud_extension admin_service
[filter:build_auth_context]
paste.filter_factory = keystone.middleware:AuthContextMiddleware.factory
在process_request中:
request.environ[authorization.AUTH_CONTEXT_ENV] = auth_context
还有neutron中:
[composite:neutronapi_v2_0]
use = call:neutron.auth:pipeline_factory
noauth = request_id catch_errors extensions neutronapiapp_v2_0
keystone = request_id catch_errors authtoken keystonecontext
extensions neutronapiapp_v2_0
[filter:keystonecontext]
paste.filter_factory = neutron.auth:NeutronKeystoneContext.factory
ctx = context.Context(user_id, tenant_id, roles=roles,
user_name=user_name, tenant_name=tenant_name,
request_id=req_id, auth_token=auth_token)
# Inject the context...
req.environ['neutron.context'] = ctx
return self.application
和nova一样,在controller中可以使用
知道context是什么,有什么,再看起来就更明白了