blpapi.ProviderSession
- class blpapi.ProviderSession(options=None, eventHandler=None, eventDispatcher=None)
Bases:
AbstractSessionThis class provides a session that can be used for providing services.
It inherits from
AbstractSession. In addition to theAbstractSessionfunctionality aProviderSessionprovides the following functions to applications.A provider can register to provide services using
registerService(). Before registering to provide a service the provider must have established its identity. Then the provider can create topics and publish events on topics. It also can get requests from the event queue and send back responses.After users have registered a service they will start receiving subscription requests (
TopicSubscribedmessage inTOPIC_STATUS) for topics which belong to the service. If the resolver has specifiedsubServiceCodefor topics inPermissionResponse, then only providers who have activated thesubServiceCodewill get the subscription request. Where multiple providers have registered the same service and sub-service code (if any), the provider that registered the highest priority for the sub-service code will receive subscription requests; if multiple providers have registered the same sub-service code with the same priority (or the resolver did not set a sub-service code for the subscription), the subscription request will be routed to one of the providers with the highest service priority.- AUTO_REGISTER_SERVICES = 1
- DONT_REGISTER_SERVICES = 0
- __init__(options=None, eventHandler=None, eventDispatcher=None)
Constructor.
- Parameters
options – Options used to construct the sessions
eventHandler – Handler for the events generated by this session
eventDispatcher – Dispatcher for the events generated by this session
- Raises
InvalidArgumentException – If
eventHandlerisNoneand theeventDispatcheris notNone
Construct a Session using the optionally specified ‘options’, the optionally specified ‘eventHandler’ and the optionally specified ‘eventDispatcher’. See
SessionOptionsfor details on what can be specified in theoptions.If
eventHandleris notNonethen this Session will operate in asynchronous mode, otherwise the Session will operate in synchronous mode. If supplied,eventHandleris a callable object that takes two arguments: received event and related session.If
eventDispatcherisNonethen the Session will create a defaultEventDispatcherfor this Session which will use a single thread for dispatching events. For more control over event dispatching a specific instance ofEventDispatchercan be supplied. This can be used to share a singleEventDispatcheramongst multiple Session objects.If an
eventDispatcheris supplied which uses more than one thread the Session will ensure that events which should be ordered are passed to callbacks in a correct order. For example, partial response to a request or updates to a single subscription.Each
EventDispatcheruses its own thread or pool of threads so if you want to ensure that a session which receives very large messages and takes a long time to process them does not delay a session that receives small messages and processes each one very quickly then give each one a separateEventDispatcher.
- activateSubServiceCodeRange(serviceName, begin, end, priority)
- Parameters
Register to receive, with the specified
priority, subscriptions for the specifiedservicethat the resolver has mapped to a service code between the specifiedbeginand the specifiedendvalues, inclusive. Numerically greater values ofpriorityindicate higher priorities.Note
The behavior of this function is undefined unless
servicehas already been successfully registered,0 <= begin <= end < (1 << 24), andpriorityis non-negative.- Return type
- cancel(correlationId)
Cancel request(s) with a single
correlationIdor a list.- Parameters
correlationId (
Union[CorrelationId,Sequence[CorrelationId]]) – Correlation id(s) associated with the request(s) to cancel
For all specified
correlationIdvalues that identify an ongoing request cancel that request.Once this call returns the specified
correlationIdwill not be seen in any subsequentMessageobtained from aMessageIteratorby callingnext(). However, anyMessagecurrently pointed to by aMessageIteratorwhencancel()is called is not affected even if it has the specifiedcorrelationId. Also anyMessagewhere a reference has been retained by the application may still contain thecorrelationId. For these reasons, although technically an application is free to re-usecorrelationIdas soon as this method returns it is preferable not to aggressively re-use correlation IDs, particularly with an asynchronous Session.- Return type
- createIdentity()
Create an
Identitywhich is valid but has not been authorized.- Returns
Identity which is valid but has not been authorized
- Return type
- createServiceStatusTopic(service)
Create a
ServiceStatusTopicwhich is to be used to provide service status.- Parameters
service – Service for which to create the topic
- Returns
A service status topic
On success invoking
isValid()on the returnedTopicwill returnFalse.
- createTopics(topicList, resolveMode=0, identity=None)
Create the topics in the specified
topicList.- Parameters
topicList – List of topics to create
resolveMode – Mode to use for topic resolution
identity – Identity to use for authorization
Create the topics in the specified
topicList, which must be an object of typeTopicList, and updatetopicListwith the results of the creation process. If service needs to be registered,identityshould be supplied. Once a call to this function returns, each entry in thetopicListwill have been updated with a new topic creation status.Before
createTopics()returns one or moreRESOLUTION_STATUSevents, zero or moreSERVICE_STATUSevents and one or moreTOPIC_STATUSevents are generated. If this is an asynchronousProviderSessionthen theseEvents may be processed by the registeredeventHandlerbeforecreateTopics()has returned.When
identityis not provided, the session identity will be used if it has been authorized.
- createTopicsAsync(topicList, resolveMode=0, identity=None)
Create the topics in the specified
topicList.- Parameters
topicList – List of topics to create
resolveMode – Mode to use for topic resolution
identity – Identity to use for authorization
Create the topics in the specified
topicList, which must be an object of typeTopicList, and updatetopicListwith the results of the creation process. If service needs to be registered,identityshould be supplied. Once a call to this function returns, each entry in thetopicListwill have been updated with a new topic creation status.Before
createTopics()returns one or moreRESOLUTION_STATUSevents, zero or moreSERVICE_STATUSevents and one or moreTOPIC_STATUSevents are generated. If this is an asynchronousProviderSessionthen theseEvents may be processed by the registeredeventHandlerbeforecreateTopics()has returned.When
identityis not provided, the session identity will be used if it has been authorized.
- deactivateSubServiceCodeRange(serviceName, begin, end)
- Parameters
De-register to receive subscriptions for the specified
servicethat the resolver has mapped to a service code between the specifiedbeginand the specifiedendvalues, inclusive.Note
The behavior of this function is undefined unless
servicehas already been successfully registered and0 <= begin <= end < (1 << 24).- Return type
- deleteTopic(topic)
Remove one reference from the specified ‘topic’.
- Parameters
topic (
Topic) – Topic to remove the reference from
If this function has been called the same number of times that
topicwas created bycreateTopics, thentopicis deleted: aTopicDeletedmessage is delivered, preceded byTopicUnsubscribedandTopicDeactivatediftopicwas subscribed.Note
The behavior of this function is undefined if
topichas already been deleted the same number of times that it has been created. Further, the behavior is undefined if a provider attempts to publish a message on a deleted topic.- Return type
- deleteTopics(topics)
Delete each topic in the specified
topicscontainer.- Parameters
deleteTopics – Topics to delete
See
deleteTopic()above for additional details.- Return type
- deregisterService(serviceName)
De-register the service, including all registered parts.
- Parameters
serviceName (
str) – Service to de-register- Return type
- Returns
Falseif the service is not registered nor in pending registration,Trueotherwise.
The identity in the service registration is reused to verify permissions for deregistration. If the service is in pending registration, cancel the pending registration. If the service is registered, send a deregistration request; generate
TOPIC_STATUSevents containing aTopicUnsubscribedmessage for each subscribed topic, aTopicDeactivatedmessage for each active topic and aTopicDeletedfor each created topic; generate~Event.REQUEST_STATUSevents containing aRequestFailuremessage for each pending incoming request; and generate aSERVICE_STATUSevent containing aServiceDeregisteredmessage. All published events on topics created on this service will be ignored after this method returns.
- flushPublishedEvents(timeoutMsecs)
Wait at most
timeoutMsecsmilliseconds for all the published events to be sent through the underlying channel.- Parameters
timeoutMsecs (
int) – Timeout threshold in milliseconds- Return type
- Returns
Trueif all the published events have been sent,Falseotherwise
The method returns either as soon as all the published events have been sent out or when it has waited
timeoutMsecsmilliseconds. The behavior is undefined unless the specifiedtimeoutMsecsis a non-negative value. WhentimeoutMsecsis0, the method checks if all the published events have been sent and returns without waiting.
- generateAuthorizedIdentity(authOptions, correlationId=None)
Generates an authorized
Identitywith the specifiedauthOptionsandcorrelationId.- Parameters
- Returns
Identifies the aforementioned events and the generated
Identity.- Return type
If this is an asynchronous session then an
Eventmay be delivered to the registeredEventHandlerbeforegenerateAuthorizedIdentity()has returned.One or more
Event.AUTHORIZATION_STATUSevents, zero or moreEvent.TOKEN_STATUSevents, and zero or moreEvent.SERVICE_STATUSevents are generated.The behavior is undefined if either
authOptionsorcorrelationIdisNone.
- generateToken(correlationId=None, eventQueue=None, authId=None, ipAddress=None)
Generate a token to be used for authorization.
- Parameters
correlationId – Correlation id to be associated with the request
eventQueue – Event queue on which to receive Events related to this request
authId – The id used for authentication
ipAddress – IP of the machine used for authentication
- Returns
The correlation id used to identify the Events generated as a result of this call
- Return type
- Raises
InvalidArgumentException – If the authentication options in
SessionOptionsor the arguments to the function are invalid.
The
authIdandipAddressmust be provided together and can only be provided if the authentication mode isMANUAL.
- getAuthorizedIdentity(correlationId=None)
Returns the authorized
Identityassociated withcorrelationId. IfcorrelationIdis not given, returns the session identity.- Parameters
correlationId (
Optional[CorrelationId]) – Optional. Associated with anIdentity.- Returns
the
Identityassociated withcorrelationId.- Return type
- Raises
NotFoundException – If there is no
Identityassociated withcorrelationId, if the associatedIdentityis not authorized, or ifcorrelationIdis not given and the session identity is not authorized.
- getService(serviceName)
Return a
Serviceobject representing the service.- Parameters
serviceName (
str) – Name of the service to retrieve- Returns
Service identified by the service name
- Return type
- Raises
InvalidStateException – If the service identified by the specified
serviceNameis not open already
The
serviceNamemust contain a fully qualified service name. That is, it must be of the form//<namespace>/<service-name>.
- getTopic(message)
Find a previously created
Topicbased on themessage.- Parameters
message – Message to get the topic from
- Returns
The topic the message was published on
The
messagemust be one of the following types:TopicCreated,TopicActivated,TopicDeactivated,TopicSubscribed,TopicUnsubscribed,TopicRecap. If themessageis not valid then invokingisValid()on the returnedTopicwill returnFalse.
- nextEvent(timeout=0)
- Parameters
timeout (
int) – Timeout threshold in milliseconds- Return type
- Returns
Next available event for this session
- Raises
InvalidStateException – If invoked on a session created in asynchronous mode
If there is no
Eventavailable this will block for up to the specifiedtimeoutmilliseconds for anEventto arrive. A value of0fortimeout(the default) indicatesnextEvent()should not timeout and will not return until the nextEventis available.If
nextEvent()returns due to a timeout it will return an event of typeTIMEOUT.
- openService(serviceName)
Open the service identified by the specified
serviceName.- Parameters
serviceName (
str) – Name of the service- Return type
- Returns
Trueif the service is opened successfully,Falseotherwise.
Attempt to open the service identified by the specified
serviceNameand block until the service is either opened successfully or has failed to be opened. ReturnTrueif the service is opened successfully andFalseif the service cannot be successfully opened.The
serviceNamemust contain a fully qualified service name. That is, it must be of the form//<namespace>/<service-name>.Before
openService()returns aSERVICE_STATUSEventis generated. If this is an asynchronous Session then thisEventmay be processed by the registeredeventHandlerbeforeopenService()has returned.
- openServiceAsync(serviceName, correlationId=None)
Begin the process to open the service and return immediately.
- Parameters
serviceName (
str) – Name of the servicecorrelationId (
Optional[CorrelationId]) – Correlation id to associate with events generated as a result of this call
- Returns
The correlation id used to identify the Events generated as a result of this call
- Return type
Begin the process to open the service identified by the specified
serviceNameand return immediately. The optional specifiedcorrelationIdis used to trackEvents generated as a result of this call.The
serviceNamemust contain a fully qualified service name. That is, it must be of the form//<namespace>/<service-name>.The application must monitor events for a
SERVICE_STATUSEventwhich will be generated once the service has been successfully opened or the opening has failed.
- publish(event)
Publish the specified
event.
- registerService(uri, identity=None, options=None)
Attempt to register the service and block until it is done.
- Parameters
uri – Name of the service
identity – Identity used to verify permissions to provide the service being registered
options – Options used to register the service
- Returns
Trueif the service registered successfully, elseFalse
Attempt to register the service identified by the specified
uriand block until the service is either registered successfully or has failed to be registered. The optionally specifiedidentityis used to verify permissions to provide the service being registered. The optionally specifiedoptionsis used to specify the group ID and service priority of the service being registered.The
urimust begin with a full qualified service name. That is it must begin with//<namespace>/<service-name>[/]. Any portion of theuriafter the service name is ignored.Before
registerService()returns aSERVICE_STATUSEventis generated. If this is an asynchronousProviderSessionthen thisEventmay be processed by the registeredEventbeforeregisterService()has returned.When
identityis not provided, the session identity will be used if it has been authorized.
- registerServiceAsync(uri, identity=None, correlationId=None, options=None)
Begin the process of registering the service immediately.
- Parameters
uri – Name of the service
identity – Identity used to verify permissions to provide the service being registered
correlationId – Correlation id to associate with this operation
options – Options used to register the service
- Returns
Correlation id associated with events generated by this operation
Begin the process of registering the service identified by the specified
uriand return immediately. The optionally specifiedidentityis used to verify permissions to provide the service being registered. The optionally specifiedcorrelationIdis used to trackEvents generated as a result of this call. The actualcorrelationIdthat will identifyEvents generated as a result of this call is returned. The optionally specifiedoptionsis used to specify the group ID and service priority of the service being registered.The
urimust begin with a full qualified service name. That is it must begin with//<namespace>/<service-name>[/]. Any portion of theuriafter the service name is ignored.The application must monitor events for a
SERVICE_STATUSEventwhich will be generated once the service has been successfully registered or registration has failed.When
identityis not provided, the session identity will be used if it has been authorized.
- resolve(resolutionList, resolveMode=0, identity=None)
Resolve the topics in the specified
resolutionList.- Parameters
resolutionList – List of topics to resolve
resolveMode – Mode to resolve in
identity – Identity used for authorization
Resolve the topics in the specified
resolutionList, which must be an object of typeResolutionList, and update theresolutionListwith the results of the resolution process. If the specifiedresolveModeisDONT_REGISTER_SERVICES(the default) then all the services referenced in the topics in theresolutionListmust already have been registered usingregisterService(). IfresolveModeisAUTO_REGISTER_SERVICESthen the specifiedidentityshould be supplied andProviderSessionwill automatically attempt to register any services reference in the topics in theresolutionListthat have not already been registered. Onceresolve()returns each entry in theresolutionListwill have been updated with a new status.Before
resolve()returns one or moreRESOLUTION_STATUSevents and, ifresolveModeisAUTO_REGISTER_SERVICES, zero or moreSERVICE_STATUSevents are generated. If this is an asynchronousProviderSessionthen theseEvents may be processed by the registeredeventHandlerbeforeresolve()has returned.When
identityis not provided, the session identity will be used if it has been authorized.
- resolveAsync(resolutionList, resolveMode=0, identity=None)
Begin the resolution of the topics in the specified list.
- Parameters
resolutionList – List of topics to resolve
resolveMode – Mode to resolve in
identity – Identity used for authorization
Begin the resolution of the topics in the specified
resolutionList, which must be an object of typeResolutionList. If the specifiedresolveModeisDONT_REGISTER_SERVICES(the default) then all the services referenced in the topics in theresolutionListmust already have been registered usingregisterService(). IfresolveModeisAUTO_REGISTER_SERVICESthen the specifiedidentityshould be supplied andProviderSessionwill automatically attempt to register any services reference in the topics in theresolutionListthat have not already been registered.One or more
RESOLUTION_STATUSevents will be delivered with the results of the resolution. These events may be generated before or afterresolveAsync()returns. IfAUTO_REGISTER_SERVICESis specifiedSERVICE_STATUSevents may also be generated before or afterresolveAsync()returns.When
identityis not provided, the session identity will be used if it has been authorized.
- sendAuthorizationRequest(request, identity, correlationId=None, eventQueue=None)
Send the specified
authorizationRequest.- Parameters
request – Authorization request to send
identity – Identity to update with the results
correlationId – Correlation id to associate with the request
eventQueue – Event queue on which the events related to this request will arrive
- Returns
The correlation id used to identify the Events generated as a result of this call
- Return type
Send the specified
authorizationRequestand update the specifiedidentitywith the results. If the optionally specifiedcorrelationIdis supplied, it is used; otherwise create aCorrelationId. The actualCorrelationIdused is returned. If the optionally specifiedeventQueueis supplied allEvents relating to thisRequestwill arrive on thatEventQueue.The underlying user information must remain valid until the Request has completed successfully or failed.
A successful request will generate zero or more
PARTIAL_RESPONSEMessages followed by exactly oneRESPONSEMessage. Once the finalRESPONSEMessagehas been received the specifiedidentitywill have been updated to contain the users entitlement information and theCorrelationIdassociated with the request may be re-used. If the request fails at any stage aREQUEST_STATUSwill be generated, the specifiedidentitywill not be modified and theCorrelationIdmay be re-used.The
identitysupplied must have been returned from this Session’screateIdentity()method and must not be the session identity.
- sendResponse(event, isPartialResponse=False)
Send the response event for previously received request.
- start()
Start this
Sessionin synchronous mode.Attempt to start this
Sessionand block until theSessionhas started or failed to start. Beforestart()returns aSESSION_STATUSEventis generated. ASessionmay only be started once.
- startAsync()
Start this
Sessionin asynchronous mode.- Return type
- Returns
Trueif the process to start aSessionbegan successfully,Falseotherwise.
Attempt to begin the process to start this
Session. The application must monitor events for aSESSION_STATUSEventwhich will be generated once theSessionhas started or if it fails to start. TheSESSION_STATUSEventmay be processed by the registeredeventHandlerbeforestartAsync()has returned. ASessionmay only be started once.
- stop()
Stop operation of this
Sessionand wait until it stops.Stop operation of this
Sessionand block until all callbacks toeventHandlerobjects relating to thisSessionwhich are currently in progress have completed (including the callback to handle theSESSION_STATUSEventthis call generates). Once this returns no further callbacks toeventHandlerswill occur. Ifstop()is called from within aneventHandlercallback it is silently converted to astopAsync()in order to prevent deadlock. Once aSessionhas been stopped it can only be destroyed.
- stopAsync()
Begin the process to stop this Session and return immediately.
The application must monitor events for a
SESSION_STATUSEventwhich will be generated once theSessionhas been stopped. After thisSESSION_STATUSEventno further callbacks toeventHandlerswill occur. Once aSessionhas been stopped it can only be destroyed.
- terminateSubscriptionsOnTopic(topic, message=None)
Delete the specified
topic(SeedeleteTopic()for additional details).- Parameters
topic – Topic to delete
message – Message to convey additional information to subscribers regarding the termination
Furthermore, proactively terminate all current subscriptions on
topic. The optionally specifiedmessagecan be used to convey additional information to subscribers regarding the termination. This message is contained in thedescriptionofreasonin aSubscriptionTerminatedmessage.
- terminateSubscriptionsOnTopics(topics, message=None)
Terminate subscriptions on the specified
topics.- Parameters
topics – Topics to delete
message – Message to convey additional information to subscribers regarding the termination
See
terminateSubscriptionsOnTopic()for additional details.