WorldQuant--发送post请求时no location的处理办法

当你准备了一堆alpha 通过循环进行simulate的时候,由于登录过期等问题可能会出现如下报错

处理办法就是从中断的地方重新登录,重新开始,下面是一个解决问题的示例代码:

python 复制代码
from time import sleep
import json
import requests
from os.path import expanduser


def login():
    # Load credentials
    with open(expanduser('brain_credentials.txt')) as f:
        credentials = json.load(f)
    # Extract username and password from the list
    username, password = credentials
    # Create a session object
    sess = requests.Session()
    # Set up basic authentication
    sess.auth = HTTPBasicAuth(username, password)
    # Send a POST request to the API for authentication
    response = sess.post('https://api.worldquantbrain.com/authentication')
    # Print response status and content for debugging
    print(response.status_code)
    print(response.text)
    return sess


def main():
    alpha_list = []  # 这里应该是你的 alpha 列表,你需要根据实际情况填充
    sess = login()
    index = 0  # 记录当前处理的 alpha 的索引
    while index < len(alpha_list):
        alpha = alpha_list[index]
        try:
            sim_resp = sess.post(
                "https://api.worldquantbrain.com/simulations",
                json=alpha,
            )
            sim_progress_url = sim_resp.headers.get('Location')
            if sim_progress_url:
                while True:
                    sim_progress_resp = sess.get(sim_progress_url)
                    retry_after_sec = float(sim_progress_resp.headers.get("Retry-After", 0))
                    if retry_after_sec == 0:  # simulation done!
                        break
                    sleep(retry_after_sec)
                alpha_id = sim_progress_resp.json()["alpha"]  # the final simulation result
                print(alpha_id)
            else:
                print("no location, sleep for 10 seconds and try next alpha")
                sleep(10)
        except Exception as e:
            print(f"An error occurred: {e}")
            print("Re-login and try again from the next alpha.")
            sess = login()
            index += 1  # 从下一个 alpha 开始
        index += 1


if __name__ == "__main__":
    main()
相关推荐
华科云商xiao徐14 小时前
Linux环境下爬虫程序的部署难题与系统性解决方案
爬虫·数据挖掘·数据分析
木木子999914 小时前
不同行业视角下的数据分析
数据挖掘·数据分析
SHUIPING_YANG16 小时前
如何让dify分类器更加精准的分类?
人工智能·分类·数据挖掘
Christo31 天前
TFS-2018《On the convergence of the sparse possibilistic c-means algorithm》
人工智能·算法·机器学习·数据挖掘
用户Taobaoapi20141 天前
京东店铺所有商品API技术开发文档
大数据·数据挖掘·数据分析
总有刁民想爱朕ha1 天前
车牌模拟生成器:Python3.8+Opencv代码实现与商业应用前景(C#、python 开发包SDK)
开发语言·python·数据挖掘
Stestack1 天前
人工智能常见分类
人工智能·分类·数据挖掘
华科云商xiao徐2 天前
告别IP被封!分布式爬虫的“隐身”与“分身”术
爬虫·数据挖掘·数据分析
未来之窗软件服务2 天前
商业软件开发入门到精通之路-东方仙盟
人工智能·数据挖掘·仙盟创梦ide·东方仙盟·商业软件开发入门
民乐团扒谱机2 天前
逻辑回归算法干货详解:从原理到 MATLAB 可视化实现
数学建模·matlab·分类·数据挖掘·回归·逻辑回归·代码分享