blpapi.Session
- class blpapi.Session(options=None, eventHandler=None, eventDispatcher=None)
Bases:
AbstractSession
Consumer session for making requests for Bloomberg services.
This class provides a consumer session for making requests for Bloomberg services. For information on generic session operations, see the parent class:
AbstractSession
.Sessions manage access to services either by requests and responses or subscriptions. A Session can dispatch events and replies in either a synchronous or asynchronous mode. The mode of a Session is determined when it is constructed and cannot be changed subsequently.
A Session is asynchronous if an
eventHandler
argument is supplied when it is constructed. ThenextEvent()
method may not be called. All incoming events are delivered to theeventHandler
supplied on construction.If supplied,
eventHandler
must be a callable object that takes two arguments: receivedEvent
and related session.A Session is synchronous if an
eventHandler
argument is not supplied when it is constructed. ThenextEvent()
method must be called to read incoming events.Several methods in Session take a
CorrelationId
parameter. The application may choose to supply its ownCorrelationId
values or allow the Session to create values. If the application supplies its ownCorrelationId
values it must manage their lifetime such that the same value is not reused for more than one operation at a time. The lifetime of aCorrelationId
begins when it is supplied in a method invoked on a Session and ends either when it is explicitly cancelled usingcancel()
orunsubscribe()
, when aRESPONSE
Event
(not aPARTIAL_RESPONSE
) containing it is received or when aSUBSCRIPTION_STATUS
Event
which indicates that the subscription it refers to has been terminated is received.When using an asynchronous Session, the application must be aware that because the callbacks are generated from another thread, they may be processed before the call which generates them has returned. For example, the
SESSION_STATUS
Event
generated by astartAsync()
may be processed beforestartAsync()
has returned (even thoughstartAsync()
itself will not block).This becomes more significant when Session generated
CorrelationId
s are in use. For example, if a call tosubscribe()
which returns a Session generatedCorrelationId
has not completed before the firstEvent
s which contain thatCorrelationId
arrive the application may not be able to interpret those events correctly. For this reason, it is preferable to use user generatedCorrelationId
s when using asynchronous Sessions. This issue does not arise when using a synchronous Session as long as the calls tosubscribe()
etc. are made on the same thread as the calls tonextEvent()
.The class attributes represent the states in which a subscription can be.
- CANCELLED = 3
No longer active, terminated by Application.
- PENDING_CANCELLATION = 4
No longer active, terminated by Application.
- SUBSCRIBED = 2
Updates are flowing.
- SUBSCRIBING = 1
Initiated but no updates received.
- UNSUBSCRIBED = 0
No longer active, terminated by API.
- __init__(options=None, eventHandler=None, eventDispatcher=None)
Create a consumer
Session
.- Parameters:
options – Options to construct the session with
eventHandler – Handler for events generated by the session. Takes two arguments - received event and related session
eventDispatcher – An optional dispatcher for events.
- Raises:
InvalidArgumentException – If
eventHandler
isNone
and and theeventDispatcher
is notNone
If
eventHandler
is notNone
then thisSession
will operate in asynchronous mode, otherwise theSession
will operate in synchronous mode.If
eventDispatcher
isNone
then theSession
will create a defaultEventDispatcher
for thisSession
which will use a single thread for dispatching events. For more control over event dispatching a specific instance ofEventDispatcher
can be supplied. This can be used to share a singleEventDispatcher
amongst multipleSession
objects.If an
eventDispatcher
is supplied which uses more than one thread theSession
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
eventDispatcher
uses it’s 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
.Note
In case of unhandled exception in
eventHandler
, the exception traceback will be printed tosys.stderr
and application will be terminated with nonzero exit code.
- cancel(correlationId)
Cancel request(s) with a single
correlationId
or a list.- Parameters:
correlationId (
Union
[CorrelationId
,Sequence
[CorrelationId
]]) – Correlation id(s) associated with the request(s) to cancel
For all specified
correlationId
values that identify an ongoing request cancel that request.Once this call returns the specified
correlationId
will not be seen in any subsequentMessage
obtained from aMessageIterator
by callingnext()
. However, anyMessage
currently pointed to by aMessageIterator
whencancel()
is called is not affected even if it has the specifiedcorrelationId
. Also anyMessage
where a reference has been retained by the application may still contain thecorrelationId
. For these reasons, although technically an application is free to re-usecorrelationId
as 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
Identity
which is valid but has not been authorized.- Returns:
Identity which is valid but has not been authorized
- Return type:
- createSnapshotRequestTemplate(subscriptionString, correlationId, identity=None)
Create a snapshot request template for getting subscription data specified by the
subscriptionString
using the specifiedidentity
.- Parameters:
subscriptionString – String that specifies the subscription
correlationId – Correlation id to associate with events generated by this operation
identity – Optional. Identity used for authorization.
- Returns:
Created request template
- Return type:
- Raises:
Exception – If one or more of the following conditions is not met: the session is established,
subscriptionString
is a valid subscription string andcorrelationId
is not used in this session.
The provided
correlationId
will be used for status updates about the created request template state and an implied subscription associated with it delivered bySUBSCRIPTION_STATUS
events.The benefit of the snapshot request templates is that these requests may be serviced from a cache and the user may expect to see significantly lower response time.
There are 3 possible states for a created request template:
Pending
,Available
, andTerminated
. Right after creation a request template is in thePending
state.If a state is
Pending
, the user may send a request using this template but there are no guarantees about response time since cache is not available yet. Request template may transition intoPending
state only from theAvailable
state. In this case theRequestTemplatePending
message is generated.If state is
Available
, all requests will be serviced from a cache and the user may expect to see significantly reduced latency. Note, that a snapshot request template can transition out of theAvailable
state concurrently with requests being sent, so no guarantee of service from the cache can be provided. Request template may transition intoAvailable
state only from thePending
state. In this case theRequestTemplateAvailable
message is generated. This message will also contain information about currently used connection in theboundTo
field. Note that it is possible to get theRequestTemplateAvailable
message with a new connection information, even if a request template is already in theAvailable
state.If state is
Terminated
, sending request will always result in a failure response. Request template may transition into this state from any other state. This is a final state and it is guaranteed that the last message associated with the providedcorrelationId
will be theRequestTemplateTerminated
message which is generated when a request template transitions into this state. If a request template transitions into this state, all outstanding requests will be failed and appropriate messages will be generated for each request. After receiving theRequestTemplateTerminated
message,correlationId
may be reused.Note that resources used by a snapshot request template are released only when request template transitions into the
Terminated
state or when session is destroyed. In order to release resources when request template is not needed anymore, user should call thecancel()
method unless theRequestTemplateTerminated
message was already received due to some problems. When the last copy of aRequestTemplate
object goes out of scope and there are no outstanding requests left, the snapshot request template will be destroyed automatically. If the last copy of aRequestTemplate
object goes out of scope while there are still some outstanding requests left, snapshot service request template will be destroyed automatically when the last request gets a final response.When
identity
isNone
, the session identity will be used if it has been authorized.
- generateAuthorizedIdentity(authOptions, correlationId=None)
Generates an authorized
Identity
with the specifiedauthOptions
andcorrelationId
.- Parameters:
- Returns:
Identifies the aforementioned events and the generated
Identity
.- Return type:
If this is an asynchronous session then an
Event
may be delivered to the registeredEventHandler
beforegenerateAuthorizedIdentity()
has returned.One or more
Event.AUTHORIZATION_STATUS
events, zero or moreEvent.TOKEN_STATUS
events, and zero or moreEvent.SERVICE_STATUS
events are generated.The behavior is undefined if either
authOptions
orcorrelationId
isNone
.
- 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
SessionOptions
or the arguments to the function are invalid.
The
authId
andipAddress
must be provided together and can only be provided if the authentication mode isMANUAL
.
- getAuthorizedIdentity(correlationId=None)
Returns the authorized
Identity
associated withcorrelationId
. IfcorrelationId
is not given, returns the session identity.- Parameters:
correlationId (
Optional
[CorrelationId
]) – Optional. Associated with anIdentity
.- Returns:
the
Identity
associated withcorrelationId
.- Return type:
- Raises:
NotFoundException – If there is no
Identity
associated withcorrelationId
, if the associatedIdentity
is not authorized, or ifcorrelationId
is not given and the session identity is not authorized.
- getService(serviceName)
Return a
Service
object 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
serviceName
is not open already
The
serviceName
must contain a fully qualified service name. That is, it must be of the form//<namespace>/<service-name>
.
- nextEvent(timeout=0)
- Parameters:
timeout (
int
) – Timeout threshold in milliseconds- Returns:
Next available event for this session
- Return type:
- Raises:
InvalidStateException – If invoked on a session created in asynchronous mode
If there is no
Event
available this will block for up to the specifiedtimeout
milliseconds for anEvent
to arrive. A value of0
fortimeout
(the default) indicatesnextEvent()
should not timeout and will not return until the nextEvent
is 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:
True
if the service is opened successfully,False
otherwise.
Attempt to open the service identified by the specified
serviceName
and block until the service is either opened successfully or has failed to be opened. ReturnTrue
if the service is opened successfully andFalse
if the service cannot be successfully opened.The
serviceName
must contain a fully qualified service name. That is, it must be of the form//<namespace>/<service-name>
.Before
openService()
returns aSERVICE_STATUS
Event
is generated. If this is an asynchronous Session then thisEvent
may be processed by the registeredeventHandler
beforeopenService()
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
serviceName
and return immediately. The optional specifiedcorrelationId
is used to trackEvent
s generated as a result of this call.The
serviceName
must 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_STATUS
Event
which will be generated once the service has been successfully opened or the opening has failed.
- resubscribe(subscriptionList, requestLabel=None, resubscriptionId=None, mode=SubscriptionPreprocessMode.FAIL_ON_FIRST_ERROR)
Modify subscriptions in
subscriptionList
.- Parameters:
subscriptionList – List of subscriptions to modify
requestLabel – String which will be recorded along with any diagnostics for this operation
resubscriptionId – An id that will be included in the event generated from this operation
mode – Mode to use for this operation. See
SubscriptionPreprocessMode
for an explanation of the available modes.
- Returns:
- If mode is
FAIL_ON_FIRST_ERROR
, then
None
is returned. If mode isRETURN_INDIVIDUAL_ERRORS
, then a list ofSubscriptionPreprocessError
is returned.
- If mode is
Modify each subscription in the specified
subscriptionList
, which must be an object of typeSubscriptionList
, to reflect the modified options specified for it. If the optionalrequestLabel
is provided it defines a string which will be recorded along with any diagnostics for this operation.For each entry in the
subscriptionList
which has a correlation ID which identifies a current subscription the modified options replace the current options for the subscription and aSUBSCRIPTION_STATUS
Event
(containing theresubscriptionId
if specified) will be generated in the event stream before the first update based on the new options. If the correlation ID of an entry in thesubscriptionList
does not identify a current subscription then that entry is ignored.
- 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
authorizationRequest
and update the specifiedidentity
with the results. If the optionally specifiedcorrelationId
is supplied, it is used; otherwise create aCorrelationId
. The actualCorrelationId
used is returned. If the optionally specifiedeventQueue
is supplied allEvent
s relating to thisRequest
will 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_RESPONSE
Message
s followed by exactly oneRESPONSE
Message
. Once the finalRESPONSE
Message
has been received the specifiedidentity
will have been updated to contain the users entitlement information and theCorrelationId
associated with the request may be re-used. If the request fails at any stage aREQUEST_STATUS
will be generated, the specifiedidentity
will not be modified and theCorrelationId
may be re-used.The
identity
supplied must have been returned from this Session’screateIdentity()
method and must not be the session identity.
- sendRequest(request, identity=None, correlationId=None, eventQueue=None, requestLabel=None)
Send the specified
request
.- Parameters:
request – Request to send
identity – Identity used for authorization
correlationId – Correlation id to associate with the request
eventQueue – Event queue on which the events related to this operation will arrive
requestLabel – String which will be recorded along with any diagnostics for this operation
- Returns:
The actual correlation id associated with the request
- Return type:
Send the specified
request
using the optionally specifiedidentity
for authorization. Ifidentity
is not provided, then the request will be sent using the session identity. If the optionally specifiedcorrelationId
is supplied use it, otherwise create aCorrelationId
. The actualCorrelationId
used is returned. If the optionally specifiedeventQueue
is supplied all events relating to thisRequest
will arrive on thatEventQueue
. If the optionalrequestLabel
is provided it defines a string which will be recorded along with any diagnostics for this operation.A successful request will generate zero or more
PARTIAL_RESPONSE
Message
s followed by exactly oneRESPONSE
Message
. Once the finalRESPONSE
Message
has been received theCorrelationId
associated with this request may be re-used. If the request fails at any stage aREQUEST_STATUS
will be generated after which theCorrelationId
associated with the request may be re-used.When
identity
is not provided, the session identity will be used if it has been authorized.
- sendRequestTemplate(requestTemplate, correlationId=None)
Send a request defined by the specified
requestTemplate
.- Parameters:
requestTemplate (
RequestTemplate
) – Template that defines the requestcorrelationId (
Optional
[CorrelationId
]) – Correlation id to associate with the request
- Returns:
The actual correlation id used for the request is returned.
- Return type:
If the optionally specified
correlationId
is supplied, use it otherwise create a newCorrelationId
. The actualCorrelationId
used is returned.A successful request will generate zero or more
PARTIAL_RESPONSE
events followed by exactly oneRESPONSE
event. Once the finalRESPONSE
event has been received theCorrelationId
associated with this request may be re-used. If the request fails at any stage aREQUEST_STATUS
will be generated after which theCorrelationId
associated with the request may be re-used.
- setStatusCorrelationId(service, correlationId, identity=None)
Set the Correlation id on which service status messages will be received.
- Parameters:
service – The service from which the status messages are received
correlationId – Correlation id to associate with the service status messages
identity – Identity used for authorization
Note
No service status messages are received prior to this call
- start()
Start this
Session
in synchronous mode.Attempt to start this
Session
and block until theSession
has started or failed to start. Beforestart()
returns aSESSION_STATUS
Event
is generated. ASession
may only be started once.
- startAsync()
Start this
Session
in asynchronous mode.- Return type:
- Returns:
True
if the process to start aSession
began successfully,False
otherwise.
Attempt to begin the process to start this
Session
. The application must monitor events for aSESSION_STATUS
Event
which will be generated once theSession
has started or if it fails to start. TheSESSION_STATUS
Event
may be processed by the registeredeventHandler
beforestartAsync()
has returned. ASession
may only be started once.
- stop()
Stop operation of this
Session
and wait until it stops.Stop operation of this
Session
and block until all callbacks toeventHandler
objects relating to thisSession
which are currently in progress have completed (including the callback to handle theSESSION_STATUS
Event
this call generates). Once this returns no further callbacks toeventHandlers
will occur. Ifstop()
is called from within aneventHandler
callback it is silently converted to astopAsync()
in order to prevent deadlock. Once aSession
has been stopped it can only be destroyed.
- stopAsync()
Begin the process to stop this Session and return immediately.
- Return type:
- Returns:
True
if the process to stop aSession
began successfully,False
otherwise.
The application must monitor events for a
SESSION_STATUS
Event
which will be generated once theSession
has been stopped. After thisSESSION_STATUS
Event
no further callbacks toeventHandlers
will occur. Once aSession
has been stopped it can only be destroyed.
- subscribe(subscriptionList, identity=None, requestLabel=None, mode=SubscriptionPreprocessMode.FAIL_ON_FIRST_ERROR)
Begin subscriptions for each entry in the specified list.
- Parameters:
subscriptionList – List of subscriptions to begin
identity – Identity used for authorization
requestLabel – String which will be recorded along with any diagnostics for this operation
mode – Mode to use for this operation. See
SubscriptionPreprocessMode
for an explanation of the available modes.
- Returns:
- If mode is
FAIL_ON_FIRST_ERROR
, then
None
is returned. If mode isRETURN_INDIVIDUAL_ERRORS
, then a list ofSubscriptionPreprocessError
is returned.
- If mode is
Begin subscriptions for each entry in the specified
subscriptionList
, which must be an object of typeSubscriptionList
, optionally using the specifiedidentity
for authorization. If noidentity
is specified, the default authorization information is used. If the optionalrequestLabel
is provided it defines a string which will be recorded along with any diagnostics for this operation.A
SUBSCRIPTION_STATUS
Event
will be generated for each entry in thesubscriptionList
.When
identity
is not provided, the session identity will be used if it has been authorized.
- tryNextEvent()
- Returns:
Next available event for this session
- Return type:
If there are
Event
s available for the session, return the nextEvent
If there is no event available for theSession
, returnNone
. This method never blocks.
- unsubscribe(subscriptionList)
Cancel subscriptions from the specified
subscriptionList
.- Parameters:
subscriptionList – List of subscriptions to cancel
Cancel each of the current subscriptions identified by the specified
subscriptionList
, which must be an object of typeSubscriptionList
. If the correlation ID of any entry in thesubscriptionList
does not identify a current subscription then that entry is ignored. All entries which have valid correlation IDs will be cancelled.Once this call returns the correlation ids in the
subscriptionList
will not be seen in any subsequentMessage
obtained from aMessageIterator
by callingnext()
However, anyMessage
currently pointed to by aMessageIterator
whenunsubscribe()
is called is not affected even if it has one of the correlation IDs in thesubscriptionList
. Also anyMessage
where a reference has been retained by the application may still contain a correlation ID from thesubscriptionList
. For these reasons, although technically an application is free to re-use the correlation IDs as soon as this method returns it is preferable not to aggressively re-use correlation IDs, particularly with an asynchronousSession
.