Forums

trouble getting .env variables into my main script

Hi,

I've been beating my head against a wall for about 2 hours trying to figure out why this won't work. Whenever I POST to my script I hit the passphrase protection error I have set up even though the passphrase I'm POSTing and the passphrase I have stored are the same (I don't think double quotes (") vs single quotes (') should matter, but maybe I'm mistaken about that). The most annoying part is when I call the script in bash with a print statement for one of the my secret variables, it shows up just fine.

from main.py:

from flask import Flask, request, render_template
import config, json, requests
import datetime as dt
from pytz import timezone
import alpaca_trade_api as tradeapi
import sys
import time

app = Flask(__name__)

QUOTE_API_KEY = config.QUOTE_API_KEY
QUOTE_API_SECRET = config.QUOTE_API_SECRET
WEBHOOK_PASSPHRASE = config.WEBHOOK_PASSPHRASE

@app.route('/webhook', methods=['POST'])
def webhook():
    try:
        webhook_message = json.loads(request.data)

        if webhook_message['passphrase'] != WEBHOOK_PASSPHRASE:
        return {
                    'code': 'error',
                    'message': 'nice try buddy'
                }

from config.py, located at /home/inkheist/tqqq-swing/config.py:

import os
from dotenv import load_dotenv
load_dotenv()

DISCORD_WEBHOOK_URL_LIVE = os.getenv("DISCORD_WEBHOOK_URL_LIVE")
DISCORD_WEBHOOK_URL_TEST = os.getenv("DISCORD_WEBHOOK_URL_TEST")

QUOTE_API_KEY = os.getenv("QUOTE_API_KEY")
QUOTE_API_SECRET = os.getenv("QUOTE_API_SECRET")

WEBHOOK_PASSPHRASE = os.getenv("WEBHOOK_PASSPHRASE")

from my .env file, located at /home/inkheist/tqqq-swing/.env:

DISCORD_WEBHOOK_URL_LIVE="######"
DISCORD_WEBHOOK_URL_TEST="######"
QUOTE_API_KEY='#####'
QUOTE_API_SECRET='######'
WEBHOOK_PASSPHRASE="####"

from WSGI.py:

import sys
path = '/home/inkheist/tqqq-swing'
if path not in sys.path:
    sys.path.append(path)

from main import app as application

import os
from dotenv import load_dotenv
project_folder = os.path.expanduser('~/')  # adjust as appropriate
load_dotenv(os.path.join(project_folder, '.env'))

If I put the passphrase directly into my script it works just fine, but for some reason it won't read in from my .env file. Any help is appreciated!

edit: updated code as it currently is

Try removing the spaces in your .env file

Didn't seem to make a difference.

You have also a typo in os.path.expanduser(' ~/') -- it will return " ~". You should remove the initial space.

I just fixed that too, but it's still not working without putting my .env variables directly into main.py

Not sure if it helps, but this is my traceback:

Traceback (most recent call last):
File "/home/inkheist/.virtualenvs/venv/lib/python3.10/site-packages/flask/app.py", line 2073, in wsgi_app
response = self.full_dispatch_request()
File "/home/inkheist/.virtualenvs/venv/lib/python3.10/site-packages/flask/app.py", line 1520, in 
full_dispatch_request
return self.finalize_request(rv)
File "/home/inkheist/.virtualenvs/venv/lib/python3.10/site-packages/flask/app.py", line 1539, in 
finalize_request
response = self.make_response(rv)
File "/home/inkheist/.virtualenvs/venv/lib/python3.10/site-packages/flask/app.py", line 1743, in 
make_response
rv.status_code = status
File "/home/inkheist/.virtualenvs/venv/lib/python3.10/site-packages/werkzeug/sansio/response.py", line 151, in status_code
self.status = code  # type: ignore
File "/home/inkheist/.virtualenvs/venv/lib/python3.10/site-packages/werkzeug/sansio/response.py", line 161, in status
raise TypeError("Invalid status argument")
TypeError: Invalid status argument

In only get this error when I reference variables from my .env file, my code functions as it should when I put the variables from my .env directly into my code.

edited to include traceback

What is the response status you set?

That's actually the traceback I get when I send a request to Alpaca, since it's not pulling my API key into main.py either, otherwise I just get the passphrase protection error I have set up.

I was able to solve the problem by replacing my current code in the WSGI file with this one:

import sys
import os
from dotenv import load_dotenv
project_home = '/home/inkheist/tqqq-swing'
if project_home not in sys.path:
    sys.path = [project_home] + sys.path

load_dotenv(os.path.join(project_home, '.env'))

from main import app as application

Not sure why, but I found this code in another help topic: https://www.pythonanywhere.com/forums/topic/14207/ and everything works now. I didn't need to change anything in any other file.

As far as I can tell the only differences are that there's no longer a variable called path that might be interfering with sys.path? And append isn't used to add the home directory to sys.path. And the home directory is referenced directly rather than through the project_folder variable, but I tried referencing the former path variable directly before and it didn't seem to help. Not sure why any of those changes would make a difference, but it fixed my web app.

Glad to hear that you were able to sort it.