From matfall94 at gmail.com Tue Jun 4 04:21:51 2019 From: matfall94 at gmail.com (matar fall) Date: Tue, 4 Jun 2019 10:21:51 +0200 Subject: [Flask] Question of outsourcing flask app Message-ID: Hello, I have a question about flask application. Is it possible to externalize the configuration of a flask application thanks to a link? Like I give my link www.test.fr/config.py or something like that as source of my flask configuration. Best regards. -- *Cordialement.* *Matar FALL* *Etudiant en Machine Learning for Data Science ? l'Universit? Paris Descartes* *Tel: +33 07 51 53 95 18* -------------- next part -------------- An HTML attachment was scrubbed... URL: From casahome2000 at gmail.com Tue Jun 4 09:06:31 2019 From: casahome2000 at gmail.com (Carlos Anchia) Date: Tue, 4 Jun 2019 08:06:31 -0500 Subject: [Flask] Question of outsourcing flask app In-Reply-To: References: Message-ID: <55A0F33D-8869-47CC-9746-383CC3654BB0@gmail.com> Depends? "The way Flask is designed usually requires the configuration to be available when the application starts up.? http://flask.pocoo.org/docs/1.0/config/ If this is a goal, I would think there would need to be a script to pull the latest config from the URL, then launch the Flask Application pointing to the updated config.py. The issue here is that changes to the config.py file (at the URL) would not update the config of the running flask app (at runtime). > On Jun 4, 2019, at 3:21 AM, matar fall wrote: > > Hello, > I have a question about flask application. > Is it possible to externalize the configuration of a flask application thanks to a link? > Like I give my link www.test.fr/config.py or something like that as source of my flask configuration. > Best regards. > > -- > Cordialement. > > Matar FALL > Etudiant en Machine Learning for Data Science ? l'Universit? Paris Descartes > Tel: +33 07 51 53 95 18 > > _______________________________________________ > Flask mailing list > Flask at python.org > https://mail.python.org/mailman/listinfo/flask -------------- next part -------------- An HTML attachment was scrubbed... URL: From badrihippo at gmail.com Tue Jun 4 09:11:16 2019 From: badrihippo at gmail.com (Hippo) Date: Tue, 4 Jun 2019 18:41:16 +0530 Subject: [Flask] Question of outsourcing flask app In-Reply-To: <55A0F33D-8869-47CC-9746-383CC3654BB0@gmail.com> References: <55A0F33D-8869-47CC-9746-383CC3654BB0@gmail.com> Message-ID: Why do you want to externalise the configuration? In other words, what are the settings that you plan to modify in the external file? Depending on what it is, you could code your application to automatically load the settings whenever it needs to, during runtime, instead of having to get it from the config file. (Of course, if it's something major then Carlos' suggestion of having a separate launch script would work better. Depends on what you're trying to do). ?Badri -------------- next part -------------- An HTML attachment was scrubbed... URL: From matfall94 at gmail.com Tue Jun 4 09:51:11 2019 From: matfall94 at gmail.com (matar fall) Date: Tue, 4 Jun 2019 15:51:11 +0200 Subject: [Flask] Question of outsourcing flask app In-Reply-To: References: <55A0F33D-8869-47CC-9746-383CC3654BB0@gmail.com> Message-ID: Got It. Thank for your reply. It is necessary for me to do this kind of configuration if it is possible. Suggestion of Carlos is a nice idea which I will check/explore. Thank You. Regards Le mar. 4 juin 2019 ? 15:11, Hippo a ?crit : > Why do you want to externalise the configuration? In other words, what are > the settings that you plan to modify in the external file? > > Depending on what it is, you could code your application to automatically > load the settings whenever it needs to, during runtime, instead of having > to get it from the config file. (Of course, if it's something major then > Carlos' suggestion of having a separate launch script would work better. > Depends on what you're trying to do). > > ?Badri > -- *Cordialement.* *Matar FALL* *Etudiant en Machine Learning for Data Science ? l'Universit? Paris Descartes* *Tel: +33 07 51 53 95 18* -------------- next part -------------- An HTML attachment was scrubbed... URL: From paradox2005 at gmail.com Tue Jun 4 10:30:57 2019 From: paradox2005 at gmail.com (Adil Hasan) Date: Tue, 4 Jun 2019 15:30:57 +0100 Subject: [Flask] Question of outsourcing flask app In-Reply-To: References: <55A0F33D-8869-47CC-9746-383CC3654BB0@gmail.com> Message-ID: <20190604143056.GC3622@parsnip> Hello, I think that perhaps reading configs from remote resources could potentially be a security issue. If you can make sure that the site providing the configs also has to provide some token that may help to mitigate the issue. hth adil On Tue, Jun 04, 2019 at 03:51:11PM +0200, matar fall wrote: > Got It. > Thank for your reply. > It is necessary for me to do this kind of configuration if it is possible. > Suggestion of Carlos is a nice idea which I will check/explore. > Thank You. Regards > > Le mar. 4 juin 2019 ? 15:11, Hippo a ?crit : > > > Why do you want to externalise the configuration? In other words, what are > > the settings that you plan to modify in the external file? > > > > Depending on what it is, you could code your application to automatically > > load the settings whenever it needs to, during runtime, instead of having > > to get it from the config file. (Of course, if it's something major then > > Carlos' suggestion of having a separate launch script would work better. > > Depends on what you're trying to do). > > > > ?Badri > > > > > -- > > *Cordialement.* > > > *Matar FALL* > > *Etudiant en Machine Learning for Data Science ? l'Universit? Paris > Descartes* > > *Tel: +33 07 51 53 95 18* > _______________________________________________ > Flask mailing list > Flask at python.org > https://mail.python.org/mailman/listinfo/flask From keith at the-sanctuary.biz Tue Jun 4 13:10:18 2019 From: keith at the-sanctuary.biz (keith macdonald) Date: Tue, 4 Jun 2019 18:10:18 +0100 Subject: [Flask] Question of outsourcing flask app In-Reply-To: References: Message-ID: <001301d51af8$62e564f0$28b02ed0$@biz> I agree with Adil about the security risk - how would you know what's in the remote file *before* it gets used? But, if you must go that route, how about running a Curl command from inside the Python code, just before the Flask app is initialized? With the Curl program saving the file to somewhere local. For example: # get remote file import os cmd = "C:/Curl/curl.exe www.test.fr/config.py -o C:/Download/config.py # or (instead of a Download folder) whatever folder is good for the local code. os.system(cmd) # now start Flask app import config as config from flask import Flask app = Flask(__name__) From matfall94 at gmail.com Tue Jun 4 14:50:35 2019 From: matfall94 at gmail.com (matar fall) Date: Tue, 4 Jun 2019 20:50:35 +0200 Subject: [Flask] Question of outsourcing flask app In-Reply-To: <001301d51af8$62e564f0$28b02ed0$@biz> References: <001301d51af8$62e564f0$28b02ed0$@biz> Message-ID: Got it. Thank You for sharing your knowledge. I will handle and take into account all your suggestions. Regards. Le mar. 4 juin 2019 ? 19:35, keith macdonald a ?crit : > I agree with Adil about the security risk - how would you know what's in > the > remote file *before* it gets used? > > But, if you must go that route, how about running a Curl command from > inside > the Python code, just before the Flask app is initialized? With the Curl > program saving the file to somewhere local. > > For example: > > # get remote file > import os > cmd = "C:/Curl/curl.exe www.test.fr/config.py -o C:/Download/config.py > # or (instead of a Download folder) whatever folder is good for the local > code. > os.system(cmd) > > # now start Flask app > import config as config > from flask import Flask > app = Flask(__name__) > > _______________________________________________ > Flask mailing list > Flask at python.org > https://mail.python.org/mailman/listinfo/flask > -------------- next part -------------- An HTML attachment was scrubbed... URL: From coreybrett at gmail.com Tue Jun 4 15:38:32 2019 From: coreybrett at gmail.com (Corey Boyle) Date: Tue, 4 Jun 2019 15:38:32 -0400 Subject: [Flask] combing decorators Message-ID: I need to create a new decorator for my views to handle different users having different roles/access levels. Something like this... @role_required('SALES') So my views would end up something like this... @blueprint.route('/post') @login_required @role_required(['SALES']) def post(): pass Is there any way for me to combine those decorators? Maybe something like... @view('/post', ['SALES']) -------------- next part -------------- An HTML attachment was scrubbed... URL: From cs at cskk.id.au Tue Jun 4 17:31:36 2019 From: cs at cskk.id.au (Cameron Simpson) Date: Wed, 5 Jun 2019 07:31:36 +1000 Subject: [Flask] combing decorators In-Reply-To: References: Message-ID: <20190604213136.GA27974@cskk.homeip.net> On 04Jun2019 15:38, Corey Boyle wrote: >I need to create a new decorator for my views to handle different users >having different roles/access levels. > >Something like this... >@role_required('SALES') I'm doing roughly this, though at present there's just one logged in role for my app. >So my views would end up something like this... >@blueprint.route('/post') >@login_required >@role_required(['SALES']) >def post(): > pass > >Is there any way for me to combine those decorators? >Maybe something like... >@view('/post', ['SALES']) Sure. You just need to ensure that app.route is the outermost decorator so that it attaches your other-decorated handler to the route. I've a @post_route decorator in my current app which intercepts particular form fields, looks them up, and presents the lookups as parameters, and this is common enough to do exactly what you're describing: wrap app.route and other things into a single decorator. Works a treat. Start with this: def view(route, roles, **kw): def decorate(handler): return blueprint.route(route,**kw)( login_required( role_required(roles)( handler))) return decorate That's untested, but you see the structure I presume. Cheers, Cameron Simpson From cs at cskk.id.au Tue Jun 4 17:35:33 2019 From: cs at cskk.id.au (Cameron Simpson) Date: Wed, 5 Jun 2019 07:35:33 +1000 Subject: [Flask] Question of outsourcing flask app In-Reply-To: <20190604143056.GC3622@parsnip> References: <20190604143056.GC3622@parsnip> Message-ID: <20190604213533.GA68570@cskk.homeip.net> On 04Jun2019 15:30, Adil Hasan wrote: >I think that perhaps reading configs from remote resources could >potentially be a security issue. I was thinking that too. >If you can make sure that the site >providing the configs also has to provide some token that may help to >mitigate the issue. That sounds like a good idea. Some years ago we had to support an app which had to read a SOAP specification from a URL (limitation of their SOAP library), and we went to the effort of providing an internal static web server whose whole purpose was to provide that URL. The app still fetched a URL, but it was wired to fetch it from a totally internal resource. Cheers, Cameron Simpson >adil > >On Tue, Jun 04, 2019 at 03:51:11PM +0200, matar fall wrote: >> Got It. >> Thank for your reply. >> It is necessary for me to do this kind of configuration if it is possible. >> Suggestion of Carlos is a nice idea which I will check/explore. >> Thank You. Regards >> >> Le mar. 4 juin 2019 ? 15:11, Hippo a ?crit : >> >> > Why do you want to externalise the configuration? In other words, what are >> > the settings that you plan to modify in the external file? >> > >> > Depending on what it is, you could code your application to automatically >> > load the settings whenever it needs to, during runtime, instead of having >> > to get it from the config file. (Of course, if it's something major then >> > Carlos' suggestion of having a separate launch script would work better. >> > Depends on what you're trying to do). >> > >> > ?Badri >> *Cordialement.* >> *Matar FALL* >> *Etudiant en Machine Learning for Data Science ? l'Universit? Paris >> Descartes* >> *Tel: +33 07 51 53 95 18* From gergely at polonkai.eu Wed Jun 5 00:34:47 2019 From: gergely at polonkai.eu (Gergely Polonkai) Date: Wed, 5 Jun 2019 06:34:47 +0200 Subject: [Flask] Question of outsourcing flask app In-Reply-To: References: <001301d51af8$62e564f0$28b02ed0$@biz> Message-ID: Hello, what you outline is not a terrible idea, and not too hard to code. However, there are a lot of pitfalls, some of which were mentioned by others. First, you should download the config before you initialise your app. This isn?t hard, you can do it with external commands like proposed before, or a few lines of Python using the http or requests (and a lot more) libraries. When you have your file, you should check its integrity. Is this file what it claims to be? Was this file generated by a trusted party? You may ask the people who generate the file to cryptographically sign it so you can check it before deploying it. If the signature is not good, you can fall back to a previous, good file. All this is especially true if you download this file from a service on an external network so you can avoid man in the middle attacks. Now that you know you can trust the file, you should still check for other errors. We?re all humans and as such, make mistakes. The file might have syntax errors, conflicting configuration options like ?turn on caching? but without a cache backend set, or the likes. And finally, you can fire up your app! Happy Coding! Gergely On Tue, 4 Jun 2019, 20:51 matar fall, wrote: > Got it. > Thank You for sharing your knowledge. > I will handle and take into account all your suggestions. > Regards. > > Le mar. 4 juin 2019 ? 19:35, keith macdonald a > ?crit : > >> I agree with Adil about the security risk - how would you know what's in >> the >> remote file *before* it gets used? >> >> But, if you must go that route, how about running a Curl command from >> inside >> the Python code, just before the Flask app is initialized? With the Curl >> program saving the file to somewhere local. >> >> For example: >> >> # get remote file >> import os >> cmd = "C:/Curl/curl.exe www.test.fr/config.py -o C:/Download/config.py >> # or (instead of a Download folder) whatever folder is good for the local >> code. >> os.system(cmd) >> >> # now start Flask app >> import config as config >> from flask import Flask >> app = Flask(__name__) >> >> _______________________________________________ >> 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 ar at zeit.io Mon Jun 10 08:32:40 2019 From: ar at zeit.io (Arup Rakshit) Date: Mon, 10 Jun 2019 18:02:40 +0530 Subject: [Flask] pytest code from flask official tut "with" vs "no with" block Message-ID: Hi, In this piece of code: def test_login(client, auth): assert client.get('/auth/login').status_code == 200 response = auth.login() assert response.headers['Location'] == 'http://localhost/' with client: client.get('/?) # 1 assert session['user_id'] == 1 # 2 assert g.user['username'] == ?test? # 3 Why #1, #2 and #3 is wrapped into the with block, instead of writing them normally like: client.get('/') assert session['user_id'] == 1 assert g.user['username'] == 'test' I found the code from https://github.com/pallets/flask/blob/master/examples/tutorial/tests/test_auth.py#L67 Thanks, Arup Rakshit ar at zeit.io From badrihippo at gmail.com Mon Jun 10 08:37:47 2019 From: badrihippo at gmail.com (Hippo) Date: Mon, 10 Jun 2019 18:07:47 +0530 Subject: [Flask] pytest code from flask official tut "with" vs "no with" block In-Reply-To: References: Message-ID: Not sure about this case, but they usually use "with" when the object needs to be disabled or something after the block. For example, you'd use "with open('filename.txt', 'w') as file:" so that the file automatically gets closed after the "with" block is over. I'm guessing "client" works in a similar fashion. (Someone else could confirm: I'm a bit busy to investigate right now, sorry). ~Badri On Mon, 10 Jun 2019 at 18:03, Arup Rakshit wrote: > Hi, > > In this piece of code: > > def test_login(client, auth): > assert client.get('/auth/login').status_code == 200 > response = auth.login() > assert response.headers['Location'] == 'http://localhost/' > > with client: > client.get('/?) # 1 > assert session['user_id'] == 1 # 2 > assert g.user['username'] == ?test? # 3 > > Why #1, #2 and #3 is wrapped into the with block, instead of writing them > normally like: > > client.get('/') > assert session['user_id'] == 1 > assert g.user['username'] == 'test' > > I found the code from > https://github.com/pallets/flask/blob/master/examples/tutorial/tests/test_auth.py#L67 > > > Thanks, > > Arup Rakshit > ar at zeit.io > > > > _______________________________________________ > Flask mailing list > Flask at python.org > https://mail.python.org/mailman/listinfo/flask > -------------- next part -------------- An HTML attachment was scrubbed... URL: From harish77kumar4270 at gmail.com Mon Jun 10 13:28:13 2019 From: harish77kumar4270 at gmail.com (Harish Kumar) Date: Mon, 10 Jun 2019 22:58:13 +0530 Subject: [Flask] pytest code from flask official tut "with" vs "no with" block In-Reply-To: References: Message-ID: Hi Community folks I need a small help. We at https://quantamixsolutions.com/home developed a full-fledged social media platform in Flask but we had a hard time to integrate analytics from social media data like there are WordPress plugins. I was trying to integrate WordPress API in python which is available. Has anyone tried this before? https://pypi.org/project/wordpress-api/ The website for Quantamix Solutions is also based in python Flask. How to find more information as if one would like to rate one's website with other similar Flask based websites. Best regards, Harish On Mon, Jun 10, 2019 at 6:03 PM Arup Rakshit wrote: > Hi, > > In this piece of code: > > def test_login(client, auth): > assert client.get('/auth/login').status_code == 200 > response = auth.login() > assert response.headers['Location'] == 'http://localhost/' > > with client: > client.get('/?) # 1 > assert session['user_id'] == 1 # 2 > assert g.user['username'] == ?test? # 3 > > Why #1, #2 and #3 is wrapped into the with block, instead of writing them > normally like: > > client.get('/') > assert session['user_id'] == 1 > assert g.user['username'] == 'test' > > I found the code from > https://github.com/pallets/flask/blob/master/examples/tutorial/tests/test_auth.py#L67 > > > Thanks, > > Arup Rakshit > ar at zeit.io > > > > _______________________________________________ > Flask mailing list > Flask at python.org > https://mail.python.org/mailman/listinfo/flask > -- -------------- next part -------------- An HTML attachment was scrubbed... URL: From ar at zeit.io Mon Jun 10 14:42:45 2019 From: ar at zeit.io (Arup Rakshit) Date: Tue, 11 Jun 2019 00:12:45 +0530 Subject: [Flask] pytest code from flask official tut "with" vs "no with" block In-Reply-To: References: Message-ID: <47E94232-202C-43DA-97F9-DBD251B31C2C@zeit.io> Do not hijack others post, else create your own post. Thanks, Arup Rakshit ar at zeit.io > On 10-Jun-2019, at 10:58 PM, Harish Kumar wrote: > > Hi Community folks > > I need a small help. > > We at https://quantamixsolutions.com/home developed a full-fledged social media platform in Flask but we had a hard time to integrate analytics from social media data like there are WordPress plugins. > > I was trying to integrate WordPress API in python which is available. Has anyone tried this before? > > https://pypi.org/project/wordpress-api/ > > The website for Quantamix Solutions is also based in python Flask. > > How to find more information as if one would like to rate one's website with other similar Flask based websites. > > Best regards, > Harish > > > > > On Mon, Jun 10, 2019 at 6:03 PM Arup Rakshit wrote: > Hi, > > In this piece of code: > > def test_login(client, auth): > assert client.get('/auth/login').status_code == 200 > response = auth.login() > assert response.headers['Location'] == 'http://localhost/' > > with client: > client.get('/?) # 1 > assert session['user_id'] == 1 # 2 > assert g.user['username'] == ?test? # 3 > > Why #1, #2 and #3 is wrapped into the with block, instead of writing them normally like: > > client.get('/') > assert session['user_id'] == 1 > assert g.user['username'] == 'test' > > I found the code from https://github.com/pallets/flask/blob/master/examples/tutorial/tests/test_auth.py#L67 > > > Thanks, > > Arup Rakshit > ar at zeit.io > > > > _______________________________________________ > Flask mailing list > Flask at python.org > https://mail.python.org/mailman/listinfo/flask > > > -- > > From ar at zeit.io Wed Jun 12 16:31:29 2019 From: ar at zeit.io (Arup Rakshit) Date: Thu, 13 Jun 2019 02:01:29 +0530 Subject: [Flask] Flask RuntimeError: Working outside of application context. Message-ID: <33569EB0-FB17-4904-BD7E-54DA1B310CA7@zeit.io> Hello All, I have the following factory function. from flask import Flask, jsonify import os import pprint def create_app(test_config=None): """Create and configure an instance of the Flask application.""" app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( # a default secret that should be overridden by instance config SECRET_KEY="dev", # store the database in the instance folder DATABASE="awesome_recipes_dev", ) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile("config.py", silent=True) else: # load the test config if passed in app.config.update(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass from app import db db.init_app(app) @app.shell_context_processor def shell_context(): from app.models.recipe import Recipe return { "app": app, "db": db.get_db(), "pp": pprint.PrettyPrinter(indent=4).pprint, "Recipe": Recipe, } @app.route("/") def index(): return jsonify({"hello": "World"}) from .recipes.views import recipes_blueprint app.register_blueprint(recipes_blueprint) return app Now when I run flask shell I get error: Traceback (most recent call last): File "/Users/aruprakshit/Code/flask/awesome_recipes/backend/venv/bin/flask", line 11, in sys.exit(main()) File "/Users/aruprakshit/Code/flask/awesome_recipes/backend/venv/lib/python3.7/site-packages/flask/cli.py", line 906, in main cli.main(args=args, prog_name=name) File "/Users/aruprakshit/Code/flask/awesome_recipes/backend/venv/lib/python3.7/site-packages/flask/cli.py", line 569, in main return super(FlaskGroup, self).main(*args, **kwargs) File "/Users/aruprakshit/Code/flask/awesome_recipes/backend/venv/lib/python3.7/site-packages/click/core.py", line 717, in main rv = self.invoke(ctx) File "/Users/aruprakshit/Code/flask/awesome_recipes/backend/venv/lib/python3.7/site-packages/click/core.py", line 1137, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/Users/aruprakshit/Code/flask/awesome_recipes/backend/venv/lib/python3.7/site-packages/click/core.py", line 956, in invoke return ctx.invoke(self.callback, **ctx.params) File "/Users/aruprakshit/Code/flask/awesome_recipes/backend/venv/lib/python3.7/site-packages/click/core.py", line 555, in invoke return callback(*args, **kwargs) File "/Users/aruprakshit/Code/flask/awesome_recipes/backend/venv/lib/python3.7/site-packages/click/decorators.py", line 17, in new_func return f(get_current_context(), *args, **kwargs) File "/Users/aruprakshit/Code/flask/awesome_recipes/backend/venv/lib/python3.7/site-packages/flask/cli.py", line 418, in decorator with __ctx.ensure_object(ScriptInfo).load_app().app_context(): File "/Users/aruprakshit/Code/flask/awesome_recipes/backend/venv/lib/python3.7/site-packages/flask/cli.py", line 381, in load_app app = locate_app(self, import_name, name) File "/Users/aruprakshit/Code/flask/awesome_recipes/backend/venv/lib/python3.7/site-packages/flask/cli.py", line 255, in locate_app return find_best_app(script_info, module) File "/Users/aruprakshit/Code/flask/awesome_recipes/backend/venv/lib/python3.7/site-packages/flask/cli.py", line 77, in find_best_app app = call_factory(script_info, app_factory) File "/Users/aruprakshit/Code/flask/awesome_recipes/backend/venv/lib/python3.7/site-packages/flask/cli.py", line 117, in call_factory return app_factory() File "/Users/aruprakshit/Code/flask/awesome_recipes/backend/app/__init__.py", line 49, in create_app from .recipes.views import recipes_blueprint File "/Users/aruprakshit/Code/flask/awesome_recipes/backend/app/recipes/views.py", line 3, in from ..models.recipe import Recipe File "/Users/aruprakshit/Code/flask/awesome_recipes/backend/app/models/recipe.py", line 4, in class Recipe: File "/Users/aruprakshit/Code/flask/awesome_recipes/backend/app/models/recipe.py", line 6, in Recipe __db__ = get_db() File "/Users/aruprakshit/Code/flask/awesome_recipes/backend/app/db.py", line 22, in get_db if "db" not in g: File "/Users/aruprakshit/Code/flask/awesome_recipes/backend/venv/lib/python3.7/site-packages/werkzeug/local.py", line 380, in __contains__ = lambda x, i: i in x._get_current_object() File "/Users/aruprakshit/Code/flask/awesome_recipes/backend/venv/lib/python3.7/site-packages/werkzeug/local.py", line 307, in _get_current_object return self.__local() File "/Users/aruprakshit/Code/flask/awesome_recipes/backend/venv/lib/python3.7/site-packages/flask/globals.py", line 44, in _lookup_app_object raise RuntimeError(_app_ctx_err_msg) RuntimeError: Working outside of application context. I am not able to figure out where I need to push the app context to make it work. Can anyone help me? My code is https://gitlab.com/aruprakshit/flask_awesome_recipes/tree/master/app Thanks, Arup Rakshit ar at zeit.io From coreybrett at gmail.com Sat Jun 15 09:40:55 2019 From: coreybrett at gmail.com (Corey Boyle) Date: Sat, 15 Jun 2019 09:40:55 -0400 Subject: [Flask] Flask-Login / multiple auth backends Message-ID: Has anyone ever done different logins for different Blueprints? I have a site which is mostly public, except one Blueprint that requires authentication using Flask-Login which uses LDAP as the backend. Now I would like to add another Blueprint that uses a traditional registration based setup. How could I configure Flask-Login to work for both? -------------- next part -------------- An HTML attachment was scrubbed... URL: From savageapple850 at gmail.com Tue Jun 18 02:28:03 2019 From: savageapple850 at gmail.com (Cravan) Date: Tue, 18 Jun 2019 14:28:03 +0800 Subject: [Flask] Flask app syntax error Message-ID: <279A41A8-642C-4612-96F7-ABDB26B04045@gmail.com> I'm setting up a flask app variable, but app throws up a syntax error. Can someone please help thanks. I literally can't tell whats wrong, and have already looked out for any forgotten brackets and spacing, but I might be wrong haha ```` import os import sqlalchemy from flask import Flask, render_template, request, session, redirect, url_for, escape from flask_session import Session from sqlalchemy import create_engine engine = create_engine(os.getenv("DATABASE_URL") app = Flask(__name__) @app.route("/") def index(): ??? movies = engine.execute("SELECT * FROM movies").fetchall() ??? return render_template("index.html", movies=movies) ```` ```` ##################### Traceback (most recent call last): ? File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask/cli. py", line 332, in __call__ ??? self._flush_bg_loading_exception() ? File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask/cli. py", line 320, in _flush_bg_loading_exception ??? reraise(*exc_info) ? File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask/_com pat.py", line 36, in reraise ??? raise value ? File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask/cli. py", line 309, in _load_app ??? self._load_unlocked() ? File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask/cli. py", line 324, in _load_unlocked self._app = rv = self.loader() ? File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask/cli. py", line 381, in load_app ??? app = locate_app(self, import_name, name) ? File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask/cli. py", line 236, in locate_app ??? __import__(module_name) File "/Users/CPZ/Desktop/cepsummative3/main.py", line 7 ??? app = Flask(__name__) ????? ^ SyntaxError: invalid syntax -------------- next part -------------- An HTML attachment was scrubbed... URL: From matthew at jrgnsn.net Tue Jun 18 02:32:08 2019 From: matthew at jrgnsn.net (Matthew Jorgensen) Date: Tue, 18 Jun 2019 01:32:08 -0500 Subject: [Flask] Flask app syntax error In-Reply-To: <279A41A8-642C-4612-96F7-ABDB26B04045@gmail.com> References: <279A41A8-642C-4612-96F7-ABDB26B04045@gmail.com> Message-ID: > On Jun 18, 2019, at 01:28, Cravan wrote: > > engine = create_engine(os.getenv("DATABASE_URL") This needs the second closing parenthesis. `engine = create_engine(os.getenv("DATABASE_URL"))` Matthew From imonikemohammed at gmail.com Tue Jun 18 12:01:32 2019 From: imonikemohammed at gmail.com (Abdul Mohammed) Date: Tue, 18 Jun 2019 17:01:32 +0100 Subject: [Flask] Can't get Werkzeug check_password_hash method to work Message-ID: I am trying to learn to use the Flask framework. I am trying to implement Werkzeug's password hashing and running into problems. My code looks like this: ...from flask import render_template,request,jsonify, url_for, flashfrom flask_login import login_required, login_userfrom models import Userfrom auth.forms import LoginForm... @app.route('/',methods=['GET','POST'])def index(): form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user is not None and user.check_password(form.password.data): login_user(user, form.remember_me.data) return redirect(request.args.get('next') or url_for('dashboard')) flash('Invalid username or password.') return render_template('auth/login.html', form=form) I have confirmed that the query successfully returns the user. It is at the very next line that program execution stops. Since I am sure that the user is returned from the database, it seems my implementation of the check_password function is causing the problem. My Model looks like this: from flask_login import UserMixinfrom flask_login import LoginManagerfrom dbobject import dbfrom werkzeug.security import generate_password_hash, check_password_hash login_manager = LoginManager() class User(UserMixin, db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key = True) email = db.Column(db.String(64), unique=True, index=True) username = db.Column(db.String(64), unique=True, index=True) password_hash = db.Column(db.String(128)) @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) def set_password(self, password): self.password_hash = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.password_hash, password) The app is running off a MySQL database and I used the MySQL Password() function to generate the password hashes stored in the database. Please can anyone give me pointers to what I might be doing wrong? Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ziirish at ziirish.info Tue Jun 18 12:14:19 2019 From: ziirish at ziirish.info (Ziirish) Date: Tue, 18 Jun 2019 18:14:19 +0200 Subject: [Flask] Can't get Werkzeug check_password_hash method to work In-Reply-To: References: Message-ID: <20190618161418.4rjaejhnsn2kbw33@mail.ziirish.info> * On Tuesday, June 18, 2019 at 05:01 PM +0100, Abdul Mohammed wrote: > > def set_password(self, password): > self.password_hash = generate_password_hash(password) > > def check_password(self, password): > return check_password_hash(self.password_hash, password) > > > The app is running off a MySQL database and I used the MySQL Password() > function to generate the password hashes stored in the database. Please > can anyone give me pointers to what I might be doing wrong? So you mean the password_hash value has actually not been initialized with generate_password_hash? That would explain why check_password_hash() doesn't work, because MySQL Password() function and generate_password_hash() don't return the same thing. From imonikemohammed at gmail.com Tue Jun 18 12:27:26 2019 From: imonikemohammed at gmail.com (Abdul Mohammed) Date: Tue, 18 Jun 2019 17:27:26 +0100 Subject: [Flask] Can't get Werkzeug check_password_hash method to work In-Reply-To: <20190618161418.4rjaejhnsn2kbw33@mail.ziirish.info> References: <20190618161418.4rjaejhnsn2kbw33@mail.ziirish.info> Message-ID: Thanks Ziirish. I had a suspicion but I didn't know enough about password hashing to be sure. I used the MySQL Password() function because I am building the app in parts. I had done a login module but not a registration module, which is where I would have used generate_password_hash. I just wanted to test the login module and that I had set up SQLAlchemy. I will work on my registration model making sure to use generate_password_hash and see how it goes. Many thanks again. On Tue, Jun 18, 2019 at 5:14 PM Ziirish wrote: > * On Tuesday, June 18, 2019 at 05:01 PM +0100, Abdul Mohammed < > imonikemohammed at gmail.com> wrote: > > > > def set_password(self, password): > > self.password_hash = generate_password_hash(password) > > > > def check_password(self, password): > > return check_password_hash(self.password_hash, password) > > > > > > The app is running off a MySQL database and I used the MySQL Password() > > function to generate the password hashes stored in the database. Please > > can anyone give me pointers to what I might be doing wrong? > > So you mean the password_hash value has actually not been initialized with > generate_password_hash? > That would explain why check_password_hash() doesn't work, because MySQL > Password() function and generate_password_hash() don't return the same > thing. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From imonikemohammed at gmail.com Tue Jun 18 12:28:34 2019 From: imonikemohammed at gmail.com (Abdul Mohammed) Date: Tue, 18 Jun 2019 17:28:34 +0100 Subject: [Flask] Can't get Werkzeug check_password_hash method to work In-Reply-To: References: <20190618161418.4rjaejhnsn2kbw33@mail.ziirish.info> Message-ID: *and that I had set up SQLAlchemy correctly. On Tue, Jun 18, 2019 at 5:27 PM Abdul Mohammed wrote: > Thanks Ziirish. > I had a suspicion but I didn't know enough about password hashing to be > sure. I used the MySQL Password() function because I am building > the app in parts. I had done a login module but not a registration module, > which is where I would have used generate_password_hash. I just wanted to > test > the login module and that I had set up SQLAlchemy. I will work on my > registration model making sure to use generate_password_hash and see how it > goes. > > Many thanks again. > > On Tue, Jun 18, 2019 at 5:14 PM Ziirish wrote: > >> * On Tuesday, June 18, 2019 at 05:01 PM +0100, Abdul Mohammed < >> imonikemohammed at gmail.com> wrote: >> > >> > def set_password(self, password): >> > self.password_hash = generate_password_hash(password) >> > >> > def check_password(self, password): >> > return check_password_hash(self.password_hash, password) >> > >> > >> > The app is running off a MySQL database and I used the MySQL Password() >> > function to generate the password hashes stored in the database. Please >> > can anyone give me pointers to what I might be doing wrong? >> >> So you mean the password_hash value has actually not been initialized with >> generate_password_hash? >> That would explain why check_password_hash() doesn't work, because MySQL >> Password() function and generate_password_hash() don't return the same >> thing. >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From aco at miza.org Tue Jun 18 14:28:02 2019 From: aco at miza.org (Aco Strkalj) Date: Tue, 18 Jun 2019 13:28:02 -0500 Subject: [Flask] Can't get Werkzeug check_password_hash method to work In-Reply-To: References: <20190618161418.4rjaejhnsn2kbw33@mail.ziirish.info> Message-ID: <2E99D817-324E-41F8-A1CA-6FD4E9C7D56C@miza.org> What kind of app you building? > On Jun 18, 2019, at 11:28 AM, Abdul Mohammed wrote: > > *and that I had set up SQLAlchemy correctly. > >> On Tue, Jun 18, 2019 at 5:27 PM Abdul Mohammed wrote: >> Thanks Ziirish. >> I had a suspicion but I didn't know enough about password hashing to be sure. I used the MySQL Password() function because I am building >> the app in parts. I had done a login module but not a registration module, which is where I would have used generate_password_hash. I just wanted to test >> the login module and that I had set up SQLAlchemy. I will work on my registration model making sure to use generate_password_hash and see how it goes. >> >> Many thanks again. >> >>> On Tue, Jun 18, 2019 at 5:14 PM Ziirish wrote: >>> * On Tuesday, June 18, 2019 at 05:01 PM +0100, Abdul Mohammed wrote: >>> > >>> > def set_password(self, password): >>> > self.password_hash = generate_password_hash(password) >>> > >>> > def check_password(self, password): >>> > return check_password_hash(self.password_hash, password) >>> > >>> > >>> > The app is running off a MySQL database and I used the MySQL Password() >>> > function to generate the password hashes stored in the database. Please >>> > can anyone give me pointers to what I might be doing wrong? >>> >>> So you mean the password_hash value has actually not been initialized with >>> generate_password_hash? >>> That would explain why check_password_hash() doesn't work, because MySQL >>> Password() function and generate_password_hash() don't return the same thing. > _______________________________________________ > Flask mailing list > Flask at python.org > https://mail.python.org/mailman/listinfo/flask -------------- next part -------------- An HTML attachment was scrubbed... URL: From imonikemohammed at gmail.com Tue Jun 18 18:20:19 2019 From: imonikemohammed at gmail.com (Abdul Mohammed) Date: Tue, 18 Jun 2019 23:20:19 +0100 Subject: [Flask] Can't get Werkzeug check_password_hash method to work In-Reply-To: <2E99D817-324E-41F8-A1CA-6FD4E9C7D56C@miza.org> References: <20190618161418.4rjaejhnsn2kbw33@mail.ziirish.info> <2E99D817-324E-41F8-A1CA-6FD4E9C7D56C@miza.org> Message-ID: It's an app for vehicle routing. The code provided is for logging into the app. On Tue, Jun 18, 2019, 7:28 PM Aco Strkalj wrote: > What kind of app you building? > > On Jun 18, 2019, at 11:28 AM, Abdul Mohammed > wrote: > > *and that I had set up SQLAlchemy correctly. > > On Tue, Jun 18, 2019 at 5:27 PM Abdul Mohammed > wrote: > >> Thanks Ziirish. >> I had a suspicion but I didn't know enough about password hashing to be >> sure. I used the MySQL Password() function because I am building >> the app in parts. I had done a login module but not a registration >> module, which is where I would have used generate_password_hash. I just >> wanted to test >> the login module and that I had set up SQLAlchemy. I will work on my >> registration model making sure to use generate_password_hash and see how it >> goes. >> >> Many thanks again. >> >> On Tue, Jun 18, 2019 at 5:14 PM Ziirish wrote: >> >>> * On Tuesday, June 18, 2019 at 05:01 PM +0100, Abdul Mohammed < >>> imonikemohammed at gmail.com> wrote: >>> > >>> > def set_password(self, password): >>> > self.password_hash = generate_password_hash(password) >>> > >>> > def check_password(self, password): >>> > return check_password_hash(self.password_hash, password) >>> > >>> > >>> > The app is running off a MySQL database and I used the MySQL Password() >>> > function to generate the password hashes stored in the database. Please >>> > can anyone give me pointers to what I might be doing wrong? >>> >>> So you mean the password_hash value has actually not been initialized >>> with >>> generate_password_hash? >>> That would explain why check_password_hash() doesn't work, because MySQL >>> Password() function and generate_password_hash() don't return the same >>> thing. >>> >> _______________________________________________ > Flask mailing list > Flask at python.org > https://mail.python.org/mailman/listinfo/flask > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From savageapple850 at gmail.com Tue Jun 18 22:56:10 2019 From: savageapple850 at gmail.com (Cravan) Date: Wed, 19 Jun 2019 10:56:10 +0800 Subject: [Flask] Unexpected result when running flask application Message-ID: Hi all, ??????????????? I am experiencing an unexpected result when I try to run my flask application. The movie.html page prints out nothing except those in the

. This appears on my webpage: I want it to print out all the stuff related to the movie in my sql table, e.g. year, runtime etc. How should I modify my code then? Also, when trying out search.html, it prints method not allowed for the requested URL. How should I rectify this? Cravan -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image001.png Type: image/png Size: 37844 bytes Desc: not available URL: -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: main.py Type: text/x-python-script Size: 3097 bytes Desc: not available URL: -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: users.sql Type: application/octet-stream Size: 83 bytes Desc: not available URL: From savageapple850 at gmail.com Wed Jun 19 00:42:31 2019 From: savageapple850 at gmail.com (Cravan) Date: Wed, 19 Jun 2019 12:42:31 +0800 Subject: [Flask] Unexpected result when running flask application Message-ID: From: cool kid Date: Wednesday, 19 June 2019 at 12:08 PM To: Frost Ming Subject: Re: [Flask] Unexpected result when running flask application Dear Frost, Sorry, but im a beginner at coding and am not so familiar, hence I require more elaboration. Although you mentioned that I returned early, I embedded my search.html within a link in my movies.html page, and im trying to use my info down in the search function, hence I have completely no idea where to put my search.html render template. Kindly refer to the updated code. Btw the movie page still doesn?t load after I replaced the argument. From: Frost Ming Date: Wednesday, 19 June 2019 at 11:48 AM To: cool kid Subject: Re: [Flask] Unexpected result when running flask application In the search view function, you returned early so the logic below is never touched. In the movie view function, why did you drop the `movie_title` argument? The solutions lie in the above statement and don't ask for them again, please. Cravan ?2019?6?19??? ??11:35??? However, I have changed with both your suggestions for movie=movie and request.args, but it still isn?t working. From: Frost Ming Date: Wednesday, 19 June 2019 at 11:34 AM To: cool kid Subject: Re: [Flask] Unexpected result when running flask application The root cause is the solution itself, IMO it is clear enough. Just pass `movie=movie` to `render_template`, you must have forgotten it? Cravan ?2019?6?19??? ??11:31??? Thank you Frost, may I know how to rectify this? Cravan From: Frost Ming Date: Wednesday, 19 June 2019 at 11:23 AM To: cool kid Subject: Re: [Flask] Unexpected result when running flask application You didn't pass any movie data to the view template. Cravan ?2019?6?19??? ??10:56??? Hi all, I am experiencing an unexpected result when I try to run my flask application. The movie.html page prints out nothing except those in the

. This appears on my webpage: I want it to print out all the stuff related to the movie in my sql table, e.g. year, runtime etc. How should I modify my code then? Also, when trying out search.html, it prints method not allowed for the requested URL. How should I rectify this? Cravan _______________________________________________ Flask mailing list Flask at python.org https://mail.python.org/mailman/listinfo/flask -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image001.png Type: image/png Size: 48240 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image002.png Type: image/png Size: 24643 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image003.png Type: image/png Size: 37848 bytes Desc: not available URL: -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: users.sql Type: application/octet-stream Size: 83 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: main.py Type: text/x-python-script Size: 2905 bytes Desc: not available URL: From srshanmugavel at gmail.com Fri Jun 21 23:18:51 2019 From: srshanmugavel at gmail.com (shanmugavel Subramani) Date: Sat, 22 Jun 2019 08:48:51 +0530 Subject: [Flask] Getting old value from DB Message-ID: I have below DB setup in my code. There are few APIs in my code and few controllers which will serve templates and corresponding form POST handlers. The problem is when i call /details?stu_id=abcd the handler decorator gets invoked and I have a db query to check if the given stu_id is present in my table(Student). I am randomly getting the passed id is not exists in my table error. But when i checked manually its present. after few refreshes its working fine. I dont get this problem in the APIs Sometimes it happens in the later stages of the pages. I update status in each page movement. When i read status from the same table using above StuHelper methods it gives me the old value but when i checked in db manually it has the correct value. after a refresh, it returns me some other value which i updated in sequence and after few refreshes, it gives me the right value from db. Then i added *app.teardown_appcontext(close_db)* line but it's not working still. ```app/extenstions.py from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() app/__init__.py from app.extensions import db def close_db(e=None): db = g.pop('db', None) if db is not None: db.close() def initdb(db): print("init database...") try: from app.models import Student db.create_all() except Exception as e: print(e) def creat_app(config_name): app.config.from_object(app_config[config_name]) db.init_app(app) app.app_context().push() app.teardown_appcontext(close_db) initdb(db) controllers/student.py @student_blueprint('/details', methods=['GET','POST']) @handler def stu_details() print("blah") app/utils.py def handler(f): @wraps(f) def wrapper(*args, **kwargs): stu_id = request.args.get("stu_id") if not stu_id: logger.debug("There is no stu_id in the query string") _return_fun = abort(404) else: try: stu_helper= db_handler.StuHelper(stu_id) current_status = stu_helper.get_status() if not current_status: logger.debug("URL has not been setup") abort(404) try: _return_fun = f(*args, **kwargs) except: _return_fun = abort(500) return _return_fun return wrapper db_hanlder.py class StuHelper(object): def __new__(cls, stu_id): stu_obj = Student.query_filter_by(stu_id=stu_id).first() if not stu_obj: print("stu_id not exists {0}".format(stu_id))``` I should be getting stu_id from the table when I query from ORM and correct status value in subsequent pages query. I feel like flask maintains a stack which gives me random behavior here. Can someone help me solving this problem? -------------- next part -------------- An HTML attachment was scrubbed... URL: From cs at cskk.id.au Sat Jun 22 19:18:59 2019 From: cs at cskk.id.au (Cameron Simpson) Date: Sun, 23 Jun 2019 09:18:59 +1000 Subject: [Flask] Getting old value from DB In-Reply-To: References: Message-ID: <20190622231859.GA15112@cskk.homeip.net> On 22Jun2019 08:48, shanmugavel Subramani wrote: >I have below DB setup in my code. There are few APIs in my code and few >controllers which will serve templates and corresponding form POST >handlers. The problem is when i call /details?stu_id=abcd the handler >decorator gets invoked and I have a db query to check if the given stu_id >is present in my table(Student). I am randomly getting the passed id is not >exists in my table error. But when i checked manually its present. after >few refreshes its working fine. I dont get this problem in the APIs > >Sometimes it happens in the later stages of the pages. I update status in >each page movement. When i read status from the same table using above >StuHelper methods it gives me the old value but when i checked in db >manually it has the correct value. after a refresh, it returns me some >other value which i updated in sequence and after few refreshes, it gives >me the right value from db. [...] >I should be getting stu_id from the table when I query from ORM and >correct >status value in subsequent pages query. I feel like flask maintains a stack >which gives me random behavior here. Can someone help me solving this >problem? Is it possible that the new stu_id row is created by a transaction which has not been committed? I don't see any explicit transaction stuff in the code you quoted, but since flask is multithreaded it is possible for the creating transaction to be still open (uncommitted) when your query is made. Depending on what is going on. Have you tried having your stu_id creation code use an explicit transaction: with session->begin(): ... insert student data so that the transaction is definitiely committed when you leave the "with" above? Otherwise you may be operating inside a longer lived transaction. I'm just guessing here as its not clear from the code, but (a) transactions do conceal their sid effects until closed/committed and (b) transactions are often implicitly used if you don't manage them yourself and (c) they will produce effects like this as a consequence. Cheers, Cameron Simpson From spaceman at antispaceman.com Sun Jun 23 13:22:04 2019 From: spaceman at antispaceman.com (spaceman) Date: Sun, 23 Jun 2019 18:22:04 +0100 Subject: [Flask] Getting old value from DB In-Reply-To: <20190622231859.GA15112@cskk.homeip.net> References: <20190622231859.GA15112@cskk.homeip.net> Message-ID: <20190623172204.DBB34C9D@enterprise.home.antispaceman.com> Cameron Simpson wrote: > On 22Jun2019 08:48, shanmugavel Subramani wrote: > >I have below DB setup in my code. There are few APIs in my code and few > >controllers which will serve templates and corresponding form POST > >handlers. The problem is when i call /details?stu_id=abcd the handler > >decorator gets invoked and I have a db query to check if the given stu_id > >is present in my table(Student). I am randomly getting the passed id is not > >exists in my table error. But when i checked manually its present. after > >few refreshes its working fine. I dont get this problem in the APIs > > Is it possible that the new stu_id row is created by a transaction which > has not been committed? I don't see any explicit transaction stuff in > the code you quoted, but since flask is multithreaded it is possible for > the creating transaction to be still open (uncommitted) when your query > is made. Depending on what is going on. > > I'm just guessing here as its not clear from the code, but (a) > transactions do conceal their sid effects until closed/committed and (b) > transactions are often implicitly used if you don't manage them yourself > and (c) they will produce effects like this as a consequence. Adding to what Cameron said that this something to do transactions (although as far I am aware at least with Flask-SQLAlchemy autocommit is enabled by default). I had a similar problem where changes to the database would not show up between threads. The problem was solved for me by fiddling with the transaction isolation level with MySQL (it exists in other DBs as well). I had to set mine to read-commited to get data that was committed to be readable. There are few different levels, I suggest you do some research to find the one that works for you. The default for MariaDB as far as I remember wasn't sane (especially for guy coming from PHP). I am not a database expert, I am sure there someone around here who can fill you in as to what "Transaction Isolation" is and why it is necessary. Regards, spaceman From coreybrett at gmail.com Tue Jun 25 08:19:00 2019 From: coreybrett at gmail.com (Corey Boyle) Date: Tue, 25 Jun 2019 08:19:00 -0400 Subject: [Flask] flask run reloader and vscode Message-ID: Anyone have trouble with the reloader not catching all file edits when combined with vscode? Sometimes I'll get an exception when I hit a page about syntax, but just hitting the page a second time will clear the error. It's almost like it's using multiple threads. From savageapple850 at gmail.com Tue Jun 25 10:04:49 2019 From: savageapple850 at gmail.com (Cravan) Date: Tue, 25 Jun 2019 22:04:49 +0800 Subject: [Flask] Unexpected result when viewing results from a sql query Message-ID: <32D64DFB-8E7B-451F-B999-1EB2BB4DB7E6@gmail.com> Hi all, I?m working on the same movie review project as before, but I recently tried to create a new search module for my search function, which is to search for the movie?s imdbid. Each movie has its own unique imdbid, but when I search for a single unique imdbid, somehow all the movies pop out. Can someone point out the source of the problem? On a side note, I tried to include a print statement in each condition statement, but nothing is printed, and I tried fetchone instead of fetchall, but it didn?t work either. Thanks in advance! Here is my results function: ```` @app.route("/movie_results") def movie_results(): name = request.args.get("movie.title") year = request.args.get("movie.year") imdbid = request.args.get("movie.imdbid") name_pattern = "%" + name + "%" if year == '' or None and imdbid == '' or None: search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE title ILIKE :movie_title') movie_specific = engine.execute(search_movie_statement, movie_title=name_pattern).fetchall() if len(movie_specific) != 0 and movie_specific is not None: return render_template("movie_specific.html", movie_specific=movie_specific) if len(movie_specific) == 0: return render_template("error2.html", message="No such movie.") elif name == '' or None and imdbid == '' or None: search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE year = :year') movie_specific = engine.execute(search_movie_statement, year=year).fetchall() if len(movie_specific) != 0 and movie_specific is not None: return render_template("movie_specific.html", movie_specific=movie_specific) if len(movie_specific) == 0: return render_template("error2.html", message="No such movie.") elif name == '' or None and year == '' or None: search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE "imdbID" = :imdbId') movie_specific = engine.execute(search_movie_statement, imdbId=imdbid).fetchall() if len(movie_specific) != 0 and movie_specific is not None: return render_template("movie_specific.html", movie_specific=movie_specific) if len(movie_specific) == 0: return render_template("error2.html", message="No such movie.") elif name == '' or None: print(name) search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE "imdbID" = :imdbid AND year = :year') movie_specific = engine.execute(search_movie_statement, imdbid=imdbid, year=year).fetchall() if len(movie_specific) != 0 and movie_specific is not None: return render_template("movie_specific.html", movie_specific=movie_specific) if len(movie_specific) == 0: return render_template("error2.html", message="No such movie.") elif year == '' or None: search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE "imdbID" = :imdbid and title ILIKE :movie_title') movie_specific = engine.execute(search_movie_statement, imdbid=imdbid, movie_title=name_pattern).fetchall() if len(movie_specific) != 0 and movie_specific is not None: return render_template("movie_specific.html", movie_specific=movie_specific) if len(movie_specific) == 0: return render_template("error2.html", message="No such movie.") elif imdbid == '' or None: search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE year = :year and title ILIKE :movie_title') movie_specific = engine.execute(search_movie_statement, year=year, movie_title=name_pattern).fetchall() if len(movie_specific) != 0 and movie_specific is not None: return render_template("movie_specific.html", movie_specific=movie_specific) if len(movie_specific) == 0: return render_template("error2.html", message="No such movie.") elif name != None and name != '' and year != '' and year != None and imdbid != '' and imdbid != None: search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE year = :year and title ILIKE :movie_title and imdbID = :imdbid') movie_specific = engine.execute(search_movie_statement, year=year, movie_title=name_pattern, imdbid=imdbid).fetchall() if len(movie_specific) != 0 and movie_specific is not None: return render_template("movie_specific.html", movie_specific=movie_specific) if len(movie_specific) == 0: return render_template("error2.html", message="No such movie.") ```` Here is my movie table: ```` CREATE TABLE movies ( "title" TEXT UNIQUE NOT NULL, "year" INTEGER NOT NULL, "runtime" INTEGER NOT NULL, "imdbID" VARCHAR NOT NULL, "imdbRating" NUMERIC NOT NULL ); ```` Thanks, Cravan -------------- next part -------------- An HTML attachment was scrubbed... URL: From spaceman at antispaceman.com Tue Jun 25 14:11:21 2019 From: spaceman at antispaceman.com (spaceman) Date: Tue, 25 Jun 2019 19:11:21 +0100 Subject: [Flask] Unexpected result when running flask application In-Reply-To: References: Message-ID: <20190625181128.2FC6421@enterprise.home.antispaceman.com> Cravan wrote: > Hi all, > > I am experiencing an unexpected result > when I try to run my flask application. The movie.html page prints out > nothing except those in the

. This appears on my webpage: > {% for movie in movie %} > > Title: {{movie_title}} > Year: {{movie.year}} > Runtime: {{movie.runtime}} > ImdbID: {{movie.imdbID}} > ImdbRating: {{movie.imdbRating}} > > {% endfor %} That should be '{% for movie in movies %}' by my reckoning. @app.route only allows GET by default so [1]: @app.route("/search", methods=['GET', 'POST']) Regards, spaceman 1: http://flask.pocoo.org/docs/1.0/api/#url-route-registrations From fiskomaten at gmail.com Wed Jun 26 05:57:10 2019 From: fiskomaten at gmail.com (=?UTF-8?B?U8O4cmVuIFBpbGfDpXJk?=) Date: Wed, 26 Jun 2019 11:57:10 +0200 Subject: [Flask] Unexpected result when viewing results from a sql query In-Reply-To: <32D64DFB-8E7B-451F-B999-1EB2BB4DB7E6@gmail.com> References: <32D64DFB-8E7B-451F-B999-1EB2BB4DB7E6@gmail.com> Message-ID: On Tue, Jun 25, 2019 at 4:06 PM Cravan wrote: > > Hi all, > > I?m working on the same movie review project as before, but I recently tried to create a new search module for my search function, which is to search for the movie?s imdbid. Each movie has its own unique imdbid, but when I search for a single unique imdbid, somehow all the movies pop out. Can someone point out the source of the problem? On a side note, I tried to include a print statement in each condition statement, but nothing is printed, and I tried fetchone instead of fetchall, but it didn?t work either. Thanks in advance! > > Here is my results function: > > ```` > > @app.route("/movie_results") > > def movie_results(): > > name = request.args.get("movie.title") > > year = request.args.get("movie.year") > > imdbid = request.args.get("movie.imdbid") > > name_pattern = "%" + name + "%" > > if year == '' or None and imdbid == '' or None: > > search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE title ILIKE :movie_title') > > movie_specific = engine.execute(search_movie_statement, movie_title=name_pattern).fetchall() > > if len(movie_specific) != 0 and movie_specific is not None: > > return render_template("movie_specific.html", movie_specific=movie_specific) > > if len(movie_specific) == 0: > > return render_template("error2.html", message="No such movie.") > > elif name == '' or None and imdbid == '' or None: > > search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE year = :year') > > movie_specific = engine.execute(search_movie_statement, year=year).fetchall() > > if len(movie_specific) != 0 and movie_specific is not None: > > return render_template("movie_specific.html", movie_specific=movie_specific) > > if len(movie_specific) == 0: > > return render_template("error2.html", message="No such movie.") > > > > elif name == '' or None and year == '' or None: > > search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE "imdbID" = :imdbId') > > movie_specific = engine.execute(search_movie_statement, imdbId=imdbid).fetchall() > > if len(movie_specific) != 0 and movie_specific is not None: > > return render_template("movie_specific.html", movie_specific=movie_specific) > > if len(movie_specific) == 0: > > return render_template("error2.html", message="No such movie.") > > > > elif name == '' or None: > > print(name) > > search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE "imdbID" = :imdbid AND year = :year') > > movie_specific = engine.execute(search_movie_statement, imdbid=imdbid, year=year).fetchall() > > if len(movie_specific) != 0 and movie_specific is not None: > > return render_template("movie_specific.html", movie_specific=movie_specific) > > if len(movie_specific) == 0: > > return render_template("error2.html", message="No such movie.") > > > > elif year == '' or None: > > search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE "imdbID" = :imdbid and title ILIKE :movie_title') > > movie_specific = engine.execute(search_movie_statement, imdbid=imdbid, movie_title=name_pattern).fetchall() > > if len(movie_specific) != 0 and movie_specific is not None: > > return render_template("movie_specific.html", movie_specific=movie_specific) > > if len(movie_specific) == 0: > > return render_template("error2.html", message="No such movie.") > > > > elif imdbid == '' or None: > > search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE year = :year and title ILIKE :movie_title') > > movie_specific = engine.execute(search_movie_statement, year=year, movie_title=name_pattern).fetchall() > > if len(movie_specific) != 0 and movie_specific is not None: > > return render_template("movie_specific.html", movie_specific=movie_specific) > > if len(movie_specific) == 0: > > return render_template("error2.html", message="No such movie.") > > > > elif name != None and name != '' and year != '' and year != None and imdbid != '' and imdbid != None: > > search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE year = :year and title ILIKE :movie_title and imdbID = :imdbid') > > movie_specific = engine.execute(search_movie_statement, year=year, movie_title=name_pattern, imdbid=imdbid).fetchall() > > if len(movie_specific) != 0 and movie_specific is not None: > > return render_template("movie_specific.html", movie_specific=movie_specific) > > if len(movie_specific) == 0: > > return render_template("error2.html", message="No such movie.") > > ```` > > Here is my movie table: > > ```` > > CREATE TABLE movies ( > > "title" TEXT UNIQUE NOT NULL, > > "year" INTEGER NOT NULL, > > "runtime" INTEGER NOT NULL, > > "imdbID" VARCHAR NOT NULL, > > "imdbRating" NUMERIC NOT NULL > > ); > > ```` > > Thanks, > > Cravan > > > > _______________________________________________ > Flask mailing list > Flask at python.org > https://mail.python.org/mailman/listinfo/flask """ Beaware that you are using `or` wrong x == y or z is equivalent to (x == y) or (z) So you have a lot of conditions depending on None to be true, which will always fail If you just want to test if something is falsey use `not x` so instead of if `if x == "" or x is None` you could just write `if not x` Also you have a lot of repetition in your code making it very hard to reason about. I made a cleaner version. In general this way of building search queries often explodes in cases. You will end up with 2^n cases where n is the number of arguments that can either be there or not. In your case there should be 2^3=8 cases but you only handle 7. When doing long sequences of complicated if statements it is advisable to also have an else clause even if it theoretically should never be hit. Make that throw an error. I marked that with ??? """ @app.route("/movie_results") def movie_results(): name = request.args.get("movie.title") year = request.args.get("movie.year") imdbid = request.args.get("movie.imdbid") name_pattern = "%" + name + "%" if not year and not imdbid: search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE title ILIKE :movie_title') movie_specific = engine.execute(search_movie_statement, movie_title=name_pattern).fetchall() elif not name and not imdbid: search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE year = :year') movie_specific = engine.execute(search_movie_statement, year=year).fetchall() elif not name and not year: search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE "imdbID" = :imdbId') movie_specific = engine.execute(search_movie_statement, imdbId=imdbid).fetchall() elif not name: print(name) search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE "imdbID" = :imdbid AND year = :year') movie_specific = engine.execute(search_movie_statement, imdbid=imdbid, year=year).fetchall() elif not year: search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE "imdbID" = :imdbid and title ILIKE :movie_title') movie_specific = engine.execute(search_movie_statement, imdbid=imdbid, movie_title=name_pattern).fetchall() elif not imdbid: search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE year = :year and title ILIKE :movie_title') movie_specific = engine.execute(search_movie_statement, year=year, movie_title=name_pattern).fetchall() elif name and year and imdbid: search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE year = :year and title ILIKE :movie_title and imdbID = :imdbid') movie_specific = engine.execute(search_movie_statement, year=year, movie_title=name_pattern, imdbid=imdbid).fetchall() else: ??? # Return some kind of error if len(movie_specific) != 0 and movie_specific is not None: return render_template("movie_specific.html", movie_specific=movie_specific) if len(movie_specific) == 0: return render_template("error2.html", message="No such movie.") """ Another thing that can be done to clear the logic is to ensure that the if statement and the used variables matches, so use the fact that it has a value instead of it not having a value. So you could simplify your code even further I haven't used sqlalchemy for a while so I can't remember if you are allowed to send unused parameters to engine.execute. """ @app.route("/movie_results") def movie_results(): title = request.args.get("movie.title") year = request.args.get("movie.year") imdbid = request.args.get("movie.imdbid") title_pattern = "%{title}%".format(title) if title and year and imdbid: search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE year = :year and title ILIKE :movie_title and imdbID = :imdbid') elif title and year and not imdbid: search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE year = :year and title ILIKE :movie_title') elif title and not year and imdbid: search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE "imdbID" = :imdbid and title ILIKE :movie_title') elif not title and year and imdbid: search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE "imdbID" = :imdbid AND year = :year') elif title and not year and not imdbid: search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE title ILIKE :movie_title') elif not title and year and not imdbid: search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE year = :year') elif not title and not year and imdbid: search_movie_statement = sqlalchemy.text('SELECT * FROM movies WHERE "imdbID" = :imdbId') elif not title and not year and not imdbid: # Empty search, what to do here? ??? else: assert False, "Should never happen, a case was not handled correctly" movie_specific = engine.execute(search_movie_statement, year=year, movie_title=title_pattern, imdbid=imdbid).fetchall() if movie_specific: return render_template("movie_specific.html", movie_specific=movie_specific) else: return render_template("error2.html", message="No such movie.") """ I find this much cleaner to reason about """