According to the Flask documentation,
The flask script is nice to start a local development server, but you
would have to restart it manually after each change to your code. That
is not very nice and Flask can do better. If you enable debug support
the server will reload itself on code changes, and it will also
provide you with a helpful debugger if things go wrong.
To enable all development features (including debug mode) you can
export the FLASK_ENV environment variable and set it to development
before running the server:
$ export FLASK_ENV=development
$ flask run
However, in my very simple example, code changes still don't take effect until I restart the server. I've set up the particular script I want to run with export FLASK_APP=hello.py and the script is as follows:
from flask import Flask, url_for, request, render_template
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!!"
While the Flask development server is running, I change the return value by adding or removing an exclamation mark and saving the file. Then I refresh the page on http://127.0.0.1:5000/ in Chrome, but the number of exclamation points is unchanged. Once I quit Flask in the terminal using Ctrl-C and restart it and then refresh the page again, I get the proper number of exclamation points.
This is on a Mac, Python 3.6.0 (Anaconda), Flask 0.12.
Am I misunderstanding how the development server can help me, or is there anything else you think I should check? I'm quite new to Flask.
Try
FLASK_APP=app.py FLASK_DEBUG=1 TEMPLATES_AUTO_RELOAD=1 flask run
FLASK_DEBUG will get you the behavior you're looking for now; TEMPLATE_AUTO_RELOAD will get you the behavior you'll need as soon as you starting using templates.
$env:FLASK_ENV = "development"
flask run
That's worked for me on my Win10 laptop running VS code
Looking at app.config contents I discovered variable ENV='production'.
Set ENV='development' in config file and it worked. FLASK_ENV variable does not even exist.
Related
I'm maintaining a web application built with Flask with python 2.7 coupled with Jinja and angularjs .In a Linux environment, everything is working fine.
On windows when I run the application on cmd or git bash (python app.py), I only see that the server is running and in which port (and everything else is working fine in the browser), but the problem is that the logs in console aren't shown like in a Linux terminal.
For example, I can't see the requests like: POST /login..or an exceptional mission or even a simple print "test" Dosen"to show (still everything is working in a browser).
Even worst, when I terminate the server with "ctr+c" all the previous messages and logs are printed in the terminal, all together in one single dump!
--- Update ---
when i use the command python -u app.py
it's even worst , the application dose'nt run in the browser anymore , no log in console and when i termiante it shows this :
screenshot of terminal
I would suggest that you creat a proper uWSGI gateway.
An example setup could be:
Linux 18.04 ->
Nginx / Apache reverse web proxy mode ->
Gunicorn (which has a debugger you can attach, this will output to the regular log files like other applications. Systemd logs I think) ->
Flask web framework.
Hope this helps.
I wrote a simple Flask application on a VPS server in Apache
from flask import Flask, render_template, request
import sys
app = Flask(__name__)
#app.route("/")
def hello():
return "123"
if __name__ == "__main__":
app.run()
When I change the string return "123" to return "123456" and save it, it doesn't change when refreshing the site with Ctrl+F5.
It changes only when I restart the Apache server.
How can I change the file without a restart?
You can try reloading. Even that will impact the incoming traffic though.If there are more than one servers you can do a rolling reload or restart.
If not you can do a graceful restart of apache where traffic wont be impacted, using
apachectl -k graceful
You can do without a restart or reload as well.
The reason why you are getting older code is,
you might have a compiled python code(bytecode) file which will be served for every new request, if your script is myscript.py, check if there is a myscript.pyc, which is a bytecode containing the older version of the script. You need to remove that.
If you are using wsgi module for serving python in apache, you need to look at the following link on how to reload source code.
https://code.google.com/archive/p/modwsgi/wikis/ReloadingSourceCode.wiki
I'm using Pycharm 4, with flask 0.10.1, python 3.4
It seems that when running a flask application from inside pycharm, if I run it with:
app.run(debug=True)
My breakpoints are ignored. After some googling, I've found that in order to make PyCharm stop on breakpoints, I should run flask with:
app.run(debug=True, use_reloader=False)
Now PyCharm correctly stops on breakpoints, but I miss the autoreloading feature.
Is there any way to make both work together?
Using python 2.7 both things work
I reported this to PyCharm: https://youtrack.jetbrains.com/issue/PY-13976
I'm going to start with the short answer: No, what you want cannot be done with any releases of PyCharm up to 4.0.1.
The problem is that when you use the reloader the Flask application runs in a child process, so the PyCharm debugger is attached to the master process and has no control over the child.
The best way to solve this problem, in my opinion, is to ask Jetbrains to build a "restart on change" feature in their IDE. Then you don't need to use Werkzeug's reloader at all and you get the same functionality direct from PyCharm.
Until Jetbrains decides to implement this, I can share my workaround, which is not terribly bad.
In the "Edit Configurations", set the configuration you are going to use to "Single Instance only" (check box in the top right of the dialog box)
Make sure the configuration is the active one.
Configure your Flask app to not use the Werkzeug reloader.
Press Ctrl-D to start debugging (on Mac, others may have a different shortcut)
Breakpoints should work just fine because the reloader isn't active.
Make any code changes you need.
When you are ready to restart, hit Ctrl-D again. The first time you do it you will get a confirmation prompt, something like "stop and restart?". Say yes, and check the "do not show again" checkbox.
Now you can hit Ctrl-D to quickly restart the debugger whenever you need to.
I agree it is not perfect, but once the Ctrl-D gets into your muscle memory you will not even think about it.
Good luck!
I found that in PyCharm 2018.1.2 there is FLASK_DEBUG checbox in run configuration:
With this after making some changes, saving file triggers reload action.
In my setup, I'm debugging the flask app by running a main.py file which sets some configuration and calls app.run(). My python interpreter is set up in a Docker container.
My issue was that I needed to check Run with Python console.
The problem is because with use_reloader=True the werkzeug application is started in a seperate (child) thread of main application and PyCharm fails to correctly handle breakpoints because they are lost when the thread starts.
You can try to follow this thread: http://forum.jetbrains.com/thread/PyCharm-776 but it seams there was not too much progress on that.
I'd suggest using something Python-ish like pdb, i.e.:
#app.route('/<string:page>')
def main(page):
import pdb; pdb.set_trace() # This line actually stops application execution
# and starts Python debug shell in the console
# where you can examine current scope and continue
# normal code execution at any time.
# You can inject *any* code here.
# For example, if you type `print page` during pause,
# it will output content of "page" variable.
return render_template('index.html')
Try configuring this python running configuration in "Edit Configurations". After that, run in debug mode.
You need to unlock the console.
you start the app in debug mode
then you make something that causes an error.
at the end of the error message from flask is this
Here you enter the PIN flask prints in the console at the start
copy paste this pin into the console and click confirm PIN
now the breakpoints will work
from pycharm 2017 using python 2.7 (in my case with virtual env, but I suppose not necessary) I do:
run...
leave scripts and scripts parameters blank
I put in interpreter options: -m flask run
set the env variables FLASK_APP
than run attach to local process, and finally choose the running process
my use case is to connect from postman to flask rest services endpoints and interrupt on my breakpoints
I need to test two Flask Apps in my browser at the same time. By standard, Flask runs the app in the localhost:5000. So, a good alternative would be changing the address of one of the apps. Is that possible? If so, how to do it?
You can set the addres and port for your app
app.run(host='0.0.0.0',port=12345)
As long as the port numbers don't clash you can run seperate instances of flask apps on the same computer
Since version 0.11, flask run is the recommended method to start a development server. In your case, open a new terminal, then run the same app on different port:
$ export FLASK_APP=my_app2 # use "set FLASK_APP=my_app2" on Windows
$ flask run --port 5001
To debug a bug I'm seeing on Heroku but not on my local machine, I'm trying to do step-through debugging.
The typical import pdb; pdb.set_trace() approach doesn't work with Heroku since you don't have access to a console connected to your app, but apparently you can use rpdb, a "remote" version of pdb.
So I've installed rpdb, added import rpdb; rpdb.set_trace() at the appropriate spot. When I make a request that hits the rpdb line, the app hangs as expected and I see the following in my heroku log:
pdb is running on 3d0c9fdd-c18a-4cc2-8466-da6671a72cbc:4444
Ok, so how to connect to the pdb that is running? I've tried heroku run nc 3d0c9fdd-c18a-4cc2-8466-da6671a72cbc 4444 to try to connect to the named host from within heroku's system, but that just immediately exits with status 1 and no error message.
So my specific question is: how do I now connect to this remote pdb?
The general related question is: is this even the right way for this sort of interactive debugging of an app running on Heroku? Is there a better way?
NOTE RE CELERY: Note, I've now also tried a similar approach with Celery, to no avail. The default host celery's rdb (remote pdb wrapper) uses is localhost, which you can't get to when it's Heroku. I've tried using the CELERY_RDB_HOST environment variable to the domain of the website that is being hosted on Heroku, but that gives a "Cannot assign requested address" error. So it's the same basic issue -- how to connect to the remote pdb instance that's running on Heroku?
In answer to your second question, I do it differently depending on the type of error (browser-side, backend, or view). For backend and view testing (unittests), will something like this work for you?
$ heroku run --app=your-app "python manage.py shell --settings=settings.production"
Then debug-away within ipython:
>>> %run -d script_to_run_unittests.py
Even if you aren't running a django app you could just run the debugger as a command line option to ipython so that any python errors will drop you to the debugger:
$ heroku run --app=your-app "ipython --pdb"
Front-end testing is a whole different ballgame where you should look into tools like selenium. I think there's also a "salad" test suite module that makes front end tests easier to write. Writing a test that breaks is the first step in debugging (or so I'm told ;).
If the bug looks simple, you can always do the old "print and run" with something like
import logging
logger = logging.getLogger(__file__)
logger.warn('here be bugs')`
and review your log files with getsentry.com or an equivalent monitoring tool or just:
heroku logs --tail