Forums

Having trouble with Flask Environmental Variables

I've been following the guide at https://help.pythonanywhere.com/pages/environment-variables-for-web-apps/ , but I'm still running into some difficulties with doing this.

I have successfully run my environmental variables on my local machine, but can't get it to transfer to Python Anywhere. After following the guide I end up with these files.

WSGI File

import sys
import os
from dotenv import load_dotenv

# add your project directory to the sys.path
project_home = u'/home/tkellough/mysite/Teaching_Website'
if project_home not in sys.path:
    sys.path = [project_home] + sys.path

project_folder = os.path.expanduser(u'/home/tkellough/mysite/Teaching_Website/crhs_web')
load_dotenv(os.path.join(project_folder, '.env'))

# import flask app but need to call it "application" for WSGI to work
from run import app as application  # noqa

My routes page

from flask import render_template, url_for, flash, redirect
from crhs_web import app
from crhs_web.forms import RegistrationForm
from crhs_web.scripts import gene_expression
import smtplib
import os

@app.route('/contact', methods=['GET', 'POST'])
def contact():
    form = RegistrationForm()

    if form.validate_on_submit():

        smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
        smtpObj.ehlo()
        smtpObj.starttls()
        smtpObj.login(os.environ.get('CRHS_EMAIL'), os.environ.get('CRHS_PASS'))
        from_address = os.environ.get('CRHS_EMAIL')
        to_address = os.environ.get('CRHS_TOEMAIL')
        if form.phone.data:
            phone = form.phone.data
        else:
            phone = 'Not provided'
        message = f"Name - {form.name.data}\nEmail - {form.email.data}\nPhone - {phone}\nMessage - {form.text.name}"
        smtpObj.sendmail(from_addr=from_address, to_addrs=to_address, msg=message)
        smtpObj.quit()

        flash(f'Thank you for your message, {form.name.data}. You should hear back from me soon!', 'success')
        return redirect(url_for('home'))
    elif form.errors:
        flash(f'Please correct the errors and resubmit the form.', 'danger')
        return render_template('contact.html', title='Contact Me', form=form)
    return render_template('contact.html', title='Contact Me', form=form)

And my .env file

export CRHS_EMAIL=myfirstemailhere
export TO_EMAIL=mysecondemailhere
export CRHS_PASS=mypasswordhere

I'm thinking I may have something wrong with my WSGI folder and not organizing my directories correctly? But I'm honestly not sure. Here is my directory tree. The only file located in 'Teaching_Website' is my run.py file.

── Teaching_Website
│   ├── crhs_web
│   │   ├── __init__.py
│   │   ├── forms.py
│   │   ├── gene_expression.py
│   │   ├── routes.py
│   │   ├── scripts
│   │   │   ├── __init__.py
│   │   │   └── gene_expression.py
│   │   ├── static
----------ALL STATIC FILES
│   │   ├── templates
│   │   │   ├── _formhelpers.html
│   │   │   ├── about.html
│   │   │   ├── announcements.html
│   │   │   ├── biodiversity-quizlet.html
│   │   │   ├── biology-calendar.html
│   │   │   ├── biology-handouts.html
│   │   │   ├── biology-notes.html
│   │   │   ├── biology-videos.html
│   │   │   ├── contact.html
│   │   │   ├── environmental-science-calendar.html
│   │   │   ├── environmental-science-handouts.html
│   │   │   ├── environmental-science-notes.html
│   │   │   ├── environmental-science-videos.html
│   │   │   ├── gene-expression.html
│   │   │   ├── home.html
│   │   │   ├── layout.html
│   │   │   └── survey.html
│   │   └── templates.zip
│   ├── run.py

All of that looks like it's set up properly -- what's the specific error that you're getting that shows that the environment variables aren't being loaded properly?

D'oh! I forgot to include the error. Sorry about that.

After clicking submit on the contact from I get this error.

Internal Server Error

The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

When you get an error page like that, there will be a message with a full stack trace written to the error log for your site -- you can access the error log from the "Web" tab, and the most recent error will be at the bottom. There should be something there that will clarify what the problem is.

Thank you so much for your reply. I accessed the log and was able to resolve the issue.

For anyone else that stumbles upon this later, here was the error I was receiving.

2018-12-28 19:39:14,762: Exception on /contact [POST] Traceback (most recent call last):   File "/usr/lib/python3.7/site-packages/flask/app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()   File "/usr/lib/python3.7/site-packages/flask/app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)   File "/usr/lib/python3.7/site-packages/flask/app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)   File "/usr/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
    raise value   File "/usr/lib/python3.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()   File "/usr/lib/python3.7/site-packages/flask/app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)   File "/home/tkellough/mysite/Teaching_Website/crhs_web/routes.py", line 74, in contact
    smtpObj.login(os.environ.get('CRHS_EMAIL'), os.environ.get('CRHS_PASS'))   File "/usr/lib/python3.7/smtplib.py", line 730, in login
    raise last_exception   File "/usr/lib/python3.7/smtplib.py", line 721, in login
    initial_response_ok=initial_response_ok)   File "/usr/lib/python3.7/smtplib.py", line 642, in auth
    raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8  https://support.google.com/mail/?p=BadCredentials q54sm17931821qtb.64
- gsmtp')

I then created an app password on my gmail account and used that as my environmental variable. (I also had an error with naming the environmental variable that I had to fix in my above code) and it worked like a charm!

Thank you again for your help!

Cool. Glad you could resolve it.

Hey, I have a flask project, which is structured like this run.py (flask app) myapp/ | templates/ assets/ views.py models.py init.py

I have set the nev variables and the app is running, but a Template not found error is being shown. Locally it is working, as I have configured the app using arguments like static_folder and static_url_path. Can you point out the problem with the configuration?

We have a help page about static files...

https://help.pythonanywhere.com/pages/StaticFiles

...and a help page dedicated to debugging of static files problems.

https://help.pythonanywhere.com/pages/DebuggingStaticFiles/