如何调试Python端点:在Thunder客户端中有效,但在Python脚本中无效

问题描述 投票:0回答:1

我不知道我哪里错了。该端点在 Thunder 客户端上工作正常,但在 python 中却无法正常工作,即使传递的正文和标头也是相同的。

为了确保正文正确,我在终端中打印了数据并将其粘贴到迅雷客户端的正文中。

我还仔细检查了我在 SC_CSRF_TOKEN 中传递的令牌是否正确。

要获取 SC_CSRF_TOKEN 登录https://www.smallcase.com/,然后转到检查元素并检查路由请求的标头

def get_sc_stock_data(stock):
    print(f"Fetching stock data of {stock}")
    url=f"https://api.smallcase.com/market/search?text={stock}"
    responce=requests.get(url)
    responce=responce.json()
    res=responce['data']['searchResults']
    if(len(res)<=0):
        print("stock data not found in smallcase")
        return
    elif(len(res)==1):
        return responce['data']['searchResults'][0]
    else:
        for i in res:
            if(i['stock']['info']['ticker']==stock):
                return i

def get_stock_close_prices(stocks):
    print("Generating the close prices of basket's stocks")
    res = {'count': 0, 'total': 0}
    for stock in stocks:
        stock=stock.upper()
        try:
            st = yf.Ticker(stock+'.NS')
            price = st.history(period='1d').Close.iloc[0]
            res[stock] = price
            res['count'] += 1
            res['total'] += price
        except IndexError:
            print(f"No historical data available for {stock}")
            res[stock] = None
    return res

def convert_to_sc_format(stocks, name, desc):
    print("Generating smallcase basket")
    prices = get_stock_close_prices(stocks)
    total = prices['total']
    constituents = []
    tickers = []
    
    for stock in stocks:
        stock = stock.upper()
        data = get_sc_stock_data(stock)
        if not data:
            continue
        ticker = data['stock']['info']['ticker']
        temp = {
            "sid": data['sid'],
            "shares": 1,
            "locked": False,
            "weight": prices[ticker] / total,
            "sidInfo": {
                "name": data['stock']['info']['name'],
                "sector": data['stock']['info']['sector'],
                "ticker": ticker
            }
        }
        tickers.append(ticker)
        constituents.append(temp)
    
    res = {
        "did": None,
        "scid": None,
        "source": 'CREATED',
        "constituents": constituents,
        "segments": [
            {
                "label": "New Segment",
                "constituents": tickers
            }
        ],
        "compositionScheme": "WEIGHTS",
        "info": {
            "name": name,
            "shortDescription": desc,
            "tier": None
        },
        "stats": {
            "initialValue": total
        }
    }
    res=json.dumps(res,indent=2)
    return res

def post_basket_to_sm(stocks,name,desc):
    data=convert_to_sc_format(stocks,name,desc)
    print(data)
    
    url='https://api.smallcase.com/user/sc/drafts/save'

    headers = {
        'X-Csrf-Token': SC_CSRF_TOKEN,
    }
    res = requests.post(url, headers=headers, json=data)

    return res.json()
stocks=['dlf','ongc']
data1=post_basket_to_sm(stocks,'t2','t2')
print(data1)

我尝试使用 json.dumps() ,但没有显示:

{'success': False, 'errors': \['Invalid token'\], 'data': None}

我还尝试将此数据导出到新的 json 文件中,然后将其导入回函数

预期产量

{
"success": true,
"errors": null,
"data": {
"did": ".......",
"scid": "......."
}
}

输出

{'data': 'Please mail us at [email protected]. Mistake is on our side!'}
python rest debugging integration-testing csrf-token
1个回答
0
投票

我发现了问题所在,基本上标头需要 X-Csrf-Token 和 cookies。在thunder客户端中,有一个cookie管理器,当您在标头中传递cookie时,它会自动存储cookie,因此,如果您再次发送标头中没有这些cookie的请求,它仍然可以工作,因此要准确地知道哪些标头需要清除从迅雷客户端的cookie管理器获取数据,然后发送请求。

© www.soinside.com 2019 - 2024. All rights reserved.