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()
相关推荐
伊一大数据&人工智能学习日志1 小时前
自然语言处理NLP 04案例——苏宁易购优质评论与差评分析
人工智能·python·机器学习·自然语言处理·数据挖掘
huaqianzkh3 小时前
理解构件的3种分类方法
人工智能·分类·数据挖掘
是一只努力的小菜鸡啦18 小时前
数据分析和数据挖掘的工作内容
信息可视化·数据挖掘·数据分析
Sodas(填坑中....)1 天前
SVM对偶问题
人工智能·机器学习·支持向量机·数据挖掘
zhengyawen6661 天前
深度学习之图像回归(二)
人工智能·数据挖掘·回归
liruiqiang051 天前
线性模型 - Logistic 回归
人工智能·机器学习·数据挖掘·回归
zhengyawen6661 天前
深度学习之图像回归(一)
人工智能·数据挖掘·回归
数据小爬虫@1 天前
爬虫获取的数据能用于哪些数据分析?
爬虫·数据挖掘·数据分析
拓端研究室TRL1 天前
R语言Stan贝叶斯空间条件自回归CAR模型分析死亡率多维度数据可视化
开发语言·信息可视化·数据挖掘·回归·r语言
易基因科技2 天前
易基因: ChIP-seq+DRIP-seq揭示AMPK通过调控H3K4me3沉积和R-loop形成以维持基因组稳定性和生殖细胞完整性|NAR
经验分享·数据挖掘·生物学·生物信息学