Utility function for initializing osometweet API
mr-devs opened this issue · 0 comments
mr-devs commented
Very often it happens that I just want to make a single call to a function to see what it returns, etc.
As a result, I find myself typing out the below preamble before doing anything with the API all the time and it has become my least favorite thing about the package. 👼
# Initialize the OSoMeTweet object
bearer_token = os.environ.get("TWITTER_BEARER_TOKEN")
oauth2 = osometweet.OAuth2(bearer_token=bearer_token)
ot = osometweet.OsomeTweet(oauth2)
A simple solution is to just set up a utility function that does this for us by drawing on the user's environment variables. I am imagining one for both authorization contexts.
- App (bearer token) context
- Wiki example
- User context
- Wiki example
I imagine a loading function, as well as an initializing function for each context. Here is a rough example for the App context...
def load_bearer_token(env_key: str = "TWITTER_BEARER_TOKEN") -> str:
"""
Load Twitter Keys from Local Environment.
Parameters:
-----------
- env_key (str) : The name of the environment variable for your Twitter bearer token. (default = "TWITTER_BEARER_TOKEN")
"""
# Set Twitter tokens/keys.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
print("Loading bearer token...")
bearer_token = os.environ.get(env_key, None)
if bearer_token is None:
raise Exception(
f"No environment variable named `{env_key}`! "
"Make sure to set this from your terminal via:\n\n"
f"\t --> '{env_key}'='<your_twitter_bearer_token>' "
)
return bearer_token
def initialize_osometweet(
env_key: str = "TWITTER_BEARER_TOKEN",
manage_rate_limits: bool = True
) -> osometweet.api.OsomeTweet:
"""
Return an authorized osometweet API object
from which we can make API calls.
Parameters:
----------
- env_key (str) : The name of the environment variable for your Twitter bearer token. (default = "TWITTER_BEARER_TOKEN")
"""
print("Initializing osometweet with oauth2a authentication...")
bearer_token = load_bearer_token(env_key)
oauth2 = osometweet.OAuth2(
bearer_token=bearer_token,
manage_rate_limits=manage_rate_limits
)
return osometweet.OsomeTweet(oauth2)
This approach allows users a bunch of freedom like:
- Calling the loading functions on their own and initializing the standard way, if they want
- Using whatever environment variables the user has set
- Controling the rate limiting option from the initializing function like standard approach
- If the user set it up so that their environment variable matches the default, they can simply call
initialize_osometweet()
with no input and get anosometweet.api.OsomeTweet
object right away