Python调用smallcase API调试:Thunder Client可用但脚本失败
Smallcase API Python调用失败问题排查
Smallcase的/user/sc/drafts/save接口在Thunder Client中可正常调用,但在Python脚本中执行失败,尽管请求体和请求头与Thunder Client中完全一致:
- 已将终端打印的请求体复制到Thunder Client中验证,确认格式正确
- SC_CSRF_TOKEN是登录smallcase官网后从开发者工具的请求头中获取,反复核对过正确性
错误表现
- 未使用
json.dumps()处理请求体时,返回错误:
{'success': False, 'errors': ['Invalid token'], 'data': None}
- 使用
json.dumps()处理请求体后,返回结果:
{'data': 'Please mail us at tech@smallcase.com. Mistake is on our side!'}
预期成功响应
{ "success": true, "errors": null, "data": { "did": ".......", "scid": "......." } }
已尝试的解决方案
将生成的数据导出为JSON文件后再导入函数调用,问题仍未解决。
相关代码
import requests import yfinance as yf import json # 替换为实际获取的SC_CSRF_TOKEN SC_CSRF_TOKEN = "your-actual-token" 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)
内容的提问来源于stack exchange,提问作者Robin
相关产品推荐
相关产品推荐

