Skip to content

Commit

Permalink
Various fixes to un-fuck handling of file paths when importing module…
Browse files Browse the repository at this point in the history
…s within each other

The use of manually building file paths was causing various FileNotFoundError problems. I decided to instead use the os.path module to let the paths build themselves using the location of __file__
  • Loading branch information
Phrancis committed Aug 21, 2019
1 parent 0c972af commit 96ec375
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 3 deletions.
File renamed without changes.
13 changes: 10 additions & 3 deletions get_twitter_api.py → api/get_twitter_api.py
@@ -1,17 +1,23 @@
import json
import os
from typing import Dict, TextIO
from tweepy import API
from tweepy import OAuthHandler

PATH_TO_APP_DATA = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'app_data')

def get_twitter_api(file_path: str = 'app_data/twitter_api_keys.json') -> API:

def get_twitter_api(file_path: str = os.path.join(PATH_TO_APP_DATA, 'twitter_api_keys.json')) -> API:
"""
Authenticates Twitter API using stored values, and returns an API instance.
:param file_path: The path to app_data/twitter_api_keys.json
:return: A Twitter API instance from tweepy.
"""
try:
_file: TextIO
_keys: Dict = dict()
print(os.path.dirname(__file__))
print(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'app_data', 'twitter_api_keys.json'))
with open(file_path, 'r') as _file:
_keys = json.load(_file)
except FileNotFoundError as _err:
Expand Down Expand Up @@ -39,10 +45,11 @@ def get_current_user_json_field(field_name: str) -> object:
:param field_name: Name of the JSON field
:return: Value of the JSON field
"""
return api.me()._json[field_name]
_api = get_twitter_api(os.path.join(PATH_TO_APP_DATA, 'twitter_api_keys.json'))
return _api.me()._json[field_name]


if __name__ == '__main__':
api: API = get_twitter_api()
api: API = get_twitter_api(os.path.join('app_data', 'twitter_api_keys.json'))
# Query the API for self data to make sure it's working
print(f'Current API user: {get_current_user_json_field("screen_name")}')
File renamed without changes.
22 changes: 22 additions & 0 deletions followers/extract_all_user_followers.py
@@ -0,0 +1,22 @@
import datetime
import os
from api import get_twitter_api as api

PATH_TO_APP_DATA = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'app_data')


def extract_all_follower_user_ids(screen_name: str = '') -> None:
"""
Get all of an account's followers' user IDs and write them to a JSON file with today's date.
:param screen_name:
:return:
"""
_api = api.get_twitter_api(os.path.join(PATH_TO_APP_DATA, 'twitter_api_keys.json'))
if screen_name == '':
screen_name = api.get_current_user_json_field('screen_name')
_file_name = f'follower_user_ids {screen_name} {datetime.date.today()}'
print(_file_name)


if __name__ == '__main__':
extract_all_follower_user_ids()

0 comments on commit 96ec375

Please sign in to comment.