雅虎! Fantasy API 最大计数?

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

我正在尝试使用 Yahoo! 返回的 JSON 获取某个位置的所有可用玩家。 Fantasy API,使用此资源:

http://fantasysports.yahooapis.com/fantasy/v2/game/nfl/players;status=A;position=RB

这个 API 似乎总是返回最多 25 个玩家。我也尝试过使用

;count=n
过滤器,但如果 n 大于 25,我仍然只返回 25 名玩家。有谁知道这是为什么?我怎样才能获得更多?

这是我的代码:

from yahoo_oauth import OAuth1

oauth = OAuth1(None, None, from_file='oauth.json', base_url='http://fantasysports.yahooapis.com/fantasy/v2/')

uri = 'league/nfl.l.91364/players;position=RB;status=A;count=100'

if not oauth.token_is_valid():
    oauth.refresh_access_token

response = oauth.session.get(uri, params={'format': 'json'})
python json oauth yahoo-api
2个回答
3
投票

我确实解决了这个问题。我发现最大的“count”是25,但是“start”参数是这个操作的关键。看来 API 为每个玩家附加了一个索引(但是它是排序的),并且“start”参数是开始的索引。这可能看起来很奇怪,但我能找到的唯一方法就是让所有玩家以 25 人为一组返回。所以我的代码解决方案如下所示:

from yahoo_oauth import OAuth1

oauth = OAuth1(None, None, from_file='oauth.json', base_url='http://fantasysports.yahooapis.com/fantasy/v2/')

done = False
start = 1
while(not done) :
    uri = 'league/nfl.l.<league>/players;position=RB;status=A;start=%s,count=25' % start

    if not oauth.token_is_valid():
        oauth.refresh_access_token

    response = oauth.session.get(uri, params={'format': 'json'})

    # parse response, get num of players, do stuff

    start += 25

    if numPlayersInResp < 25:
        done = True

0
投票

我使用了你的编辑,无论起始位置是什么,我一次又一次只能得到 25 名球员。任何见解将不胜感激

  import os
  import requests
  from requests_oauthlib import OAuth2Session
  import webbrowser
  import xml.etree.ElementTree as ET
  import csv
  import json
  # from yahoo_oauth import OAuth2

  class YahooFantasyAPI:

    def __init__(self):
    self.client_id = os.getenv('API_KEY')
    self.client_secret = os.getenv('API_SECRET')
    self.redirect_uri = 'https://localhost/'
    self.league_id = os.getenv('league_id')
    self.base_url = 'https://fantasysports.yahooapis.com/fantasy/v2'
    self.token = None
    self.oauth = OAuth2Session(self.client_id, redirect_uri=self.redirect_uri, scope='openid')
    # self.oauth2= OAuth2(self.client_id,self.client_secret,base_url=self.base_url)
    self.state = None
    self.item_dict=item_dict

def authenticate(self):
    # Step 1: Get authorization URL and state
    authorization_url, self.state = self.oauth.authorization_url(
        'https://api.login.yahoo.com/oauth2/request_auth'
    )
    print(f"Please go to this URL and authorize access: {authorization_url}")
    webbrowser.open(authorization_url)

    # Step 2: User pastes the redirected URL with the code
    redirect_response = input("Paste the full redirect URL here: ")
    print(f"Redirect URL: {redirect_response}")

    # Step 3: Verify that the state parameter from the response matches the one in the request
    if self.state not in redirect_response:
        raise ValueError(f"State in the response does not match the original state. Response state: {redirect_response}")

    print(f"State during token request: {self.state}")

    # Step 4: Fetch the token, ensuring that the state is passed correctly
    self.token = self.oauth.fetch_token(
        'https://api.login.yahoo.com/oauth2/get_token',
        authorization_response=redirect_response,
        client_secret=self.client_secret,
        state=self.state  # Explicitly pass the state value
    )
    print("Authentication successful!")

def get_players(self):
    global item_dict
    if not self.token:
      raise ValueError("Authenticate first by calling the authenticate() method.")

    done = False
    start = 1
    while(not done) :
        # Define the endpoint URL to get league players
        url = f"{self.base_url}/league/{self.league_id}/players;status=A;start={start},count=25"    

        print(url)

        # if not self.oauth.token_is_valid():
        #     self.auth.refresh_access_token

        headers = {
            'Authorization': f"Bearer {self.token['access_token']}",
            'Accept': 'application/xml'  # Expect XML response
        }

        response = self.oauth.get(url, params={'format': 'json'})

        # Print the status code and response content to debug
        print(f"Response Status Code: {response.status_code}")
        print(f"Content-Type: {response.headers.get('Content-Type')}")
        # print(response.content)

        with open('all.json', 'a') as csvfile:
            csvfile.write(response.text)
            csvfile.close()

        item_dict = json.loads(response.text)

        numPlayersInResp=len(item_dict['fantasy_content']['league'][1]['players'])   
        # print(item_dict)
        print(numPlayersInResp)

        start += 25

    if numPlayersInResp < 25:
        done = True

  # Usage
  if __name__ == '__main__':

      yahoo_api = YahooFantasyAPI()
      yahoo_api.authenticate()
      yahoo_api.get_players()
© www.soinside.com 2019 - 2024. All rights reserved.