我正在尝试使用Python API从Bloomberg中提取数据。 API包随附示例代码,并且仅需要本地主机的程序即可完美运行。但是,使用其他授权方式的程序始终会卡在错误中:
Connecting to port 8194 on localhost
TokenGenerationFailure = {
reason = {
source = "apitkns (apiauth) on ebbdbp-ob-053"
category = "NO_AUTH"
errorCode = 12
description = "User not in emrs userid=NA\mds firm=22691"
subcategory = "INVALID_USER"
}
}
Failed to get token
No authorization
我看到另外一个人也遇到类似的问题,但是他没有解决这个问题,而是选择只使用本地主机。我不能总是使用本地主机,因为我将不得不为其他用户提供帮助和故障排除。因此,我需要提示如何克服此错误。
我的问题是,如何设置用户ID而不是OS_LOGON
之外的其他任何东西,它会自动使用我的帐户的登录凭据,以便在需要时可以使用其他用户的名称?我试图用用户名更改OS_LOGON
,但没有用。
我要运行的完整程序是:
"""SnapshotRequestTemplateExample.py"""
from __future__ import print_function
from __future__ import absolute_import
import datetime
from optparse import OptionParser, OptionValueError
import blpapi
TOKEN_SUCCESS = blpapi.Name("TokenGenerationSuccess")
TOKEN_FAILURE = blpapi.Name("TokenGenerationFailure")
AUTHORIZATION_SUCCESS = blpapi.Name("AuthorizationSuccess")
TOKEN = blpapi.Name("token")
def authOptionCallback(_option, _opt, value, parser):
vals = value.split('=', 1)
if value == "user":
parser.values.auth = "AuthenticationType=OS_LOGON"
elif value == "none":
parser.values.auth = None
elif vals[0] == "app" and len(vals) == 2:
parser.values.auth = "AuthenticationMode=APPLICATION_ONLY;"\
"ApplicationAuthenticationType=APPNAME_AND_KEY;"\
"ApplicationName=" + vals[1]
elif vals[0] == "userapp" and len(vals) == 2:
parser.values.auth = "AuthenticationMode=USER_AND_APPLICATION;"\
"AuthenticationType=OS_LOGON;"\
"ApplicationAuthenticationType=APPNAME_AND_KEY;"\
"ApplicationName=" + vals[1]
elif vals[0] == "dir" and len(vals) == 2:
parser.values.auth = "AuthenticationType=DIRECTORY_SERVICE;"\
"DirSvcPropertyName=" + vals[1]
else:
raise OptionValueError("Invalid auth option '%s'" % value)
def parseCmdLine():
"""parse cli arguments"""
parser = OptionParser(description="Retrieve realtime data.")
parser.add_option("-a",
"--ip",
dest="hosts",
help="server name or IP (default: localhost)",
metavar="ipAddress",
action="append",
default=[])
parser.add_option("-p",
dest="port",
type="int",
help="server port (default: %default)",
metavar="tcpPort",
default=8194)
parser.add_option("--auth",
dest="auth",
help="authentication option: "
"user|none|app=<app>|userapp=<app>|dir=<property>"
" (default: %default)",
metavar="option",
action="callback",
callback=authOptionCallback,
type="string",
default="user")
(opts, _) = parser.parse_args()
if not opts.hosts:
opts.hosts = ["localhost"]
if not opts.topics:
opts.topics = ["/ticker/IBM US Equity"]
return opts
def authorize(authService, identity, session, cid):
"""authorize the session for identity via authService"""
tokenEventQueue = blpapi.EventQueue()
session.generateToken(eventQueue=tokenEventQueue)
# Process related response
ev = tokenEventQueue.nextEvent()
token = None
if ev.eventType() == blpapi.Event.TOKEN_STATUS or \
ev.eventType() == blpapi.Event.REQUEST_STATUS:
for msg in ev:
print(msg)
if msg.messageType() == TOKEN_SUCCESS:
token = msg.getElementAsString(TOKEN)
elif msg.messageType() == TOKEN_FAILURE:
break
if not token:
print("Failed to get token")
return False
# Create and fill the authorization request
authRequest = authService.createAuthorizationRequest()
authRequest.set(TOKEN, token)
# Send authorization request to "fill" the Identity
session.sendAuthorizationRequest(authRequest, identity, cid)
# Process related responses
startTime = datetime.datetime.today()
WAIT_TIME_SECONDS = 10
while True:
event = session.nextEvent(WAIT_TIME_SECONDS * 1000)
if event.eventType() == blpapi.Event.RESPONSE or \
event.eventType() == blpapi.Event.REQUEST_STATUS or \
event.eventType() == blpapi.Event.PARTIAL_RESPONSE:
for msg in event:
print(msg)
if msg.messageType() == AUTHORIZATION_SUCCESS:
return True
print("Authorization failed")
return False
endTime = datetime.datetime.today()
if endTime - startTime > datetime.timedelta(seconds=WAIT_TIME_SECONDS):
return False
def main():
"""main entry point"""
global options
options = parseCmdLine()
# Fill SessionOptions
sessionOptions = blpapi.SessionOptions()
for idx, host in enumerate(options.hosts):
sessionOptions.setServerAddress(host, options.port, idx)
sessionOptions.setAuthenticationOptions(options.auth)
sessionOptions.setAutoRestartOnDisconnection(True)
print("Connecting to port %d on %s" % (
options.port, ", ".join(options.hosts)))
session = blpapi.Session(sessionOptions)
if not session.start():
print("Failed to start session.")
return
subscriptionIdentity = None
if options.auth:
subscriptionIdentity = session.createIdentity()
isAuthorized = False
authServiceName = "//blp/apiauth"
if session.openService(authServiceName):
authService = session.getService(authServiceName)
isAuthorized = authorize(authService, subscriptionIdentity,
session, blpapi.CorrelationId("auth"))
if not isAuthorized:
print("No authorization")
return
else:
print("Not using authorization")
.
.
.
.
.
finally:
session.stop()
if __name__ == "__main__":
print("SnapshotRequestTemplateExample")
try:
main()
except KeyboardInterrupt:
print("Ctrl+C pressed. Stopping...")
答案 0 :(得分:2)
此示例适用于彭博的BPIPE产品,因此包括必要的授权代码。对于此示例,如果要连接到桌面API(通常为localhost:8194),则需要传递auth参数“ none”。请注意,此示例用于桌面API不支持的mktdata快照功能。
您声明要尝试代表其他用户进行故障排除,大概是使用BPIPE的交易员在其凭据下。在这种情况下,您将需要创建一个Identity对象来代表该用户。
可以这样完成:
# Create and fill the authorization request
authRequest = authService.createAuthorizationRequest()
authRequest.set("authId", STRING_CONTAINING_USERS_EMRS_LOGON)
authRequest.set("ipAddress", STRING_OF_IP_ADDRESS_WHERE_USER_IS_LOGGED_INTO_TERMINAL)
# Send authorization request to "fill" the Identity
session.sendAuthorizationRequest(authRequest, identity, cid)
使用此方法时,请注意潜在的许可合规性问题,因为这可能会导致严重的后果。如有任何疑问,请与您公司的市场数据团队联系,他们将能够询问其彭博联系人。
编辑: 如评论中的要求,详细说明AuthorizationRequest的其他可能参数。
“ uuid” +“ ipAddress”;这将是验证服务器API用户身份的默认方法。在BPIPE上,这将要求彭博社为您明确启用它。 UUID是分配给每个Bloomberg Anywhere用户的唯一整数标识符。您可以通过运行IAM在终端中查找
“ emrsId” +“ ipAddress”; “ emrsId”是“ authId”的已弃用别名。不应再使用它。
“ authId” +“ ipAddress”; “ authId”是在EMRS(BPIPE权利管理和报告系统)或SAPE(等效于EMRS的Server API)中定义的字符串,代表每个用户。通常是用户的操作系统登录详细信息(例如DOMAIN / USERID)或Active Directory属性(例如mail-> blah@blah.blah)
“ authId” +“ ipAddress” +“ application”; “应用程序”是在EMRS / SAPE上定义的应用程序名称。这将检查是否为EMRS上的命名应用程序启用了authId中定义的用户。在请求中使用这些用户+应用程序样式的身份对象之一,应在EMRS使用情况报告中记录用户和应用程序的使用情况。
“令牌”;这是首选方法。使用session.generateToken功能(可以在原始问题的代码片段中看到)将生成一个字母数字字符串。您会将其作为唯一参数传递到“授权”请求中。请注意,令牌生成系统支持虚拟化。如果它检测到它正在Citrix或远程桌面中运行,它将报告显示计算机的IP地址(或指向用户实际所在位置的一跳)。