From sidwoodstock at gmail.com Wed Oct 9 13:05:00 2019 From: sidwoodstock at gmail.com (Scott Woodstock) Date: Wed, 9 Oct 2019 10:05:00 -0700 Subject: [Flask] Proper way to refresh Flask-WTF CSRF token? In-Reply-To: References: Message-ID: What ho! A page of my Flask app functions as a single-page web app using mostly ajax requests via jQuery. After being on the page for awhile, inevitably the CSRF token will expire and subsequent HTTP POST requests will fail (Bad Request 400). The docs provide the method of adding the token to the header, but this scenario isn't mentioned. https://flask-wtf.readthedocs.io/en/stable/csrf.html# Rather than increase the token life and hope users don't stay on the page longer than its duration, I opted for creating a jquery / javascript heartbeat to request a new token and an endpoint to generate one and return it. This seems to work how I want it to, but since this scenario is not mentioned anywhere in any docs that I could find, I'm wondering if this is actually accepted practice. Please advise! -------------------- # views.py from flask_wtf.csrf import generate_csrf ... @app.route('/tools/_refresh_csrf/', methods=['GET']) @roles_accepted('admin', 'copy', 'client') def csrf_refresh(): token = generate_csrf() return jsonify(token) // template.html var csrf_token = '{{ csrf_token() }}'; // initial token // refresh the csrf token every 30 minutes var heartbeat = setInterval(function () { $.ajax({ url: '{{ url_for('csrf_refresh') }}', type: 'GET', success: function (response) { csrf_token = response; console.log('new token', csrf_token) }, error: function (jqXHR, textStatus, errorThrown) { console.log(jqXHR, textStatus, errorThrown); alert('Connection with server lost! Please refresh the page.') }, dataType: "json", contentType: "application/json" }); }, 30 * 60 * 1000); // apply the csrf token before each request $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrf_token); // insert custom header } }, }); -------------------- Thank you all for your time! Scott Woodstock -------------- next part -------------- An HTML attachment was scrubbed... URL: From scopensource at gmail.com Wed Oct 9 19:46:30 2019 From: scopensource at gmail.com (Simon Connah) Date: Thu, 10 Oct 2019 00:46:30 +0100 Subject: [Flask] Outputting the results of Python commands to terminal like interface? Message-ID: I've been thinking of a new website I want to build. It will be my first proper Flask website as all my previous websites have used Django. I want to use the freedom that Flask has to output the results of subprocesses on a website when calling code from the Python subprocess module. I'm somewhat confused about how to do this. I know there are various JavaScript terminal emulators around which you can use that allow proper command input and output but since all of my commands will be pre-written Python scripts it seems to be somewhat overkill. Should I just take the results of the subprocess commands, save them to the database and then on page refresh (either trough F5 or via JavaScript) it will show the results of the command(s)? I could then clean up the output and save it again to the database and get rid of most of the superfluous data that isn't needed to store long term. Another option since I am using PostgreSQL is to save the data as JSON and just leave it like that for future recall. Any hints and tips on what I should be doing? From unai at sysbible.org Thu Oct 10 01:51:21 2019 From: unai at sysbible.org (Unai Rodriguez) Date: Thu, 10 Oct 2019 07:51:21 +0200 Subject: [Flask] =?utf-8?q?Outputting_the_results_of_Python_commands_to_t?= =?utf-8?q?erminal_like_interface=3F?= In-Reply-To: References: Message-ID: <198255ec-5087-4f61-a1c7-20dbe1d83b87@www.fastmail.com> Hi Simon, I think one key aspect here is how long it takes for these commands to run. If they are quick (let's say a couple of seconds or less) you could run them synchronously and simply return the output straight to the UI that would be doing AJAX calls. If the commands take some time you might need to make then asynchronously and perhaps use something like Celery to decouple the execution of the command itself with the invocation from the UI. In this case the result could be placed on the database or on some sort of temporary (redis?) storage. I'd imagine the UI requesting the execution of the command via AJAX and perhaps every couple seconds request again to see if the command completed to display the results. I'd also explore websockets since they will let your UI place a request and once the server is done, reply back (without having to poll every few seconds). -- unai On Thu, Oct 10, 2019, at 1:46 AM, Simon Connah wrote: > I've been thinking of a new website I want to build. It will be my first > proper Flask website as all my previous websites have used Django. I > want to use the freedom that Flask has to output the results of > subprocesses on a website when calling code from the Python subprocess > module. > > I'm somewhat confused about how to do this. I know there are various > JavaScript terminal emulators around which youcan use that allow proper > command input and output but since all of my commands will be > pre-written Python scripts it seems to be somewhat overkill. > > Should I just take the results of the subprocess commands, save them to > the database and then on page refresh (either trough F5 or via > JavaScript) it will show the results of the command(s)? > > I could then clean up the output and save it again to the database and > get rid of most of the superfluous data that isn't needed to store long > term. Another option since I am using PostgreSQL is to save the data as > JSON and just leave it like that for future recall. > > Any hints and tips on what I should be doing? > > _______________________________________________ > Flask mailing list > Flask at python.org > https://mail.python.org/mailman/listinfo/flask > From linux4ms at gmail.com Thu Oct 10 08:47:59 2019 From: linux4ms at gmail.com (Ben Duncan) Date: Thu, 10 Oct 2019 07:47:59 -0500 Subject: [Flask] Jina Environment Message-ID: How do you set the jina 'ENVIRONMENT' up when using flask? I'm trying to globally setup the trim_block and the lstrip_block without having to use {%- in the html. What import do I need to do that as well ? Thanks .. *Ben Duncan* DBA / Chief Software Architect Mississippi State Supreme Court Electronic Filing Division -------------- next part -------------- An HTML attachment was scrubbed... URL: From linux4ms at gmail.com Thu Oct 24 10:28:08 2019 From: linux4ms at gmail.com (Ben Duncan) Date: Thu, 24 Oct 2019 09:28:08 -0500 Subject: [Flask] Blueprints Question ... Message-ID: I'm following some blueprints how to and have a question of configuration. I'm using the functional method as outlined here: http://exploreflask.com/en/latest/blueprints.html The question is: In my Top level Application folder that runs the whole thing , I have am using a lot of import libraries: ----------------------------------------------------------------------------------------------------------------------- from flask import Flask, render_template, request, redirect, url_for, flash, make_response, escape, g from flask import get_flashed_messages from flask_session import Session from flask.templating import Environment from flask_sqlalchemy import SQLAlchemy metadata = MetaData() from flask import session # Flask_wtf from: https://flask-wtf.readthedocs.io/en/stable/ from flask_wtf import FlaskForm # CSRF Protection .... from flask_wtf.csrf import CSRFProtect from flask_wtf.csrf import CSRFError 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 ------------------------------------------------------------------------------------------------------------------ In the blueprinted view of: newapp.py I only have : from flask import Blueprint, render_template *The question is:* *Do I need to include the imports I have in the top level in the blueprinted form ?* Thanks ... *Ben Duncan* DBA / Chief Software Architect Mississippi State Supreme Court Electronic Filing Division -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul.christoph.goetze at gmail.com Thu Oct 24 17:21:27 2019 From: paul.christoph.goetze at gmail.com (=?UTF-8?Q?Paul_G=c3=b6tze?=) Date: Thu, 24 Oct 2019 23:21:27 +0200 Subject: [Flask] Blueprints Question ... In-Reply-To: References: Message-ID: <10699d4c-e146-006d-2efd-c9c00cbfff16@gmail.com> Hi Ben, in general you should only need to import the functions or classes or modules you are actually using in the code of the respective module (e.g. your view Python file). There might be an exception to this if you want to provide a certain function/class/module from a special place, so that it can be imported from there. E.g. suppose you have a file (i.e. a module) abc.py were you defined a function do_abc() and a file xyz.py were there is a function do_xyz(). If you would have a main.py and wanted to import both do_abc() and do_xyz() from xyz, then you would need to import do_abc in xyz.py: # in xyz.py: from .abc import do_abc() def do_xyz(): ??? pass and then you could write: # in main.py: from .xyz import do_xyz, do_abc and use both. Otherwise you would need to import them separately: # in main.py: from .abc import do_abc from .xyz import do_xyz Maybe try if sth. breaks if you do not include all the imports. Python will complain about missing imports. If nothing breaks, then it?s fine :) Whether you use the functional or divisional structure should not matter. (If you are using PyCharm for development, then there is the Strg+Shift+Alt+L command that auto-formats your code. You can also optimize/remove not needed imports with this. But I guess a code linter in your editor would also tell you which imports are not used, by printing them gray or the like.) I hope this helps? Cheers, Paul Am 24.10.19 um 16:28 schrieb Ben Duncan: > I'm following some blueprints how to and have a question of configuration. > > I'm using the functional method as outlined here: > http://exploreflask.com/en/latest/blueprints.html > > The question is: > In my Top level Application folder that runs the whole thing , I have > am using? a lot of import libraries: > > ----------------------------------------------------------------------------------------------------------------------- > from flask import Flask, render_template, request, redirect, url_for, > flash, make_response, escape, g > from flask import get_flashed_messages > from flask_session import Session > from flask.templating import Environment > from flask_sqlalchemy import SQLAlchemy > > metadata = MetaData() > from flask import session > > # Flask_wtf from: https://flask-wtf.readthedocs.io/en/stable/ > from flask_wtf import FlaskForm > > # CSRF Protection .... > from flask_wtf.csrf import CSRFProtect > from flask_wtf.csrf import CSRFError > > 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 > ------------------------------------------------------------------------------------------------------------------ > In the blueprinted view of: newapp.py I only have : > > from flask import Blueprint, render_template > > *The question is:* > > *Do I need to include the imports I have in the top level in the > blueprinted form ?* > > Thanks ... > *Ben Duncan* > DBA / Chief Software Architect > Mississippi State Supreme Court > Electronic Filing Division > > _______________________________________________ > Flask mailing list > Flask at python.org > https://mail.python.org/mailman/listinfo/flask -------------- next part -------------- An HTML attachment was scrubbed... URL: From linux4ms at gmail.com Fri Oct 25 08:45:33 2019 From: linux4ms at gmail.com (Ben Duncan) Date: Fri, 25 Oct 2019 07:45:33 -0500 Subject: [Flask] Blueprints Question ... In-Reply-To: <10699d4c-e146-006d-2efd-c9c00cbfff16@gmail.com> References: <10699d4c-e146-006d-2efd-c9c00cbfff16@gmail.com> Message-ID: Thanks all - Especially Paul ... Now, I'm getting the following error: RuntimeError RuntimeError: Working outside of request context. This typically means that you attempted to use functionality that needed an active HTTP request. Consult the documentation on testing for information about how to avoid this problem. Traceback *(most recent call last)* - File "/data/flask/applications/myproject/wtform.py", line *63*, in from setup.setup import setup - File "/data/flask/applications/myproject/setup/setup.py", line *7*, in print "SETUP: Session what is our route? :", session['route'] - File "/opt/rh/python27/root/usr/lib/python2.7/site-packages/werkzeug/local.py", line *378*, in __getitem__ = lambda x, i: x._get_current_object()[i] - File "/opt/rh/python27/root/usr/lib/python2.7/site-packages/werkzeug/local.py", line *307*, in _get_current_object return self.__local() - File "/opt/rh/python27/root/usr/lib64/python2.7/site-packages/flask/globals.py", line *38*, in _lookup_req_object raise RuntimeError(_request_ctx_err_msg) RuntimeError: Working outside of request context. This typically means that you attempted to use functionality that needed an active HTTP request. Consult the documentation on testing for information about how to avoid this problem. My main process, wtform.py looks like this : .... (all the necessary imports for flask and wtforms and sqlalchemy) .... ...... app = Flask(__name__) app.config.from_pyfile('config.cfg') flask_session = Session() flask_session.init_app(app) session = {'modified': False } session = {'route': None } # import blueprinted applications here: from setup.setup import setup # register blueprinted applications here: app.register_blueprint(setup, url_prefix='/setup') ......... The directory 'setup' contains: __init__.py (empty) setup.py (the module) and setup.py has this: # setup - /setup/setup from flask import g, Blueprint, render_template, abort from flask import session setup = Blueprint('setup', __name__) print "SETUP: Session what is our route? :", session['route'] # @setup.route('/') @setup.route('/') def dummy():"from setup.setup" to before the " # Do some stuff return render_template('setup/dummy.html') So, what AM I doing wrong ? I tried moving the "app = Flask(__name__)" in wtform.py and it made no difference *Thanks for all the help !!!! No Really ....* *(FWIW: **If I can't get flask configured the way I need, they are going to implement this accounting system in* *a 1990's era home brew Perl system ...)* *Ben Duncan* DBA / Chief Software Architect Mississippi State Supreme Court Electronic Filing Division On Thu, Oct 24, 2019 at 4:22 PM Paul G?tze wrote: > Hi Ben, > > in general you should only need to import the functions or classes or > modules you are actually using in the code of the respective module (e.g. > your view Python file). > There might be an exception to this if you want to provide a certain > function/class/module from a special place, so that it can be imported from > there. E.g. suppose you have a file (i.e. a module) abc.py were you defined > a function do_abc() and a file xyz.py were there is a function do_xyz(). If > you would have a main.py and wanted to import both do_abc() and do_xyz() > from xyz, then you would need to import do_abc in xyz.py: > > # in xyz.py: > from .abc import do_abc() > > def do_xyz(): > pass > > and then you could write: > > # in main.py: > from .xyz import do_xyz, do_abc > > and use both. Otherwise you would need to import them separately: > > # in main.py: > from .abc import do_abc > from .xyz import do_xyz > > Maybe try if sth. breaks if you do not include all the imports. Python > will complain about missing imports. If nothing breaks, then it?s fine :) > Whether you use the functional or divisional structure should not matter. > > (If you are using PyCharm for development, then there is the > Strg+Shift+Alt+L command that auto-formats your code. You can also > optimize/remove not needed imports with this. But I guess a code linter in > your editor would also tell you which imports are not used, by printing > them gray or the like.) > > I hope this helps? > Cheers, Paul > > > Am 24.10.19 um 16:28 schrieb Ben Duncan: > > I'm following some blueprints how to and have a question of configuration. > > I'm using the functional method as outlined here: > http://exploreflask.com/en/latest/blueprints.html > > The question is: > In my Top level Application folder that runs the whole thing , I have > am using a lot of import libraries: > > > ----------------------------------------------------------------------------------------------------------------------- > from flask import Flask, render_template, request, redirect, url_for, > flash, make_response, escape, g > from flask import get_flashed_messages > from flask_session import Session > from flask.templating import Environment > from flask_sqlalchemy import SQLAlchemy > > metadata = MetaData() > from flask import session > > # Flask_wtf from: https://flask-wtf.readthedocs.io/en/stable/ > from flask_wtf import FlaskForm > > # CSRF Protection .... > from flask_wtf.csrf import CSRFProtect > from flask_wtf.csrf import CSRFError > > 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 > > ------------------------------------------------------------------------------------------------------------------ > In the blueprinted view of: newapp.py I only have : > > from flask import Blueprint, render_template > > *The question is:* > > *Do I need to include the imports I have in the top level in the > blueprinted form ?* > > Thanks ... > *Ben Duncan* > DBA / Chief Software Architect > Mississippi State Supreme Court > Electronic Filing Division > > _______________________________________________ > Flask mailing listFlask at python.orghttps://mail.python.org/mailman/listinfo/flask > > _______________________________________________ > Flask mailing list > Flask at python.org > https://mail.python.org/mailman/listinfo/flask > -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul.christoph.goetze at gmail.com Fri Oct 25 12:31:18 2019 From: paul.christoph.goetze at gmail.com (=?UTF-8?Q?Paul_G=c3=b6tze?=) Date: Fri, 25 Oct 2019 18:31:18 +0200 Subject: [Flask] Blueprints Question ... In-Reply-To: References: <10699d4c-e146-006d-2efd-c9c00cbfff16@gmail.com> Message-ID: Hi Ben, looks like the error will be gone if you move the print statement into your dummy() function. Inside of this route function there will be an active HTTP request available (which can be accessed after you imported it 'from flask import request'). If you put the print outside of dummy() it is evaluated already when Python runs the setup.py the first time, not only if you hit the defined '/' route. That means there won?t be any active request available at that time. Another thing: Is there any particular reason why you still use Python 2? (The error message states v2,7, and print function would not work without parentheses in Python 3, that?s why I noticed.) Unless there is solid reasons, like if you need to support legacy systems, etc., I?d recommend switching to Python 3. Also you will find great up-to-date documentation about everything Flask on the official webpage: https://flask.palletsprojects.com Regards, Paul Am 25.10.19 um 14:45 schrieb Ben Duncan: > Thanks all - Especially Paul ... > > Now, I'm getting the following error: > > > RuntimeError > > RuntimeError: Working outside of request context. This typically means > that you attempted to use functionality that needed an active HTTP > request. Consult the documentation on testing for information about > how to avoid this problem. > > > Traceback?/(most recent call last)/ > > * > > > File?"/data/flask/applications/myproject/wtform.py", > line?/63/, in?|| > > from setup.setup import setup > * > > > File?"/data/flask/applications/myproject/setup/setup.py", > line?/7/, in?|| > > print "SETUP: Session what is our route? :", session['route'] > * > > > File?"/opt/rh/python27/root/usr/lib/python2.7/site-packages/werkzeug/local.py", > line?/378/, in?|| > > __getitem__ = lambda x, i: x._get_current_object()[i] > * > > > File?"/opt/rh/python27/root/usr/lib/python2.7/site-packages/werkzeug/local.py", > line?/307/, in?|_get_current_object| > > return self.__local() > * > > > File?"/opt/rh/python27/root/usr/lib64/python2.7/site-packages/flask/globals.py", > line?/38/, in?|_lookup_req_object| > > raise RuntimeError(_request_ctx_err_msg) > > RuntimeError: Working outside of request context. This typically > means that you attempted to use functionality that needed an > active HTTP request. Consult the documentation on testing for > information about how to avoid this problem. > > * > * > My main process, wtform.py looks like this : > .... (all the necessary imports for flask and wtforms and sqlalchemy) .... > ...... > app = Flask(__name__) > app.config.from_pyfile('config.cfg') > > flask_session = Session() > flask_session.init_app(app) > > session = {'modified': False } > session = {'route': None } > > # import blueprinted applications here: > from setup.setup import setup > > # register blueprinted applications here: > app.register_blueprint(setup, url_prefix='/setup') > ......... > > The directory 'setup' contains: > ?? __init__.py???????????? (empty) > ? setup.py???????????????? (the module) > > and setup.py has this: > # setup - /setup/setup > from flask import g, Blueprint, render_template, abort > from flask import session > > setup = Blueprint('setup', __name__) > > print "SETUP: Session what is our route? :", session['route'] > > # @setup.route('/') > @setup.route('/') > def dummy():"from setup.setup" to before the " > ? ? # Do some stuff > ? ? return render_template('setup/dummy.html') > > So, what AM I doing wrong ? > > I tried moving the "app = Flask(__name__)" in wtform.py and it made no > difference > > /*Thanks for all the help !!!! No Really ....*/ > > *(FWIW: */If I can't get flask configured the way I need, they are > going to implement this accounting system in/ > /a 1990's era home brew Perl system ...)/ > > *Ben Duncan* > DBA / Chief Software Architect > Mississippi State Supreme Court > Electronic Filing Division > > > On Thu, Oct 24, 2019 at 4:22 PM Paul G?tze > > wrote: > > Hi Ben, > > in general you should only need to import the functions or classes > or modules you are actually using in the code of the respective > module (e.g. your view Python file). > There might be an exception to this if you want to provide a > certain function/class/module from a special place, so that it can > be imported from there. E.g. suppose you have a file (i.e. a > module) abc.py were you defined a function do_abc() and a file > xyz.py were there is a function do_xyz(). If you would have a > main.py and wanted to import both do_abc() and do_xyz() from xyz, > then you would need to import do_abc in xyz.py: > > # in xyz.py: > from .abc import do_abc() > > def do_xyz(): > ??? pass > > and then you could write: > > # in main.py: > from .xyz import do_xyz, do_abc > > and use both. Otherwise you would need to import them separately: > > # in main.py: > from .abc import do_abc > from .xyz import do_xyz > > Maybe try if sth. breaks if you do not include all the imports. > Python will complain about missing imports. If nothing breaks, > then it?s fine :) > Whether you use the functional or divisional structure should not > matter. > > (If you are using PyCharm for development, then there is the > Strg+Shift+Alt+L command that auto-formats your code. You can also > optimize/remove not needed imports with this. But I guess a code > linter in your editor would also tell you which imports are not > used, by printing them gray or the like.) > > I hope this helps? > Cheers, Paul > > > Am 24.10.19 um 16:28 schrieb Ben Duncan: >> I'm following some blueprints how to and have a question of >> configuration. >> >> I'm using the functional method as outlined here: >> http://exploreflask.com/en/latest/blueprints.html >> >> The question is: >> In my Top level Application folder that runs the whole thing , I >> have >> am using? a lot of import libraries: >> >> ----------------------------------------------------------------------------------------------------------------------- >> from flask import Flask, render_template, request, redirect, >> url_for, flash, make_response, escape, g >> from flask import get_flashed_messages >> from flask_session import Session >> from flask.templating import Environment >> from flask_sqlalchemy import SQLAlchemy >> >> metadata = MetaData() >> from flask import session >> >> # Flask_wtf from: https://flask-wtf.readthedocs.io/en/stable/ >> from flask_wtf import FlaskForm >> >> # CSRF Protection .... >> from flask_wtf.csrf import CSRFProtect >> from flask_wtf.csrf import CSRFError >> >> 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 >> ------------------------------------------------------------------------------------------------------------------ >> In the blueprinted view of: newapp.py I only have : >> >> from flask import Blueprint, render_template >> >> *The question is:* >> >> *Do I need to include the imports I have in the top level in the >> blueprinted form ?* >> >> Thanks ... >> *Ben Duncan* >> DBA / Chief Software Architect >> Mississippi State Supreme Court >> Electronic Filing Division >> >> _______________________________________________ >> Flask mailing list >> Flask at python.org >> https://mail.python.org/mailman/listinfo/flask > _______________________________________________ > Flask mailing list > Flask at python.org > https://mail.python.org/mailman/listinfo/flask > -------------- next part -------------- An HTML attachment was scrubbed... URL: From linux4ms at gmail.com Fri Oct 25 12:46:24 2019 From: linux4ms at gmail.com (Ben Duncan) Date: Fri, 25 Oct 2019 11:46:24 -0500 Subject: [Flask] Blueprints Question ... In-Reply-To: References: <10699d4c-e146-006d-2efd-c9c00cbfff16@gmail.com> Message-ID: Ok, thanks Paul ... Forced to 2.7 but trying to move to 3.6 on current RedHat 7 - but got stuck with 3.4 (It's a government agency so it's slow to move) evenetually *Ben Duncan* DBA / Chief Software Architect Mississippi State Supreme Court Electronic Filing Division On Fri, Oct 25, 2019 at 11:31 AM Paul G?tze wrote: > Hi Ben, > > looks like the error will be gone if you move the print statement into > your dummy() function. Inside of this route function there will be an > active HTTP request available (which can be accessed after you imported it > 'from flask import request'). If you put the print outside of dummy() it is > evaluated already when Python runs the setup.py the first time, not only if > you hit the defined '/' route. That means there won?t be any > active request available at that time. > > Another thing: Is there any particular reason why you still use Python 2? > (The error message states v2,7, and print function would not work without > parentheses in Python 3, that?s why I noticed.) > Unless there is solid reasons, like if you need to support legacy systems, > etc., I?d recommend switching to Python 3. Also you will find great > up-to-date documentation about everything Flask on the official webpage: > https://flask.palletsprojects.com > > Regards, Paul > > > Am 25.10.19 um 14:45 schrieb Ben Duncan: > > Thanks all - Especially Paul ... > > Now, I'm getting the following error: > RuntimeError > > RuntimeError: Working outside of request context. This typically means > that you attempted to use functionality that needed an active HTTP request. > Consult the documentation on testing for information about how to avoid > this problem. > Traceback *(most recent call last)* > > - File "/data/flask/applications/myproject/wtform.py", line *63*, in > > > from setup.setup import setup > > - File "/data/flask/applications/myproject/setup/setup.py", line *7*, > in > > print "SETUP: Session what is our route? :", session['route'] > > - File > "/opt/rh/python27/root/usr/lib/python2.7/site-packages/werkzeug/local.py", > line *378*, in > > __getitem__ = lambda x, i: x._get_current_object()[i] > > - File > "/opt/rh/python27/root/usr/lib/python2.7/site-packages/werkzeug/local.py", > line *307*, in _get_current_object > > return self.__local() > > - File > "/opt/rh/python27/root/usr/lib64/python2.7/site-packages/flask/globals.py", > line *38*, in _lookup_req_object > > raise RuntimeError(_request_ctx_err_msg) > > > RuntimeError: Working outside of request context. This typically means > that you attempted to use functionality that needed an active HTTP request. > Consult the documentation on testing for information about how to avoid > this problem. > > > My main process, wtform.py looks like this : > .... (all the necessary imports for flask and wtforms and sqlalchemy) .... > ...... > app = Flask(__name__) > app.config.from_pyfile('config.cfg') > > flask_session = Session() > flask_session.init_app(app) > > session = {'modified': False } > session = {'route': None } > > # import blueprinted applications here: > from setup.setup import setup > > # register blueprinted applications here: > app.register_blueprint(setup, url_prefix='/setup') > ......... > > The directory 'setup' contains: > __init__.py (empty) > setup.py (the module) > > and setup.py has this: > # setup - /setup/setup > from flask import g, Blueprint, render_template, abort > from flask import session > > setup = Blueprint('setup', __name__) > > print "SETUP: Session what is our route? :", session['route'] > > # @setup.route('/') > @setup.route('/') > def dummy():"from setup.setup" to before the " > # Do some stuff > return render_template('setup/dummy.html') > > So, what AM I doing wrong ? > > I tried moving the "app = Flask(__name__)" in wtform.py and it made no > difference > > *Thanks for all the help !!!! No Really ....* > > *(FWIW: **If I can't get flask configured the way I need, they are going > to implement this accounting system in* > *a 1990's era home brew Perl system ...)* > > *Ben Duncan* > DBA / Chief Software Architect > Mississippi State Supreme Court > Electronic Filing Division > > > On Thu, Oct 24, 2019 at 4:22 PM Paul G?tze < > paul.christoph.goetze at gmail.com> wrote: > >> Hi Ben, >> >> in general you should only need to import the functions or classes or >> modules you are actually using in the code of the respective module (e.g. >> your view Python file). >> There might be an exception to this if you want to provide a certain >> function/class/module from a special place, so that it can be imported from >> there. E.g. suppose you have a file (i.e. a module) abc.py were you defined >> a function do_abc() and a file xyz.py were there is a function do_xyz(). If >> you would have a main.py and wanted to import both do_abc() and do_xyz() >> from xyz, then you would need to import do_abc in xyz.py: >> >> # in xyz.py: >> from .abc import do_abc() >> >> def do_xyz(): >> pass >> >> and then you could write: >> >> # in main.py: >> from .xyz import do_xyz, do_abc >> >> and use both. Otherwise you would need to import them separately: >> >> # in main.py: >> from .abc import do_abc >> from .xyz import do_xyz >> >> Maybe try if sth. breaks if you do not include all the imports. Python >> will complain about missing imports. If nothing breaks, then it?s fine :) >> Whether you use the functional or divisional structure should not matter. >> >> (If you are using PyCharm for development, then there is the >> Strg+Shift+Alt+L command that auto-formats your code. You can also >> optimize/remove not needed imports with this. But I guess a code linter in >> your editor would also tell you which imports are not used, by printing >> them gray or the like.) >> >> I hope this helps? >> Cheers, Paul >> >> >> Am 24.10.19 um 16:28 schrieb Ben Duncan: >> >> I'm following some blueprints how to and have a question of configuration. >> >> I'm using the functional method as outlined here: >> http://exploreflask.com/en/latest/blueprints.html >> >> The question is: >> In my Top level Application folder that runs the whole thing , I have >> am using a lot of import libraries: >> >> >> ----------------------------------------------------------------------------------------------------------------------- >> from flask import Flask, render_template, request, redirect, url_for, >> flash, make_response, escape, g >> from flask import get_flashed_messages >> from flask_session import Session >> from flask.templating import Environment >> from flask_sqlalchemy import SQLAlchemy >> >> metadata = MetaData() >> from flask import session >> >> # Flask_wtf from: https://flask-wtf.readthedocs.io/en/stable/ >> from flask_wtf import FlaskForm >> >> # CSRF Protection .... >> from flask_wtf.csrf import CSRFProtect >> from flask_wtf.csrf import CSRFError >> >> 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 >> >> ------------------------------------------------------------------------------------------------------------------ >> In the blueprinted view of: newapp.py I only have : >> >> from flask import Blueprint, render_template >> >> *The question is:* >> >> *Do I need to include the imports I have in the top level in the >> blueprinted form ?* >> >> Thanks ... >> *Ben Duncan* >> DBA / Chief Software Architect >> Mississippi State Supreme Court >> Electronic Filing Division >> >> _______________________________________________ >> Flask mailing listFlask at python.orghttps://mail.python.org/mailman/listinfo/flask >> >> _______________________________________________ >> Flask mailing list >> Flask at python.org >> https://mail.python.org/mailman/listinfo/flask >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sebastian_cheung at yahoo.com Fri Oct 25 13:46:09 2019 From: sebastian_cheung at yahoo.com (sebastian cheung) Date: Fri, 25 Oct 2019 18:46:09 +0100 Subject: [Flask] Celery and working outside request context Message-ID: Is this the right place to ask about Celery and ?Working outside of request context? and Response type of class is not JSON serialisable? Mainly because my endpoints CRUDs are working but when I moved them inside celery.tasks I got the above Sebastian Sent from my iPhone From prangara at akamai.com Mon Oct 28 14:29:54 2019 From: prangara at akamai.com (Rangarajan, Prakash) Date: Mon, 28 Oct 2019 18:29:54 +0000 Subject: [Flask] Flask and Nginx/Gunicorn Message-ID: <5237E6BE-046C-4CA2-8DD7-9DA15E04E74D@akamai.com> Hi, I am trying to run my flask app behind a reverse proxy using Nginx and Gunicorn. When I run some load test, I see 499?s from nginx. I believe it is a generic error code when it can?t access the upstream or takes too long for a response. Is there a good way to debug this or some configuration parameters tht can be tuned ? Thanks, Prakash -------------- next part -------------- An HTML attachment was scrubbed... URL: From corralejob at gmail.com Mon Oct 28 16:11:39 2019 From: corralejob at gmail.com (Bryan Corralejo) Date: Mon, 28 Oct 2019 15:11:39 -0500 Subject: [Flask] Flask and Nginx/Gunicorn In-Reply-To: <5237E6BE-046C-4CA2-8DD7-9DA15E04E74D@akamai.com> References: <5237E6BE-046C-4CA2-8DD7-9DA15E04E74D@akamai.com> Message-ID: <137D2222-F5DB-4F47-A786-3C06ADB95738@gmail.com> http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_read_timeout Might be something to look into. This sets the amount of time NGINX will wait to hear back from the upstream server. Regards, Bryan > On Oct 28, 2019, at 2:18 PM, Rangarajan, Prakash via Flask wrote: > > ? > Hi, > I am trying to run my flask app behind a reverse proxy using Nginx and Gunicorn. When I run some load test, I see 499?s from nginx. I believe it is a generic error code when it can?t access the upstream or takes too long for a response. Is there a good way to debug this or some configuration parameters tht can be tuned ? > > Thanks, > Prakash > _______________________________________________ > Flask mailing list > Flask at python.org > https://mail.python.org/mailman/listinfo/flask -------------- next part -------------- An HTML attachment was scrubbed... URL: From corralejob at gmail.com Mon Oct 28 16:14:29 2019 From: corralejob at gmail.com (Bryan Corralejo) Date: Mon, 28 Oct 2019 15:14:29 -0500 Subject: [Flask] Flask and Nginx/Gunicorn In-Reply-To: <137D2222-F5DB-4F47-A786-3C06ADB95738@gmail.com> References: <137D2222-F5DB-4F47-A786-3C06ADB95738@gmail.com> Message-ID: <502EDD0F-A481-499C-9017-1DACCDC9509C@gmail.com> Although now that I think about it more, this indicates the client is closing the connection. Your client might have a timeout threshold being met when the application is under load, not an NGINX problem. Regards, Bryan > On Oct 28, 2019, at 3:11 PM, Bryan Corralejo wrote: > > ?http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_read_timeout Might be something to look into. This sets the amount of time NGINX will wait to hear back from the upstream server. > > Regards, > > Bryan > >>> On Oct 28, 2019, at 2:18 PM, Rangarajan, Prakash via Flask wrote: >>> >> ? >> Hi, >> I am trying to run my flask app behind a reverse proxy using Nginx and Gunicorn. When I run some load test, I see 499?s from nginx. I believe it is a generic error code when it can?t access the upstream or takes too long for a response. Is there a good way to debug this or some configuration parameters tht can be tuned ? >> >> Thanks, >> Prakash >> _______________________________________________ >> Flask mailing list >> Flask at python.org >> https://mail.python.org/mailman/listinfo/flask -------------- next part -------------- An HTML attachment was scrubbed... URL: From linux4ms at gmail.com Wed Oct 30 08:55:18 2019 From: linux4ms at gmail.com (Ben Duncan) Date: Wed, 30 Oct 2019 07:55:18 -0500 Subject: [Flask] Help with Blueprints ... Message-ID: I've gotten my blueprint stuff working partially. I'm using the function style as defined here : https://danidee10.github.io/2016/11/20/flask-by-example-8.html I have a master directory called mars and my blueprints are in a directory called view under mars. My mars application __init__ looks like: # -------------------------------------------- _root _iinit__.py import sys from flask import Flask, g from flask_sqlalchemy import SQLAlchemy from flask_session import Session from flask import session # 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__, instance_relative_config=False) app = Flask(__name__) app.config.from_pyfile('config.cfg') flask_session = Session() flask_session.init_app(app) session = {'modified': False } session = {'route': None } session = {'MASTERBLASTER': "Some really stupid stuff"} # 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.home import home app.register_blueprint( home ) from .views.auth import auth app.register_blueprint( auth ) from .views.ar import ar app.register_blueprint( ar ) return app # -------------- End of Init My mars wsgi.py looks like this: #---------------------- Wsgi # Base wsgi application starter from mars import create_app app = create_app() if __name__ == "__main__": app.run() #----- And my run script looks like: #!/bin/sh #rm -rf flask_session/* export FLASK_APP=wsgi.py export FLASK_ENV=development flask run --host=0.0.0.0 --cert=adhoc Under views, __iinit__.py is empty and and my home.py looks like #---- home.py # mars/views/home from flask import Blueprint, render_template, request, session # Insert libraries as needed !!! home = Blueprint('home', __name__) @home.route('/') def welcome(user_url_slug): # Do some stuff return render_template('home/welcome.html', session=session) #--- end of home. My html template file has this in it:

Hello From Template Form !!!

Insert your code here !!!

---- HOME ----

---- 2 HOME ----

session: {{ session['MASTERBLASTER'] }}

*My question/issue is* , that I need 'session' found in root __init__.py and the pgdb stuff to be available to the views/.py Am I setup correctly above? Am I missing something, what do I need to do ? -- OR -- DO I need to give up and go home ? ? Thanks ... *Ben Duncan* DBA / Chief Software Architect Mississippi State Supreme Court Electronic Filing Division -------------- next part -------------- An HTML attachment was scrubbed... URL: From linux4ms at gmail.com Thu Oct 31 07:50:43 2019 From: linux4ms at gmail.com (Ben Duncan) Date: Thu, 31 Oct 2019 06:50:43 -0500 Subject: [Flask] Sessions and blueprints and Application context Message-ID: Ok, given the previous example post form me (Help WIth BluePrints), How does on go about accessing "session" in the bluprinted view? Do I need to something more in my "__init__.py" ? Am I missing some import in my view ? As Always thanks ... *Ben Duncan* DBA / Chief Software Architect Mississippi State Supreme Court Electronic Filing Division -------------- next part -------------- An HTML attachment was scrubbed... URL: From bsdtux at gmail.com Thu Oct 31 09:12:38 2019 From: bsdtux at gmail.com (Josh Stephens) Date: Thu, 31 Oct 2019 06:12:38 -0700 Subject: [Flask] Sessions and blueprints and Application context In-Reply-To: References: Message-ID: I believe you should just be able to import session from flask and use it. I thought session is stored as a global and so it can be used anywhere. Are you getting a specific error when trying to use sessions in your blueprint? On October 31, 2019 at 6:50:58 AM, Ben Duncan (linux4ms at gmail.com) wrote: Ok, given the previous example post form me (Help WIth BluePrints), How does on go about accessing "session" in the bluprinted view? Do I need to something more in my "__init__.py" ? Am I missing some import in my view ? As Always thanks ... *Ben Duncan* DBA / Chief Software Architect Mississippi State Supreme Court Electronic Filing Division _______________________________________________ Flask mailing list Flask at python.org https://mail.python.org/mailman/listinfo/flask -------------- next part -------------- An HTML attachment was scrubbed... URL: From bsdtux at gmail.com Thu Oct 31 09:19:54 2019 From: bsdtux at gmail.com (Josh Stephens) Date: Thu, 31 Oct 2019 06:19:54 -0700 Subject: [Flask] Help with Blueprints ... In-Reply-To: References: Message-ID: Ben, Sorry I just saw this after replying to your first email. Can you try moving your flask_session = Session() out of the create_app(). Keep the flask_session.init_app(app) where it is. I am thinking this is probably where your issue is coming from because flask_session is not at a global level but in your function and thus I feel like it might be disappearing after your return app from create_app Best Regards, Josh Stephens On October 30, 2019 at 7:55:35 AM, Ben Duncan (linux4ms at gmail.com) wrote: I've gotten my blueprint stuff working partially. I'm using the function style as defined here : https://danidee10.github.io/2016/11/20/flask-by-example-8.html I have a master directory called mars and my blueprints are in a directory called view under mars. My mars application __init__ looks like: # -------------------------------------------- _root _iinit__.py import sys from flask import Flask, g from flask_sqlalchemy import SQLAlchemy from flask_session import Session from flask import session # 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__, instance_relative_config=False) app = Flask(__name__) app.config.from_pyfile('config.cfg') flask_session = Session() flask_session.init_app(app) session = {'modified': False } session = {'route': None } session = {'MASTERBLASTER': "Some really stupid stuff"} # 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.home import home app.register_blueprint( home ) from .views.auth import auth app.register_blueprint( auth ) from .views.ar import ar app.register_blueprint( ar ) return app # -------------- End of Init My mars wsgi.py looks like this: #---------------------- Wsgi # Base wsgi application starter from mars import create_app app = create_app() if __name__ == "__main__": app.run() #----- And my run script looks like: #!/bin/sh #rm -rf flask_session/* export FLASK_APP=wsgi.py export FLASK_ENV=development flask run --host=0.0.0.0 --cert=adhoc Under views, __iinit__.py is empty and and my home.py looks like #---- home.py # mars/views/home from flask import Blueprint, render_template, request, session # Insert libraries as needed !!! home = Blueprint('home', __name__) @home.route('/') def welcome(user_url_slug): # Do some stuff return render_template('home/welcome.html', session=session) #--- end of home. My html template file has this in it:

Hello From Template Form !!!

Insert your code here !!!

---- HOME ----

---- 2 HOME ----

session: {{ session['MASTERBLASTER'] }}

*My question/issue is* , that I need 'session' found in root __init__.py and the pgdb stuff to be available to the views/.py Am I setup correctly above? Am I missing something, what do I need to do ? -- OR -- DO I need to give up and go home ? ? Thanks ... *Ben Duncan* DBA / Chief Software Architect Mississippi State Supreme Court Electronic Filing Division _______________________________________________ Flask mailing list Flask at python.org https://mail.python.org/mailman/listinfo/flask -------------- next part -------------- An HTML attachment was scrubbed... URL: From linux4ms at gmail.com Thu Oct 31 10:18:09 2019 From: linux4ms at gmail.com (Ben Duncan) Date: Thu, 31 Oct 2019 09:18:09 -0500 Subject: [Flask] Sessions and blueprints and Application context In-Reply-To: References: Message-ID: Yes: my __init__.py ------------------------------------------------------------- import sys from flask import Flask, g, session from flask_sqlalchemy import SQLAlchemy # 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__, instance_relative_config=False) #app = Flask(__name__) app = Flask('mars') app.config.from_pyfile('config.cfg') session['myvar'] = 'MYVAR' ........ My wsgi.py # Base wsgi application starter from mars import create_app app = create_app() if __name__ == "__main__": app.run() And then it gets: RuntimeError RuntimeError: Working outside of request context. This typically means that you attempted to use functionality that needed an active HTTP request. Consult the documentation on testing for information about how to avoid this problem. Traceback *(most recent call last)* - File "/data/flask/applications/mars/wsgi.py", line *9*, in app = create_app() - File "/data/flask/applications/mars/__init__.py", line *21*, in create_app session['myvar'] = 'MYVAR' - File "/opt/rh/python27/root/usr/lib/python2.7/site-packages/werkzeug/local.py", line *351*, in __setitem__ self._get_current_object()[key] = value - File "/opt/rh/python27/root/usr/lib/python2.7/site-packages/werkzeug/local.py", line *307*, in _get_current_object return self.__local() - File "/opt/rh/python27/root/usr/lib64/python2.7/site-packages/flask/globals.py", line *38*, in _lookup_req_object raise RuntimeError(_request_ctx_err_msg) RuntimeError: Working outside of request context. This typically means that you attempted to use functionality that needed an active I kinda thought session would be global but ... sigh ... I've tried the import from Flask_session Session stuff and no luck ... *Ben Duncan* DBA / Chief Software Architect Mississippi State Supreme Court Electronic Filing Division On Thu, Oct 31, 2019 at 8:12 AM Josh Stephens wrote: > I believe you should just be able to import session from flask and use it. > I thought session is stored as a global and so it can be used anywhere. Are > you getting a specific error when trying to use sessions in your blueprint? > > > On October 31, 2019 at 6:50:58 AM, Ben Duncan (linux4ms at gmail.com) wrote: > > Ok, given the previous example post form me (Help WIth BluePrints), > How does on go about accessing "session" in the bluprinted view? > > Do I need to something more in my "__init__.py" ? Am I missing some import > in my view ? > > As Always thanks ... > > > *Ben Duncan* > DBA / Chief Software Architect > Mississippi State Supreme Court > Electronic Filing Division > _______________________________________________ > Flask mailing list > Flask at python.org > https://mail.python.org/mailman/listinfo/flask > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From linux4ms at gmail.com Thu Oct 31 10:32:22 2019 From: linux4ms at gmail.com (Ben Duncan) Date: Thu, 31 Oct 2019 09:32:22 -0500 Subject: [Flask] Help with Blueprints ... In-Reply-To: References: Message-ID: Ok, tried: import sys from flask import Flask, g, session from flask_sqlalchemy import SQLAlchemy from flask_session import Session from flask.templating import Environment flask_session = Session() # 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__, instance_relative_config=False) #app = Flask(__name__) app = Flask('mars') app.config.from_pyfile('config.cfg') flask_session.init_app(app) session = {'MASTERBLASTER': "Some really stupid stuff"} and I get that dreaded 'out of context' on the view .... As always thanks ... *Ben Duncan* DBA / Chief Software Architect Mississippi State Supreme Court Electronic Filing Division On Thu, Oct 31, 2019 at 8:19 AM Josh Stephens wrote: > Ben, > > Sorry I just saw this after replying to your first email. Can you try > moving your flask_session = Session() out of the create_app(). Keep the > flask_session.init_app(app) where it is. I am thinking this is probably > where your issue is coming from because flask_session is not at a global > level but in your function and thus I feel like it might be disappearing > after your return app from create_app > > Best Regards, > Josh Stephens > > > On October 30, 2019 at 7:55:35 AM, Ben Duncan (linux4ms at gmail.com) wrote: > > I've gotten my blueprint stuff working partially. I'm using the function > style > as defined here : > https://danidee10.github.io/2016/11/20/flask-by-example-8.html > > I have a master directory called mars and my blueprints are in a directory > called view under mars. > > My mars application __init__ looks like: > # -------------------------------------------- _root _iinit__.py > import sys > from flask import Flask, g > from flask_sqlalchemy import SQLAlchemy > from flask_session import Session > from flask import session > > # 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__, instance_relative_config=False) > app = Flask(__name__) > > app.config.from_pyfile('config.cfg') > flask_session = Session() > flask_session.init_app(app) > > session = {'modified': False } > session = {'route': None } > session = {'MASTERBLASTER': "Some really stupid stuff"} > > # 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.home import home > app.register_blueprint( home ) > > from .views.auth import auth > app.register_blueprint( auth ) > > from .views.ar import ar > app.register_blueprint( ar ) > > return app > # -------------- End of Init > > My mars wsgi.py looks like this: > > #---------------------- Wsgi > > # Base wsgi application starter > > from mars import create_app > app = create_app() > if __name__ == "__main__": > app.run() > > #----- > > And my run script looks like: > #!/bin/sh > > #rm -rf flask_session/* > export FLASK_APP=wsgi.py > export FLASK_ENV=development > flask run --host=0.0.0.0 --cert=adhoc > > Under views, __iinit__.py is empty and and my home.py looks like > #---- home.py > # mars/views/home > from flask import Blueprint, render_template, request, session > # Insert libraries as needed !!! > > home = Blueprint('home', __name__) > > @home.route('/') > def welcome(user_url_slug): > # Do some stuff > return render_template('home/welcome.html', session=session) > > #--- end of home. > My html template file has this in it: > >

Hello From Template Form !!!

>

Insert your code here !!!

>

---- HOME ----

>

---- 2 HOME ----

>

session: {{ session['MASTERBLASTER'] }}

> > *My question/issue is* , that I need 'session' found in root __init__.py > and the > pgdb stuff to be available to the views/.py > > Am I setup correctly above? Am I missing something, what do I need to do ? > -- OR -- > DO I need to give up and go home ? ? > > > Thanks ... > *Ben Duncan* > DBA / Chief Software Architect > Mississippi State Supreme Court > Electronic Filing Division > _______________________________________________ > Flask mailing list > Flask at python.org > https://mail.python.org/mailman/listinfo/flask > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From linux4ms at gmail.com Thu Oct 31 10:46:45 2019 From: linux4ms at gmail.com (Ben Duncan) Date: Thu, 31 Oct 2019 09:46:45 -0500 Subject: [Flask] Help with Blueprints ... In-Reply-To: References: Message-ID: Ok, I followed to the letter : https://hackersandslackers.com/managing-user-session-variables-with-flask-sessions-and-redis/ (but not the redis) And from Miguels Fine book - Flask Mega Tutorial and neither 'session' nor 'g' is in the application context. I'm beginning to wonder if there is a a bug somewhere ... *Ben Duncan* DBA / Chief Software Architect Mississippi State Supreme Court Electronic Filing Division On Thu, Oct 31, 2019 at 9:32 AM Ben Duncan wrote: > Ok, tried: > import sys > > from flask import Flask, g, session > from flask_sqlalchemy import SQLAlchemy > from flask_session import Session > from flask.templating import Environment > > flask_session = Session() > > # 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__, instance_relative_config=False) > #app = Flask(__name__) > app = Flask('mars') > > app.config.from_pyfile('config.cfg') > flask_session.init_app(app) > session = {'MASTERBLASTER': "Some really stupid stuff"} > > and I get that dreaded 'out of context' on the view .... > > As always thanks ... > > *Ben Duncan* > DBA / Chief Software Architect > Mississippi State Supreme Court > Electronic Filing Division > > > On Thu, Oct 31, 2019 at 8:19 AM Josh Stephens wrote: > >> Ben, >> >> Sorry I just saw this after replying to your first email. Can you try >> moving your flask_session = Session() out of the create_app(). Keep the >> flask_session.init_app(app) where it is. I am thinking this is probably >> where your issue is coming from because flask_session is not at a global >> level but in your function and thus I feel like it might be disappearing >> after your return app from create_app >> >> Best Regards, >> Josh Stephens >> >> >> On October 30, 2019 at 7:55:35 AM, Ben Duncan (linux4ms at gmail.com) wrote: >> >> I've gotten my blueprint stuff working partially. I'm using the function >> style >> as defined here : >> https://danidee10.github.io/2016/11/20/flask-by-example-8.html >> >> I have a master directory called mars and my blueprints are in a directory >> called view under mars. >> >> My mars application __init__ looks like: >> # -------------------------------------------- _root _iinit__.py >> import sys >> from flask import Flask, g >> from flask_sqlalchemy import SQLAlchemy >> from flask_session import Session >> from flask import session >> >> # 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__, instance_relative_config=False) >> app = Flask(__name__) >> >> app.config.from_pyfile('config.cfg') >> flask_session = Session() >> flask_session.init_app(app) >> >> session = {'modified': False } >> session = {'route': None } >> session = {'MASTERBLASTER': "Some really stupid stuff"} >> >> # 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.home import home >> app.register_blueprint( home ) >> >> from .views.auth import auth >> app.register_blueprint( auth ) >> >> from .views.ar import ar >> app.register_blueprint( ar ) >> >> return app >> # -------------- End of Init >> >> My mars wsgi.py looks like this: >> >> #---------------------- Wsgi >> >> # Base wsgi application starter >> >> from mars import create_app >> app = create_app() >> if __name__ == "__main__": >> app.run() >> >> #----- >> >> And my run script looks like: >> #!/bin/sh >> >> #rm -rf flask_session/* >> export FLASK_APP=wsgi.py >> export FLASK_ENV=development >> flask run --host=0.0.0.0 --cert=adhoc >> >> Under views, __iinit__.py is empty and and my home.py looks like >> #---- home.py >> # mars/views/home >> from flask import Blueprint, render_template, request, session >> # Insert libraries as needed !!! >> >> home = Blueprint('home', __name__) >> >> @home.route('/') >> def welcome(user_url_slug): >> # Do some stuff >> return render_template('home/welcome.html', session=session) >> >> #--- end of home. >> My html template file has this in it: >> >>

Hello From Template Form !!!

>>

Insert your code here !!!

>>

---- HOME ----

>>

---- 2 HOME ----

>>

session: {{ session['MASTERBLASTER'] }}

>> >> *My question/issue is* , that I need 'session' found in root __init__.py >> and the >> pgdb stuff to be available to the views/.py >> >> Am I setup correctly above? Am I missing something, what do I need to do ? >> -- OR -- >> DO I need to give up and go home ? ? >> >> >> Thanks ... >> *Ben Duncan* >> DBA / Chief Software Architect >> Mississippi State Supreme Court >> Electronic Filing Division >> _______________________________________________ >> Flask mailing list >> Flask at python.org >> https://mail.python.org/mailman/listinfo/flask >> >> -------------- next part -------------- An HTML attachment was scrubbed... URL: From linux4ms at gmail.com Thu Oct 31 11:00:04 2019 From: linux4ms at gmail.com (Ben Duncan) Date: Thu, 31 Oct 2019 10:00:04 -0500 Subject: [Flask] Help with Blueprints ... In-Reply-To: References: Message-ID: Oh yeah, I almost forgot - My config file: import os from datetime import timedelta SECRET_KEY = os.urandom(64) 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' # Session management SESSION_TYPE = 'filesystem' SESSION_FILE_DIR = 'flask_session' SESSION_COOKIE_PATH = '/' SESSION_KEY_PREFIX = 'flsk' *Ben Duncan* DBA / Chief Software Architect Mississippi State Supreme Court Electronic Filing Division On Thu, Oct 31, 2019 at 9:46 AM Ben Duncan wrote: > Ok, I followed to the letter : > > https://hackersandslackers.com/managing-user-session-variables-with-flask-sessions-and-redis/ > (but not the redis) > And from Miguels Fine book - Flask Mega Tutorial > and neither 'session' nor 'g' is in the application context. I'm beginning > to wonder if there is a a bug somewhere ... > > > *Ben Duncan* > DBA / Chief Software Architect > Mississippi State Supreme Court > Electronic Filing Division > > > On Thu, Oct 31, 2019 at 9:32 AM Ben Duncan wrote: > >> Ok, tried: >> import sys >> >> from flask import Flask, g, session >> from flask_sqlalchemy import SQLAlchemy >> from flask_session import Session >> from flask.templating import Environment >> >> flask_session = Session() >> >> # 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__, instance_relative_config=False) >> #app = Flask(__name__) >> app = Flask('mars') >> >> app.config.from_pyfile('config.cfg') >> flask_session.init_app(app) >> session = {'MASTERBLASTER': "Some really stupid stuff"} >> >> and I get that dreaded 'out of context' on the view .... >> >> As always thanks ... >> >> *Ben Duncan* >> DBA / Chief Software Architect >> Mississippi State Supreme Court >> Electronic Filing Division >> >> >> On Thu, Oct 31, 2019 at 8:19 AM Josh Stephens wrote: >> >>> Ben, >>> >>> Sorry I just saw this after replying to your first email. Can you try >>> moving your flask_session = Session() out of the create_app(). Keep the >>> flask_session.init_app(app) where it is. I am thinking this is probably >>> where your issue is coming from because flask_session is not at a global >>> level but in your function and thus I feel like it might be disappearing >>> after your return app from create_app >>> >>> Best Regards, >>> Josh Stephens >>> >>> >>> On October 30, 2019 at 7:55:35 AM, Ben Duncan (linux4ms at gmail.com) >>> wrote: >>> >>> I've gotten my blueprint stuff working partially. I'm using the function >>> style >>> as defined here : >>> https://danidee10.github.io/2016/11/20/flask-by-example-8.html >>> >>> I have a master directory called mars and my blueprints are in a >>> directory >>> called view under mars. >>> >>> My mars application __init__ looks like: >>> # -------------------------------------------- _root _iinit__.py >>> import sys >>> from flask import Flask, g >>> from flask_sqlalchemy import SQLAlchemy >>> from flask_session import Session >>> from flask import session >>> >>> # 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__, instance_relative_config=False) >>> app = Flask(__name__) >>> >>> app.config.from_pyfile('config.cfg') >>> flask_session = Session() >>> flask_session.init_app(app) >>> >>> session = {'modified': False } >>> session = {'route': None } >>> session = {'MASTERBLASTER': "Some really stupid stuff"} >>> >>> # 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.home import home >>> app.register_blueprint( home ) >>> >>> from .views.auth import auth >>> app.register_blueprint( auth ) >>> >>> from .views.ar import ar >>> app.register_blueprint( ar ) >>> >>> return app >>> # -------------- End of Init >>> >>> My mars wsgi.py looks like this: >>> >>> #---------------------- Wsgi >>> >>> # Base wsgi application starter >>> >>> from mars import create_app >>> app = create_app() >>> if __name__ == "__main__": >>> app.run() >>> >>> #----- >>> >>> And my run script looks like: >>> #!/bin/sh >>> >>> #rm -rf flask_session/* >>> export FLASK_APP=wsgi.py >>> export FLASK_ENV=development >>> flask run --host=0.0.0.0 --cert=adhoc >>> >>> Under views, __iinit__.py is empty and and my home.py looks like >>> #---- home.py >>> # mars/views/home >>> from flask import Blueprint, render_template, request, session >>> # Insert libraries as needed !!! >>> >>> home = Blueprint('home', __name__) >>> >>> @home.route('/') >>> def welcome(user_url_slug): >>> # Do some stuff >>> return render_template('home/welcome.html', session=session) >>> >>> #--- end of home. >>> My html template file has this in it: >>> >>>

Hello From Template Form !!!

>>>

Insert your code here !!!

>>>

---- HOME ----

>>>

---- 2 HOME ----

>>>

session: {{ session['MASTERBLASTER'] }}

>>> >>> *My question/issue is* , that I need 'session' found in root >>> __init__.py and the >>> pgdb stuff to be available to the views/.py >>> >>> Am I setup correctly above? Am I missing something, what do I need to do >>> ? >>> -- OR -- >>> DO I need to give up and go home ? ? >>> >>> >>> Thanks ... >>> *Ben Duncan* >>> DBA / Chief Software Architect >>> Mississippi State Supreme Court >>> Electronic Filing Division >>> _______________________________________________ >>> Flask mailing list >>> Flask at python.org >>> https://mail.python.org/mailman/listinfo/flask >>> >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: