コード例 #1
0
ファイル: query.py プロジェクト: famish99/BohemianRhapsody
    def get_token(self):
        """
        Login and all that crap
        """
        path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'cache'))
        token_store = FileTokenStore(path, secret=TOKEN_SECRET)

        stored_token = token_store.get('fantasy')

        if not stored_token:
            # Do the dance
            request_token, auth_url = self.yql_manager.get_token_and_auth_url()
            print "Visit url %s and get a verifier string" % auth_url
            verifier = raw_input("Enter the code: ")
            self.auth_token = self.yql_manager.get_access_token(request_token, verifier)
            token_store.set('fantasy', self.auth_token)
        else:
            # Check access_token is within 1hour-old and if not refresh it
            # and stash it
            self.auth_token = self.yql_manager.check_token(stored_token)
            if self.auth_token != stored_token:
                token_store.set('fantasy', self.auth_token)

        # Create our client.
        self.client = oauth.Client(self.consumer, self.auth_token)
コード例 #2
0
    def test_update_meme_status(self):
        """Updates status"""
        y = yql.ThreeLegged(YQL_API_KEY, YQL_SHARED_SECRET)
        query = 'INSERT INTO meme.user.posts (type, content) VALUES("text", "test with pythonyql")'
        token_store = FileTokenStore(CACHE_DIR, secret='fjdsfjllds')

        store_name = "meme"
        stored_token = token_store.get(store_name)
        if not stored_token:
            # Do the dance
            request_token, auth_url = y.get_token_and_auth_url()
            print "Visit url %s and get a verifier string" % auth_url
            verifier = raw_input("Enter the code: ")
            token = y.get_access_token(request_token, verifier)
            token_store.set(store_name, token)
        else:
            # Check access_token is within 1hour-old and if not refresh it
            # and stash it
            token = y.check_token(stored_token)
            if token != stored_token:
                token_store.set(store_name, token)

        # post a meme
        res = y.execute(query, token=token)
        assert y.uri == "http://query.yahooapis.com/v1/yql"
        assert res.rows[0].get("message") == "ok"

        pubid = None
        if res.rows[0].get("post") and res.rows[0]["post"].get("pubid"):
            pubid = res.rows[0]["post"]["pubid"]

        # Delete the post we've just created
        query = 'DELETE FROM meme.user.posts WHERE pubid=@pubid'
        res2 = y.execute(query, token=token, params={"pubid": pubid})
        assert res2.rows[0].get("message") == "ok"
コード例 #3
0
    def test_update_social_status(self):
        """Updates status"""
        y = yql.ThreeLegged(YQL_API_KEY, YQL_SHARED_SECRET)

        timestamp = time()
        query = """UPDATE social.profile.status
                   SET status='Using YQL. %s Update'
                   WHERE guid=me""" % timestamp

        token_store = FileTokenStore(CACHE_DIR, secret='gsfdsfdsfdsfs')
        stored_token = token_store.get('foo')

        if not stored_token:
            # Do the dance
            request_token, auth_url = y.get_token_and_auth_url()
            print "Visit url %s and get a verifier string" % auth_url
            verifier = raw_input("Enter the code: ")
            token = y.get_access_token(request_token, verifier)
            token_store.set('foo', token)
        else:
            # Check access_token is within 1hour-old and if not refresh it
            # and stash it
            token = y.check_token(stored_token)
            if token != stored_token:
                token_store.set('foo', token)

        res = y.execute(query, token=token)
        assert res.rows[0] == "ok"
        new_query = """select message from social.profile.status where guid=me"""
        res = y.execute(new_query, token=token)
        assert res.rows[0].get("message") == "Using YQL. %s Update" % timestamp
コード例 #4
0
ファイル: yahoo_tools.py プロジェクト: dsimpson1980/yff
def get_token(y3, dialog=None):
    """Check if there is a cached token and if so retrieve it else ask the user
    for a new token using dialog.

    The cached token is stored in ~/YahooFF/

    Parameters
    ----------
    y3:
    dialog:

    Returns
    -------
    yql.YahooToken
        Either the cached token or a newly requested token
    """
    _cache_dir = os.path.expanduser('~/YahooFF')
    if not os.access(_cache_dir, os.R_OK):
        os.mkdir(_cache_dir)
    token_store = FileTokenStore(_cache_dir, secret='sasfasdfdasfdaf')
    stored_token = token_store.get('foo')
    if not stored_token:
        request_token, auth_url = y3.get_token_and_auth_url()
        if dialog is not None:
            verifier = dialog(auth_url)
        else:
            print "Visit url %s and get a verifier string" % auth_url
            verifier = raw_input("Enter the code: ")
        token = y3.get_access_token(request_token, verifier)
        token_store.set('foo', token)
    else:
        token = y3.check_token(stored_token)
        if token != stored_token:
            token_store.set('foo', token)
    return token
コード例 #5
0
    def test_update_meme_status(self):
        """Updates status"""
        y = yql.ThreeLegged(YQL_API_KEY, YQL_SHARED_SECRET)
        query = 'INSERT INTO meme.user.posts (type, content) VALUES("text", "test with pythonyql")'
        token_store = FileTokenStore(CACHE_DIR, secret='fjdsfjllds')

        store_name = "meme"
        stored_token = token_store.get(store_name)
        if not stored_token:
            # Do the dance
            request_token, auth_url = y.get_token_and_auth_url()
            print "Visit url %s and get a verifier string" % auth_url
            verifier = raw_input("Enter the code: ")
            token = y.get_access_token(request_token, verifier)
            token_store.set(store_name, token)
        else:
            # Check access_token is within 1hour-old and if not refresh it
            # and stash it
            token = y.check_token(stored_token)
            if token != stored_token:
                token_store.set(store_name, token)

        # post a meme
        res = y.execute(query, token=token)
        assert y.uri == "http://query.yahooapis.com/v1/yql"
        assert res.rows[0].get("message") == "ok"

        pubid = None
        if res.rows[0].get("post") and res.rows[0]["post"].get("pubid"):
            pubid = res.rows[0]["post"]["pubid"]

        # Delete the post we've just created
        query = 'DELETE FROM meme.user.posts WHERE pubid=@pubid'
        res2 = y.execute(query, token=token, params={"pubid": pubid})
        assert res2.rows[0].get("message") == "ok"
コード例 #6
0
ファイル: YOAuth.py プロジェクト: SamProtas/Webpage
def OAuth():

	consumer_key = ('dj0yJmk9SGRrbkt5SHFSd2hVJmQ9WVdrOVJqUTRiMVZLTXpRbWNHbzlNQS0tJnM9Y29uc3VtZXJzZWNyZXQmeD1iNQ--')
	consumer_secret = ('3deb9f91d5086dec9c9dfe1ac8925eecb5741070')

	y3 = yql.ThreeLegged(consumer_key, consumer_secret)
	_cache_dir = os.path.expanduser('~/Desktop/FlaskApp/FlaskApp/Yahoo_Fantasy')

	if not os.access(_cache_dir,os.R_OK):
		os.mkdir(_cache_dir)
	token_store = FileTokenStore(_cache_dir, secret=consumer_secret)

	stored_token = token_store.get('foo')

	if not stored_token:
		#get access token, visit website and grant yourself access to league information
		request_token, auth_url = y3.get_token_and_auth_url()
		print "Visit url %s and get a verifier string" % auth_url
		verifier = raw_input("Enter the code: ") 
		token = y3.get_access_token(request_token, verifier)
		token_store.set('foo', token)

	else:
		# Check access_token is within 1hour-old and if not refresh it and stash it
		token = y3.check_token(stored_token)
		if token != stored_token:
			token_store.set('foo', token)
コード例 #7
0
    def test_update_social_status(self):
        """Updates status"""
        y = yql.ThreeLegged(YQL_API_KEY, YQL_SHARED_SECRET)

        timestamp = time()
        query = """UPDATE social.profile.status
                   SET status='Using YQL. %s Update'
                   WHERE guid=me"""  % timestamp

        token_store = FileTokenStore(CACHE_DIR, secret='gsfdsfdsfdsfs')
        stored_token = token_store.get('foo')

        if not stored_token:
            # Do the dance
            request_token, auth_url = y.get_token_and_auth_url()
            print "Visit url %s and get a verifier string" % auth_url
            verifier = raw_input("Enter the code: ")
            token = y.get_access_token(request_token, verifier)
            token_store.set('foo', token)
        else:
            # Check access_token is within 1hour-old and if not refresh it
            # and stash it
            token = y.check_token(stored_token)
            if token != stored_token:
                token_store.set('foo', token)

        res = y.execute(query, token=token)
        assert res.rows[0] == "ok"
        new_query = """select message from social.profile.status where guid=me"""
        res = y.execute(new_query, token=token)
        assert res.rows[0].get("message") == "Using YQL. %s Update" % timestamp
コード例 #8
0
ファイル: test_storage.py プロジェクト: allanice001/RJ45
 def test_saves_token_to_filesystem(self):
     directory = tempfile.mkdtemp()
     store = FileTokenStore(directory)
     token = YahooToken('some-token', 'some-secret')
     store.set('foo', token)
     with open(store.get_filepath('foo')) as stored_file:
         self.assertTrue('some-token' in stored_file.read())
コード例 #9
0
ファイル: yql_auth.py プロジェクト: superlou/wireless_joe
    def __init__(self, stored_token_name, key, secret):
        API_KEY = key
        SECRET = secret

        y = yql.ThreeLegged(API_KEY, SECRET)

        path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'cache'))
        if not os.path.exists(path):
            os.makedirs(path)

        token_store = FileTokenStore(path, secret='apples')

        stored_token = token_store.get(stored_token_name)

        if not stored_token:
            request_token, auth_url = y.get_token_and_auth_url()
            webbrowser.open(auth_url)
            verifier = raw_input("Enter the code: ")
            token = y.get_access_token(request_token, verifier)
            token_store.set(stored_token_name, token)
        else:
            token = y.check_token(stored_token)
            if token != stored_token:
                token_store.set(stored_token_name, token)

        self.y = y
        self.token = token
コード例 #10
0
ファイル: test_storage.py プロジェクト: allanice001/RJ45
 def test_cannot_retrieve_token_if_path_doesnt_exist(self):
     directory = tempfile.mkdtemp()
     store = FileTokenStore(directory)
     store.set('foo', '?key=%s&oauth_token=some-oauth-token&'\
               'oauth_token_secret=some-token-secret' % 'some-token')
     os.remove(store.get_filepath('foo'))
     self.assertTrue(store.get('foo') is None)
コード例 #11
0
ファイル: test_storage.py プロジェクト: allanice001/RJ45
 def test_retrieves_token_from_filesystem(self):
     directory = tempfile.mkdtemp()
     store = FileTokenStore(directory)
     store.set('foo', '?key=%s&oauth_token=some-oauth-token&'\
               'oauth_token_secret=some-token-secret' % 'some-token')
     token = store.get('foo')
     self.assertTrue('some-token' in token.to_string())
コード例 #12
0
def get_token():
    path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'cache'))
    token_store = FileTokenStore(path, secret=YAHOO_STORAGE_SECRET)
    stored_token = token_store.get('josh')
    y3 = yql.ThreeLegged(YAHOO_CONSUMER_KEY, YAHOO_CONSUMER_SECRET)
    if stored_token is None:
        query = 'select * from social.connections where owner_guid=me'
        request_token, auth_url = y3.get_token_and_auth_url()
        print "Go to {0}".format(auth_url)
        verifier = raw_input("Please put in token that Yahoo gives you")
        access_token = y3.get_access_token(request_token, verifier)
        token_store.set('josh', access_token)
        return access_token
    else:
        token = y3.check_token(stored_token)
        if token != stored_token:
            token_store.set('josh', token)
        return token
コード例 #13
0
ファイル: ffball_yql2.py プロジェクト: wimsy/ffball
def refresh_data():
  """ Call with no parameters. Returns a list of JSON rows with score data. """
  auth_vals = get_authvals_csv('auth.csv')
  y = yql.ThreeLegged(auth_vals['consumer_key'], auth_vals['consumer_secret'])
  path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'cache'))
  token_store = FileTokenStore(path, secret=auth_vals['file_token_secret'])
  stored_token = token_store.get('foo')

  if not stored_token:
    request_token, auth_url = y.get_token_and_auth_url()
    webbrowser.open(auth_url)
    verifier = raw_input('Please enter your PIN:')
    access_token = y.get_access_token(request_token, verifier)
    token_store.set('foo', access_token)
  else:
    # Check access_token is within 1hour-old and if not refresh it
    # and stash it
    access_token = y.check_token(stored_token)
    if access_token != stored_token:
        token_store.set('foo', access_token)

  teams_query = "select * from fantasysports.teams where league_key=%s" % str(auth_vals['league_key'])
  teams_yql = y.execute(teams_query, token=access_token)
  team_names = []
  for team in teams_yql.rows:
    team_names.append(team['name'])

  scoreboards_query = "select * from fantasysports.leagues.scoreboard where league_key='273.l.103279' and week in (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16)"
  scoreboards_yql = y.execute(scoreboards_query, token=access_token)
  current_week = int(scoreboards_yql.rows[-1]['current_week'])
  scoreboards = scoreboards_yql.rows[0:current_week-1]
  
  standings_query = "select * from fantasysports.leagues.standings where league_key='273.l.103279'"
  standings_yql = y.execute(standings_query, token=access_token)
  standings = standings_yql.rows

  pickle.dump(scoreboards, open('scoreboards.pkl', 'w'))
  pickle.dump(standings, open('standings.pkl', 'w'))
  return scoreboards, standings
コード例 #14
0
ファイル: yahoo_auth.py プロジェクト: jmc856/Webpage
def get_yahoo_auth():
    try:
        f = open('/var/Webpage/Yahoo_Fantasy/passwords_yahoo.txt', 'r')  # if running on server
    except IOError:
        f = open('passwords_yahoo.txt', 'r')

    text = f.read()
    d = ast.literal_eval(text)

    consumer_key = d['consumer_key']
    consumer_secret = d['consumer_secret']

    y3 = yql.ThreeLegged(consumer_key, consumer_secret)
    PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
    _cache_dir = os.path.expanduser(PROJECT_ROOT)

    if not os.access(_cache_dir, os.R_OK):
        os.mkdir(_cache_dir)
    token_store = FileTokenStore(_cache_dir, secret=consumer_secret)

    stored_token = token_store.get('foo')

    if not stored_token:
        # get access token, visit website and grant yourself access to league information
        request_token, auth_url = y3.get_token_and_auth_url()
        print "Visit url %s and get a verifier string" % auth_url
        verifier = raw_input("Enter the code: ")
        token = y3.get_access_token(request_token, verifier)
        token_store.set('foo', token)

    else:
        # Check access_token is within 1hour-old and if not refresh it and stash it
        token = y3.check_token(stored_token)
        if token != stored_token:
            token_store.set('foo', token)

    return token, y3
    def __init__(self, user_input_league_id=None, user_input_chosen_week=None):
        # config vars
        self.config = ConfigParser()
        self.config.read("config.ini")
        if user_input_league_id:
            self.league_id = user_input_league_id
        else:
            self.league_id = self.config.get(
                "Fantasy_Football_Report_Settings", "chosen_league_id")

        # verification output message
        print(
            "Generating fantasy football report for league with id: %s (report generated: %s)\n"
            % (self.league_id, "{:%Y-%b-%d %H:%M:%S}".format(
                datetime.datetime.now())))

        # yahoo oauth api (consumer) key and secret
        with open("./authentication/private.txt", "r") as auth_file:
            auth_data = auth_file.read().split("\n")
        consumer_key = auth_data[0]
        consumer_secret = auth_data[1]

        # yahoo oauth process
        self.y3 = yql.ThreeLegged(consumer_key, consumer_secret)
        _cache_dir = self.config.get("OAuth_Settings", "yql_cache_dir")
        if not os.access(_cache_dir, os.R_OK):
            os.mkdir(_cache_dir)

        token_store = FileTokenStore(_cache_dir, secret="sasfasdfdasfdaf")
        stored_token = token_store.get("foo")

        if not stored_token:
            request_token, auth_url = self.y3.get_token_and_auth_url()
            print("Visit url %s and get a verifier string" % auth_url)
            verifier = raw_input("Enter the code: ")
            self.token = self.y3.get_access_token(request_token, verifier)
            token_store.set("foo", self.token)

        else:
            print("Verifying token...\n")
            self.token = self.y3.check_token(stored_token)
            if self.token != stored_token:
                print("Setting stored token!\n")
                token_store.set("foo", self.token)
        '''
        run base yql queries
        '''
        # get fantasy football game info
        game_data = self.yql_query(
            "select * from fantasysports.games where game_key='nfl'")
        # unique league key composed of this year's yahoo fantasy football game id and the unique league id
        self.league_key = game_data[0].get("game_key") + ".l." + self.league_id
        print("League key: %s\n" % self.league_key)

        # get individual league roster
        roster_data = self.yql_query(
            "select * from fantasysports.leagues.settings where league_key='" +
            self.league_key + "'")

        roster_slots = collections.defaultdict(int)
        self.league_roster_active_slots = []
        flex_positions = []

        for position in roster_data[0].get("settings").get(
                "roster_positions").get("roster_position"):

            position_name = position.get("position")
            position_count = int(position.get("count"))

            count = position_count
            while count > 0:
                if position_name != "BN":
                    self.league_roster_active_slots.append(position_name)
                count -= 1

            if position_name == "W/R":
                flex_positions = ["WR", "RB"]
            if position_name == "W/R/T":
                flex_positions = ["WR", "RB", "TE"]

            if "/" in position_name:
                position_name = "FLEX"

            roster_slots[position_name] += position_count

        self.roster = {"slots": roster_slots, "flex_positions": flex_positions}

        # get data for all teams in league
        self.teams_data = self.yql_query(
            "select * from fantasysports.teams where league_key='" +
            self.league_key + "'")

        # get data for all league standings
        self.league_standings_data = self.yql_query(
            "select * from fantasysports.leagues.standings where league_key='"
            + self.league_key + "'")
        self.league_name = self.league_standings_data[0].get("name")
        # TODO: incorporate winnings into reports
        # entry_fee = league_standings_data[0].get("entry_fee")

        if user_input_chosen_week:
            chosen_week = user_input_chosen_week
        else:
            chosen_week = self.config.get("Fantasy_Football_Report_Settings",
                                          "chosen_week")
        try:
            if chosen_week == "default":
                self.chosen_week = str(
                    int(self.league_standings_data[0].get("current_week")) - 1)
                # self.chosen_week = "1"
            elif 0 < int(chosen_week) < 18:
                if 0 < int(chosen_week) <= int(
                        self.league_standings_data[0].get("current_week")) - 1:
                    self.chosen_week = chosen_week
                else:
                    incomplete_week = raw_input(
                        "Are you sure you want to generate a report for an incomplete week? (y/n) -> "
                    )
                    if incomplete_week == "y":
                        self.chosen_week = chosen_week
                    elif incomplete_week == "n":
                        raise ValueError(
                            "It is recommended that you not generate a report for an incomplete week."
                        )
                    else:
                        raise ValueError(
                            "Please only select 'y' or 'n'. Try running the report generator again."
                        )
            else:
                raise ValueError(
                    "You must select either 'default' or an integer from 1 to 17 for the chosen week."
                )
        except ValueError:
            raise ValueError(
                "You must select either 'default' or an integer from 1 to 17 for the chosen week."
            )
コード例 #16
0
ファイル: Live_Updates.py プロジェクト: SamProtas/Webpage
y3 = yql.ThreeLegged(consumer_key, consumer_secret)
_cache_dir = os.path.expanduser(PROJECT_ROOT)

if not os.access(_cache_dir,os.R_OK):
	os.mkdir(_cache_dir)
token_store = FileTokenStore(_cache_dir, secret=consumer_secret)

stored_token = token_store.get('foo')

if not stored_token:
	#get access token, visit website and grant yourself access to league information
	request_token, auth_url = y3.get_token_and_auth_url()
	print "Visit url %s and get a verifier string" % auth_url
	verifier = raw_input("Enter the code: ") 
	token = y3.get_access_token(request_token, verifier)
	token_store.set('foo', token)

else:
	# Check access_token is within 1hour-old and if not refresh it and stash it
	token = y3.check_token(stored_token)
	if token != stored_token:
		token_store.set('foo', token)
##########################################################################################################################################################
##########################################################################################################################################################
##########################################################################################################################################################

def career_record(table, mobile, carrier, manager, opponent, week):
	#career record against that opponent#
	#Gets total career matchups (including playoffs)
	x = int(pd.read_sql("SELECT COUNT(*) AS total FROM %s WHERE (manager1_name = %s AND manager2_name = %s AND team1_points>0) OR (manager2_name = %s AND manager1_name = %s AND team1_points>0)" % (table, manager, opponent, manager, opponent), conn)['total'][0])
	#Gets total matchups won by manager
コード例 #17
0
token_store = FileTokenStore(_cache_dir, secret='insert secret here')


stored_token = token_store.get('foo')

if not stored_token:

    # Do the dance

    request_token, auth_url = y3.get_token_and_auth_url()

    print "Visit url %s and get a verifier string" % auth_url

    verifier = raw_input("Enter the code: ")
    token = y3.get_access_token(request_token, verifier)
    token_store.set('foo', token)

else:

    # Check access_token is within 1hour-old and if not refresh it
    # and stash it

    token = y3.check_token(stored_token)

    if token != stored_token:

        token_store.set('foo', token)



コード例 #18
0
class ddfImportTools:
    def __init__(self, output_file, logger):
        # TODO: Find a better place for this. Encrypted?
        consumer_key = (
            "dj0yJmk9cERpbXB3enRMdkVEJmQ9WVdrOVQzUk5OR2h0TXpRbWNHbzlNak0yTWpjNE5qWXkmcz1jb25zdW1lcnNlY3JldCZ4PTVl"
        )
        # TODO: Find a better place for this. Encrypted?
        consumer_secret = "649bf450f84a086f0112c2584e71e34fadbf798b"

        with open("data/defense_list.json", "rb") as fp:
            self.defense_list = json.load(fp)

        with open("data/team_abbr.json", "rb") as fp:
            self.team_names_abbr = json.load(fp)

        with open("data/player_mapped_names.json", "rb") as fp:
            self.player_mismatch_names = json.load(fp)

        self.y3 = yql.ThreeLegged(consumer_key, consumer_secret)

        if getattr(sys, "frozen", None):
            basedir = os.path.dirname(sys.argv[0])
        else:
            basedir = os.path.dirname(__file__)

        self.all_picked_players = []
        my_path = os.path.join(basedir, "")
        self.token_store = FileTokenStore(my_path, consumer_secret)
        stored_token = self.token_store.get("foo")
        self.request_token, self.auth_url = self.y3.get_token_and_auth_url()
        self.sql_con = lite.connect("data/playerDB.db")
        self.output_file = output_file
        self.logger = logger

        if not stored_token:
            self.authorized = 0
            self.authorized_message = "No access token found"
        else:
            # Check access_token is within 1hour-old and if not refresh it
            # and stash it
            self.logger.info("Stored access token has been found")
            self.access_token = self.y3.check_token(stored_token)
            if self.access_token != stored_token:
                self.logger.info("refreshing access token")
                self.token = self.y3.check_token(stored_token)
                self.token_store.set("foo", self.token)
                self.authorized = 1
                self.authorized_message = "Access token has been refreshed"
                self.logger.info(self.authorized_message)
            else:
                self.authorized_message = "Access token is less than one hour old, no need to refresh"
                self.logger.info(self.authorized_message)
                self.authorized = 1

    def ddf_setup(self, league_id, ddf_file, output_file, user_team):
        """
        Sets up the ddf file by using the ddf_file provided
        The setup section is imported into the output_ddf
        and the draft order is imported. The draft order is
        mostly useless other than the fact that Draft Dominator
        and Lineup Dominator do not like blank draft orders
        """
        old_ddf = open(ddf_file, "r")

        settings_done = 0
        with open(output_file, "a+") as ddffile_setup:
            for line in old_ddf.readlines():
                if settings_done == 0:
                    if line != "[Team Names]\n":
                        match = re.search(r"TeamNumber", line)
                        if match:
                            ddffile_setup.write("TeamNumber=" + user_team + "\n")
                        else:
                            ddffile_setup.write(line)
                    else:
                        settings_done = 1
                elif settings_done == 1:
                    match_pickorder = re.search(r"\[Pick Order\]", line)
                    match_round = re.search(r"Round ", line)
                    if match_pickorder:
                        ddffile_setup.write(line)
                    elif match_round:
                        ddffile_setup.write(line)
                    else:
                        pass
                else:
                    pass
            ddffile_setup.write("\n")

    def get_auth_url(self):
        """
        Opens the default browser and directs the user to the
        authorization web page.
        """
        webbrowser.open(self.auth_url)

    def get_authorization(self, auth_pin):
        """
        Uses auth_pin to complete the authorization process.
        auth_pin is the pin number that is returned once the
        user agrees to authorize the app. The following variables
        are defined:
        oauth_verifier this is the auth pin
        self.access_token This is the request token
        self.authorized This will be 0 or 1 0 = no, 1 = yes
        self.authorized_message Message used for to display in app
        """
        oauth_verifier = auth_pin
        self.access_token = self.y3.get_access_token(self.request_token, oauth_verifier)
        self.token_store.set("foo", self.access_token)
        self.authorized = 1
        self.authorized_message = "Access token created. App is now authorized to access your Fantasy Football Data"

    def team_count(self, league_id):
        league_id = league_id
        num_teams_query = self.y3.execute(
            """select * from fantasysports.leagues where league_key='nfl.l.%s'""" % (league_id), token=self.access_token
        )
        num_teams_result = num_teams_query.results["league"]["num_teams"]
        self.num_teams = int(num_teams_result)

    def write_team_names(self, num_teams, league_id):
        ddffile = open(self.output_file, "a+")
        ddffile.write("[Team Names]" + "\n")

        for x in range(0, num_teams):
            team_num = x + 1
            team_info = self.y3.execute(
                """select * from fantasysports.teams where team_key='nfl.l.%s.t.%s'""" % (league_id, str(team_num)),
                token=self.access_token,
            )
            team_name = team_info.results["team"]["name"]
            ddffile.write("Team%s" % (str(team_num)) + "=" + team_name.encode("utf-8") + "\n")
        team_num = team_num + 1
        ddffile.write("Team%s" % (str(team_num)) + "=" + "\n")
        ddffile.write("\n")

    def team_roster(self, league_id, team_id):

        trailing_text = " , , /0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n"
        ddffile = open(self.output_file, "a+")
        ddffile.write("[Team%s]" % (team_id) + "\n")

        team = self.y3.execute(
            "select * from fantasysports.teams.roster where team_key='nfl.l.%s.t.%s'" % (league_id, team_id),
            token=self.access_token,
        )
        # This is a list embedded with dictionary entries for players data
        player_list = team.results["team"]["roster"]["players"]["player"]
        cur = self.sql_con.cursor()
        no_match = 0
        team = []
        counter = 0

        for x in player_list:
            counter = counter + 1
            cur.execute("SELECT * FROM players WHERE first=? AND last=?", (x["name"]["first"], x["name"]["last"]))
            rows = cur.fetchall()

            if len(rows) == 1:
                ddffile.write("P" + str(counter) + "=" + rows[0][0] + ", ," + rows[0][3] + trailing_text)
                self.all_picked_players.append(rows[0][0] + ", ," + rows[0][3] + trailing_text)
                self.logger.info(
                    "Found an exact match for!"
                    + " "
                    + x["name"]["first"]
                    + " "
                    + x["name"]["last"]
                    + " "
                    + x["editorial_team_abbr"].lower()
                )

            elif len(rows) > 1:
                match_found = 0
                for matched in rows:
                    if matched[4] == self.team_names_abbr[x["editorial_team_abbr"].lower()]:
                        self.all_picked_players.append(matched[0] + ", ," + rows[0][3] + trailing_text)
                        ddffile.write("P" + str(counter) + "=" + matched[0] + ", ," + rows[0][3] + trailing_text)
                        match_found = match_found + 1
                    else:
                        pass
                if match_found == 0:
                    self.logger.warning(
                        "Match not found for multiple result!"
                        + " "
                        + x["name"]["first"]
                        + " "
                        + x["name"]["last"]
                        + " "
                        + x["editorial_team_abbr"].lower()
                    )
                else:
                    self.logger.info(
                        "Match found for multiple result no problem to report here!"
                        + " "
                        + x["name"]["first"]
                        + " "
                        + x["name"]["last"]
                        + " "
                        + x["editorial_team_abbr"].lower()
                    )

            elif len(rows) == 0:
                # This should be a defense, if not we have a mismatched player
                if x["name"]["full"] in self.defense_list:
                    cur.execute(
                        "SELECT * FROM players WHERE first='%s' AND team='%s'"
                        % (x["name"]["first"], self.team_names_abbr[x["editorial_team_abbr"].lower()])
                    )
                    rows = cur.fetchall()
                    ddffile.write("P" + str(counter) + "=" + rows[0][0] + ", ," + rows[0][3] + trailing_text)
                    self.all_picked_players.append(rows[0][0] + ", ," + rows[0][3] + trailing_text)
                    self.logger.info("Match found, this is a defense!" + " " + x["name"]["full"])

                elif x["name"]["full"] in self.player_mismatch_names:
                    cur.execute(
                        "SELECT * FROM players WHERE first='%s' AND last='%s'"
                        % (
                            self.player_mismatch_names[x["name"]["full"]][0],
                            self.player_mismatch_names[x["name"]["full"]][1],
                        )
                    )
                    rows = cur.fetchall()
                    ddffile.write("P" + str(counter) + "=" + rows[0][0] + ", ," + rows[0][3] + trailing_text)
                    self.all_picked_players.append(rows[0][0] + ", ," + rows[0][3] + trailing_text)
                    self.logger.info(
                        "Match found in the misspelled list!"
                        + " "
                        + x["name"]["first"]
                        + " "
                        + x["name"]["last"]
                        + " "
                        + x["editorial_team_abbr"].lower()
                    )

                else:
                    no_match = no_match + 1
                    self.logger.warning(
                        "Match not found!"
                        + " "
                        + x["name"]["first"]
                        + " "
                        + x["name"]["last"]
                        + " "
                        + x["editorial_team_abbr"].lower()
                    )

        ddffile.write("\n")

    def importSchedule(self, league_id, team_id):
        week_list = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17"]
        week_num_count = 0
        with open(self.output_file, "a+") as fp:
            fp.write("[Schedule]\n")

        for week_num in week_list:
            schedule_query = self.y3.execute(
                "select scoreboard.matchups.matchup from fantasysports.leagues.scoreboard where league_key='nfl.l.%s' and week='%s'"
                % (league_id, week_num),
                token=self.access_token,
            )
            result_list = schedule_query.rows

            for row in result_list:

                if (
                    team_id == row["scoreboard"]["matchups"]["matchup"]["teams"]["team"][0]["team_id"]
                    or team_id == row["scoreboard"]["matchups"]["matchup"]["teams"]["team"][1]["team_id"]
                ):
                    # The correct matchup has been found

                    if team_id != row["scoreboard"]["matchups"]["matchup"]["teams"]["team"][0]["team_id"]:
                        with open(self.output_file, "a+") as fp:
                            fp.write(
                                "Week"
                                + week_num
                                + "="
                                + row["scoreboard"]["matchups"]["matchup"]["teams"]["team"][0]["team_id"]
                                + "\n"
                            )
                            week_num_count = week_num_count + 1

                    elif team_id != row["scoreboard"]["matchups"]["matchup"]["teams"]["team"][1]["team_id"]:
                        with open(self.output_file, "a+") as fp:
                            fp.write(
                                "Week"
                                + week_num
                                + "="
                                + row["scoreboard"]["matchups"]["matchup"]["teams"]["team"][1]["team_id"]
                                + "\n"
                            )
                            week_num_count = week_num_count + 1

                    else:
                        self.logger.warning(
                            "There was an error creating the schedule. Please report this to the developer"
                        )

                else:
                    pass
        week_num_count = week_num_count + 1
        for no_schedule in range(week_num_count, 21):
            with open(self.output_file, "a+") as fp:
                fp.write("Week" + str(no_schedule) + "=0\n")

        with open(self.output_file, "a+") as fp:
            fp.write("\n")

    def dummyDraftSummary(self):
        counter = 1
        with open(self.output_file, "a+") as ddffile:
            ddffile.write("[DraftSummary]\n")
            for player in self.all_picked_players:
                ddffile.write("D" + str(counter) + "=" + player)
                counter = counter + 1

            ddffile.write("\n")
コード例 #19
0
ファイル: test_storage.py プロジェクト: allanice001/RJ45
 def test_saves_token_string_to_filesystem(self):
     directory = tempfile.mkdtemp()
     store = FileTokenStore(directory)
     store.set('foo', '?key=some-token')
     with open(store.get_filepath('foo')) as stored_file:
         self.assertTrue('some-token' in stored_file.read())
コード例 #20
0
ファイル: draft_results.py プロジェクト: SamProtas/Webpage
y3 = yql.ThreeLegged(consumer_key, consumer_secret)
_cache_dir = os.path.expanduser(PROJECT_ROOT)

if not os.access(_cache_dir, os.R_OK):
    os.mkdir(_cache_dir)
token_store = FileTokenStore(_cache_dir, secret=consumer_secret)

stored_token = token_store.get("foo")

if not stored_token:
    # get access token, visit website and grant yourself access to league information
    request_token, auth_url = y3.get_token_and_auth_url()
    print "Visit url %s and get a verifier string" % auth_url
    verifier = raw_input("Enter the code: ")
    token = y3.get_access_token(request_token, verifier)
    token_store.set("foo", token)

else:
    # Check access_token is within 1hour-old and if not refresh it and stash it
    token = y3.check_token(stored_token)
    if token != stored_token:
        token_store.set("foo", token)

###################
# END AUTHENTICATION
###################


# CREATE FUNCTION TO SIFT THROUGH QUERY AND GET DRAFT DATA FOR A GENERIC LEAGUE