I have set up my first Flask project with PyCharm and this is my app.py file:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'TEST'
if __name__ == '__main__':
app.run(debug=True)
I want to run my project in debug mode so that I do not have to restart the server every time something changes. I provide the app.run function with a debug=True parameter, but this does not seem to change the debug flag. The application does start however and I do see "TEST" on the page, but this is with the debug flag set to False.
I also tried to directly change my env variable with os.environ["FLASK_DEBUG"] = "True", but this did not affect the flag also.
Any advice?
If you're using PyCharm, in Run/Debug config you can pass FLASK_DEBUG variable.
Try to set it to "1", not to "True".
Run your flask app in command line instead of PyCharm. python3 app.py
Related
I am learning to use flask and I want to run the server for an application in development mode, for this I do the following:
app = Flask(__name__)
if __name__=="__main__":
os.environ["FLASK_ENV"] = "development"
app.run(debug=True)
When I run I get the following in the terminal:
enter image description here
Environment:development does not appear to me as I understand it should appear. In fact, before doing this I don't get Environment:production either, I don't know what's going on. As a consequence, every time I want to see the changes that I am making in the code, I have to stop the server and run it again since the changes are not seen when refreshing the page.
If you're goal is for the application to restart each time code changes are saved, it shouldn't require any more than the following:
app = Flask(__name__)
if __name__=="__main__":
app.run(debug=True)
If you want to see what all your app config variables are set to by default, you can add the following line above app.run
print(app.config)
If you wanted to change your environment to production, change the 'ENV' variable after you initialize app
app = Flask(__name__)
app.config['ENV'] = 'production'
if __name__=="__main__":
app.run(debug=True)
I am building a simple flask app, jsonify() works fine on my localhost, it will return the information with new lines and the proper indent in a json format, however when running the exact same code on heroku, it omits the new lines and the indentation
This is how it looks on my localhost and this is on heroku
This is mentioned on the docs for jsonify()
This function's response will be pretty printed if the JSONIFY_PRETTYPRINT_REGULAR config parameter is set to True or the Flask app is running in debug mode
I have both set
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
app.run(debug=True)
I tried manually setting the content type to application/json, but that did not help, I even tried using json.dumps() and got the same result
return jsonify(data), 200, {'Content-Type': 'application/json; charset=utf-8'}
Any input on what could be causing heroku not pretty printing?
Edit:
from flask import request, jsonify, Flask
app = Flask(__name__)
#app.route('/test', methods = ['GET'])
def test():
test_dict = {"Key1": "Value1", "Key2": ["Value2","Value2","Value2",]}
print(jsonify(test_dict).headers)
return jsonify(test_dict)
if __name__ == '__main__':
app.run(debug=True)
This simple flask app would pretty print on my localhost like the photos linked above, however on heroku it wont. Looks like it is returning plain text. It can be seen here https://jojoapi.herokuapp.com/test.
I am using gunicorn, not sure if that has any impacts on the output
Edit 2
So, I set manually debug to True as suggested in the comments app.config["DEBUG"] = True and it works properly on heroku now
Some servers (not only Heroku) may not run directly your script and not execute app(debug=True) but they may import app to own code and run it with own arguments app(...own args...) - and this can makes problem.
You can set debug mode in code in different method.
app.config["DEBUG"] = True
Eventually you can try to set environment variable in Linux
export FLASK_DEBUG=1
or
export FLASK_ENV=development
See doc: Debug Mode
Flask doc: Standalone WSGI Containers - it shows servers which import app (as myproject:app) and they may runs with own arguments.
I'm using flask app factory pattern like and have this helloworld.py file
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return 'This is the home page'
if __name__=="__name__":
app.run(debug=True)
Then I run the app in Terminal :
python helloworld.py
(venv) C:\Users\Jayalakshmi.S1\myproject>python helloworld.py
(venv) C:\Users\Jayalakshmi.S1\myproject>
But when I go to http://localhost:5000 it doesn't work. It says:
Can’t reach this page
Make sure the web address http://127.0.0.1:5000 is correct
What could be wrong?
The problem is that you wrote if __name__=="__name__": instead of if __name__=="__main__":.
Since that will never be true, your app.run never happens. That's why when you run the script, it just returns immediately, instead of printing out something like * Running on http://127.0.0.1:5000/ and then waiting.
You also almost always want to run Flask this way:
set FLASK_APP=helloworld.py
flask run
… instead of:
python helloworld.py
Your if condition is wrong. You should mention the main module which you're running...
if __name__=="__main__":
app.run(debug=True)
I'm new to Python.
As a part of a project I'm trying to deploy a Flask server locally, through the Windows command line.
My Python version is 3.6.0.
The code:
from flask import Flask
app = Flask(__name__)
#app.route('/') def index():
return '<h1>Hello World!</h1>'
if __name__ == "__main__":
app.run()
The problem:
It's about killing the script as it runs. Launching this script with python deploy.py and hitting CTRL+C shuts it off.
BUT - if I hit access that '/' route via the browser once or more, and a moment later try to kill the script in the same manner, then it would take about 10 seconds of nothing until it responds and is finally killed.
Why is this happening? How can I shut the server off immediately each time for continuous and quick development?
Thanks!!
Well if your goal is continuous and quick development, then you can change flask's configuration.
Best solution for your problem would be setting the DEBUG setting to True. If DEBUG is set to True, then flask will automatically reload the server on code changes.
There are a few ways to do this but the easiest one(because you said you are a beginner) is to pass the debug argument to app.run()
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return '<h1>Hello World!</h1>'
if __name__ == "__main__":
app.run(debug=True)
I've been working on a new dev platform using nginx/gunicorn and Flask for my application.
Ops-wise, everything works fine - the issue I'm having is with debugging the Flask layer. When there's an error in my code, I just get a straight 500 error returned to the browser and nothing shows up on the console or in my logs.
I've tried many different configs/options.. I guess I must be missing something obvious.
My gunicorn.conf:
import os
bind = '127.0.0.1:8002'
workers = 3
backlog = 2048
worker_class = "sync"
debug = True
proc_name = 'gunicorn.proc'
pidfile = '/tmp/gunicorn.pid'
logfile = '/var/log/gunicorn/debug.log'
loglevel = 'debug'
An example of some Flask code that borks- testserver.py:
from flask import Flask
from flask import render_template_string
from werkzeug.contrib.fixers import ProxyFix
app = Flask(__name__)
#app.route('/')
def index():
n = 1/0
return "DIV/0 worked!"
And finally, the command to run the flask app in gunicorn:
gunicorn -c gunicorn.conf.py testserver:app
Thanks y'all
The accepted solution doesn't work for me.
Gunicorn is a pre-forking environment and apparently the Flask debugger doesn't work in a forking environment.
Attention
Even though the interactive debugger does not work in
forking environments (which makes it nearly impossible to use on
production servers) [...]
Even if you set app.debug = True, you will still only get an empty page with the message Internal Server Error if you run with gunicorn testserver:app. The best you can do with gunicorn is to run it with gunicorn --debug testserver:app. That gives you the trace in addition to the Internal Server Error message. However, this is just the same text trace that you see in the terminal and not the Flask debugger.
Adding the if __name__ ... section to the testserver.py and running python testserver.py to start the server in development gets you the Flask debugger. In other words, don't use gunicorn in development if you want the Flask debugger.
app = Flask(__name__)
app.config['DEBUG'] = True
if __name__ == '__main__':
app.run()
## Tip for Heroku users:
Personally I still like to use `foreman start`, instead of `python testserver.py` since [it sets up all the env variables for me](https://devcenter.heroku.com/articles/config-vars#using-foreman). To get this to work:
Contents of Procfile
web: bin/web
Contents of bin/web, file is relative to project root
#!/bin/sh
if [ "$FLASK_ENV" == "development" ]; then
python app.py
else
gunicorn app:app -w 3
fi
In development, create a .env file relative to project root with the following contents (docs here)
FLASK_ENV=development
DEBUG=True
Also, don't forget to change the app.config['DEBUG']... line in testserver.py to something that won't run Flask in debug mode in production.
app.config['DEBUG'] = os.environ.get('DEBUG', False)
The Flask config is entirely separate from gunicorn's. Following the Flask documentation on config files, a good solution would be change my source to this:
app = Flask(__name__)
app.config.from_pyfile('config.py')
And in config.py:
DEBUG = True
For Heroku users, there is a simpler solution than creating a bin/web script like suggested by Nick.
Instead of foreman start, just use foreman run python app.py if you want to debug your application in development.
I had similiar problem when running flask under gunicorn I didn't see stacktraces in browser (had to look at logs every time). Setting DEBUG, FLASK_DEBUG, or anything mentioned on this page didn't work. Finally I did this:
app = Flask(__name__)
app.config.from_object(settings_map[environment])
if environment == 'development':
from werkzeug.debug import DebuggedApplication
app_runtime = DebuggedApplication(app, evalex=False)
else:
app_runtime = app
Note evalex is disabled because interactive debbugging won't work with forking (gunicorn).
I used this:
gunicorn "swagger_server.__main__:app" -w 4 -b 0.0.0.0:8080
You cannot really run it with gunicorn and for example use the flask reload option upon code changes.
I've used following snippets in my api launchpoint:
app = Flask(__name__)
try:
if os.environ["yourapp_environment"] == "local":
run_as_local = True
# some other local configs e.g. paths
app.logger.info('Running server in local development mode!')
except KeyError as err:
if "yourapp_environment" in err.args:
run_as_local = False
# some other production configs e.g. paths
app.logger.info('No "yourapp_environment env" given so app running server in production mode!')
else:
raise
...
...
...
if __name__ == '__main__':
if run_as_local:
app.run(host='127.0.0.1', port='8058', debug=True)
else:
app.run(host='0.0.0.0')
For above solution you need to give export yourapp_environment = "local" in the console.
now I can run my local as python api.py and prod gunicorn --bind 0.0.0.0:8058 api:app
The else statement app.run() is not actually needed, but I keep it for reminding me about host, port etc.
Try setting the debug flag on the run command like so
gunicorn -c gunicorn.conf.py --debug testserver:app
and keep the DEBUG = True in your Flask application. There must be a reason why your debug option is not being applied from the config file but for now the above note should get you going.