[Flask] Getting 'The CSRF session token is missing.'
Ben Duncan
linux4ms at gmail.com
Wed Nov 13 11:09:57 EST 2019
Can someone tell me what I'm doing wrong ?
I'm trying to build the app in blueprint style, everything seems to work
except
csrf session stuff ....
As usual, thanks ...
The MASTER __init__.py
----------------------------------------------------------------------------------------------------
import sys
from flask import Flask
from flask import session
from flask import g
from flask_sqlalchemy import SQLAlchemy
from flask_session import Session
# CSRF Protection ....
from flask_wtf.csrf import CSRFProtect
from flask_wtf.csrf import CSRFError
# Globally accessible libraries
pgdb = SQLAlchemy()
from sqlalchemy import MetaData
from flask_sqlalchemy import SQLAlchemy
metadata = MetaData()
def create_app():
"""Initialize the core application."""
app = Flask(__name__)
app.config.from_pyfile('config.cfg')
#session.init_app(app)
Session(app)
# initialize Flask extensions
#pgdb = SQLAlchemy()
pgdb.app = app
pgdb.init_app(app)
pgdb.Model.metadata.reflect(pgdb.engine)
class office_table(pgdb.Model):
__table__ = pgdb.Model.metadata.tables['office']
# Initialize Blueprints
with app.app_context():
# Include our Routes
#from . import routes
# Register Blueprints
#from .views.profile import profile
#app.register_blueprint(profile)
# Method 1 - import the home.py file from views
# tghen register it as home.home
from .views.home import home
app.register_blueprint( home )
return app
----------------------------------------------------------------------------------------------------------------
The config file:
import os
from datetime import timedelta
#SECRET_KEY = os.urandom(64)
SECRET_KEY = 'Mars Random Key Stuff'
#SERVER_NAME = 'su-postgres-ben-3.mec.ms.gov:5000'
SERVER_NAME = '10.13.70.47:5000'
# Session management
SESSION_TYPE = 'filesystem'
SESSION_FILE_DIR = 'flask_session'
SESSION_COOKIE_PATH = '/'
SESSION_KEY_PREFIX = 'flsk'
PERMANENT_SESSION_LIFETIME = timedelta(minutes=15)
# Per user config:
# app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=15)
SQLALCHEMY_DATABASE_URI = 'postgres://
flask:flask at 10.13.70.47:7103/ac03303_live'
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_POOL_SIZE = 10
SQLALCHEMY_ECHO = False
# Debugging testing
DEBUG = True
DEVELOPMENT = True
TESTING = True
TEMPLATES_AUTO_RELOAD = True
# SERVER_NAME = ''
# YOUR defined variables go here
APPLICATION = 'MECS APPLICATION'
AUTHOR = 'Ben Duncan'
--------------------------------------------------------------------------------------------------
The run.sh and wsgi.py program:
#!/usr/bin/env python
#
# -*- coding: utf-8 -*-
# SAMPLE TO SHOW FLASK_SQLALCHEMY
# AND HOW TO USE IT !!!
#
import os, sys, string, copy, time
import getopt, cdecimal
from types import *
from datetime import date
sys.modules['decimal'] = cdecimal
# Base wsgi application starter
#from flask import g, session
from mars import create_app
app = create_app()
app.config['SOMETHING'] = 'wsgi.py'
# csrf error
# See : https://flask-wtf.readthedocs.io/en/stable/csrf.html#csrf
# @app.errorhandler(CSRFError)
# def handle_csrf_error(e):
# return render_template('csrf_error.html', reason=e.description), 400
if __name__ == "__main__":
app.run()
Run.sh
#!/bin/sh
#rm -rf flask_session/*
export FLASK_APP=wsgi.py
export FLASK_ENV=development
flask run --host=0.0.0.0 --cert=adhoc
---------------------------------------------------------------------------------------------------------------------------------------------------------
And finally the blueprinted app:
#!/usr/bin/env python
#
# -*- coding: utf-8 -*-
# SAMPLE TO SHOW FLASK_SQLALCHEMY
# AND HOW TO USE IT !!!
#
import os, sys, string, copy, time
import getopt, cdecimal
from types import *
from datetime import date
sys.modules['decimal'] = cdecimal
from pbkdf2 import *
import binascii
from struct import *
import base64
import zlib
import hashlib
import binascii
import hmac
from hashlib import md5, sha1, sha224, sha256, sha384, sha512
TodaysDate = str(date.today())
from flask import Flask, render_template, request, redirect, url_for
from flask import flash, make_response, escape, g
from flask import Blueprint
from flask import session
home = Blueprint('home', __name__)
# mars/views/home
# Flask Specific
from flask import current_app as app
from flask import render_template, flash, redirect, url_for, request, g, \
jsonify, current_app
from flask import get_flashed_messages
from flask.templating import Environment
# Flask_wtf from: https://flask-wtf.readthedocs.io/en/stable/
from flask_wtf import FlaskForm
# Wtforms: https://wtforms.readthedocs.io/en/stable/
from wtforms import Form, BooleanField, StringField, PasswordField,
validators
from wtforms import TextField, TextAreaField, SubmitField, RadioField,
SelectField
from wtforms import DecimalField, BooleanField, IntegerField, FloatField
from wtforms import DateField, DateTimeField
from wtforms.validators import *
from wtforms.widgets import TextArea
from mars import pgdb
class office_table(pgdb.Model):
__table__ = pgdb.Model.metadata.tables['office']
class fund_table(pgdb.Model):
__table__ = pgdb.Model.metadata.tables['fund_type']
class user_table(pgdb.Model):
__table__ = pgdb.Model.metadata.tables['users']
# Login Routine
class LoginForm(FlaskForm):
userid = StringField("userid", validators=[DataRequired()])
user_password = StringField("password: ", validators=[DataRequired()])
@home.route('/')
@home.route('/login', methods=['GET', 'POST'])
def login() :
form = LoginForm()
# Sessions ALWAYS considered new in login ...
session.clear()
...........................................
And the Template:
.... (usual top of form stuff)
<form enctype="multipart/form-data"
method="post"
autocomplete="off"
id="login_form"
role="form"
>
{{ form.csrf_token }}
<div id="namepasswd">
<div style='font-size: 18px ; color: black ; text-align: left;
width:80%;'>
Enter your User ID
<br/>
<input name="userid" type='text' maxlength='40' style='width:100%;'
{% if form.userid.data %}
value='{{ form.userid.data }}'
{% endif %}
>
.... and rest of stuff
*Ben Duncan*
DBA / Chief Software Architect
Mississippi State Supreme Court
Electronic Filing Division
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/flask/attachments/20191113/4fe5f1a2/attachment.html>
More information about the Flask
mailing list