Python:未经授权的彭博API

如何解决Python:未经授权的彭博API

我正在尝试使用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,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,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...")

解决方法

此示例适用于彭博的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地址(或指向用户实际所在位置的一跳)。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res