Hello,

My system is a Windows system and I’m writing my code in Python 3.7 Jupyter Notebook.
Currently, I’m using the code from the Twitter lab Github.

I create .env file in the same folder of the code.
berertwitter.IPYNB
As this picture


Here is my.env file

I guess the problem with the quotation marks.

import requests
import os
import json


from dotenv import load_dotenv
load_dotenv()


# To set your enviornment variables in your terminal run the following line:
 #export 'BEARER_TOKEN'='<your_bearer_token>'
print(os.environ)

def auth():
    return os.environ.get('BEARER_TOKEN')


def create_url():
    return "https://api.twitter.com/2/tweets/sample/stream"


def create_headers(bearer_token):
    headers = {"Authorization": "Bearer {}".format(bearer_token)}
    return headers


def connect_to_endpoint(url, headers):
    response = requests.request("GET", url, headers=headers, stream=True)
    print(response.status_code)
    for response_line in response.iter_lines():
        if response_line:
            json_response = json.loads(response_line)
            print(json.dumps(json_response, indent=4, sort_keys=True))
    if response.status_code != 200:
        raise Exception(
            "Request returned an error: {} {}".format(
                response.status_code, response.text
            )
        )


def main():
    bearer_token = auth()
    url = create_url()
    headers = create_headers(bearer_token)
    timeout = 0
    while True:
        connect_to_endpoint(url, headers)
        timeout += 1


if __name__ == "__main__":
    main()

The error I got as follows
401
{
“detail”: “Unauthorized”,
“status”: 401,
“title”: “Unauthorized”,
“type”: “about:blank”
}

Please any advice for solving this issue …

first make sure it was installed correctly,

pip install python-dotenv

Or, in a notebook cell you can do this with an exclamation mark at the start of the command (only needs to be done once)

!pip install python-dotenv

After that you sometimes need to restart the notebook kernel.

Also, - i notice you have file type extensions hidden. I suspect your env file is not named correctly. It appears it’s called .env.txt which will fail to load. Turn on showing file extensions in windows and change it to .env

2 Likes

You are right the file was text not .env
Thank you

2 Likes