Forums

RuntimeError: A secret key is required to use CSRF.

I use dotenv to access stored environmentals in a .env in a directory with my project files. The flask config and init run with no errors and the server displays my home page when I type my custom domain name. The problem is when I try fo load a flask-wtf form into a template, I get the above error. What will resolve this issue?

I created my vitual environment in a bash console from the dashboard Here is my wsgi.py file:

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

# add your project directory to the sys.path
project_home = '/home/trapdoor/fishing/'
if project_home not in sys.path:
    sys.path = [project_home] + sys.path

# import flask app but need to call it "application" for WSGI to work

from daf import create_app # noqa
application = create_app()

[edit by admin for formatting]

Looks like some configuration is missing. It's hard to tell more without more information.

Ok, here's some more information: The virtual environment that I have includes the fishing directory and a readme file. The daf directory is in the only thing in the fishing directory. The daf directory holds the app files: (init.py,, pycache, admin, buy_sell, config.py, main, models.py, moon.py, recipes, requirements.txt, static, templates, users, waters and .env.) The app runs and displays the home.html in the main blueprint, but the environmental variables seem unreachable from any of the routes. Does that help?

See https://help.pythonanywhere.com/pages/environment-variables-for-web-apps/

When I type echo $(SOME-ENVIRONMENTAL-VARIABLE) in my virtualev, the terminal displays the value. When I type echo $(SECRET_KEY) I get no error but a blank line. When my virtual environment gets activated, bash displays:

21:30 ~/fishing (main)$ workon fisher
bash: !083023: command not found
[1]+  Done                    SECRET_KEY=KJr!9VvU5#fFoK

This is not the key in the .env file. Should I delete /virtualenvs and any others I've tries and start over?

[edit by admin for formatting]

Yes that is weird. Maybe deleting and reinstalling your virtualenv will help.

But I think you've got to the root of the problem. The SECRET_KEY environment variable is not available in your python code. - https://stackoverflow.com/questions/47687307/how-do-you-solve-the-error-keyerror-a-secret-key-is-required-to-use-csrf-whe

Just to let you know, problem solved by recreating the venv and locating the config.py and .env files in the working directory. The app is from a creat_app function in the project directory. Passing thet config class as a parameter in the create_app allowed the process to complete. I will still need to access other key:values in the .env for api functions to work. Not sure yet quite how that will work. If you have any Ideas please let me know, thanks you.