flask, Jsonify not pretty prints on Heroku - python

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.

Related

How to run server in development mode with flask?

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)

Python Flask cannot set debug mode to true

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

Python Flask app route is not working well

I tried to find a solution for my problem in other questions but I couldn't.
I downloaded the python flask and made my first flask app and it ran fine.
Here is the code:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "Hello, world!"
When I ran my second file where I had added an app.route ("/ david") and followed the same procedure again, refreshed it and nothing changed.
That is to say, I was going to / david and I get an URL error
Here is my second file
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "Hello, world!"
#app.route("/david")
def david():
return "Hello, David!"
I tried the same with other files which have some added routes and the result is the same as the first file
Thanks for your answers, I hope to solve my problem.
You did not run the app. What you did is just create a structure for flask, but did not start the server.
Just add:
app.run()
To the bottom of the file and it will work. It will with start the flask server at http://localhost:5000.
By default, flask runs on port 5000.
It can be changed by:
app.run(host="0.0.0.0", port=xxxx)
0.0.0.0 means it accepts request from anywhere on the port specified.
Make sure you have all the permissions and nothing else is running if you want it to run on port 80.
Hope this helps. Good luck.
I had the same issue. Try first by restarting your IDE; this worked for me. If that doesn't work, try clearing your ports for Windows:
Open Task manager
Click on the “Processe” tab
Enable the "PID" column: View -> Select Columns -> Check the box for PID
Find the PID (in your case, 5000 - flask default port) and click “END PROCESS"

How to use app.debug in Flask app deployed on Azure?

I've created a simple Flask app using Azure, which I git cloned and modified to enable debug mode - my __init.py__ now looks like:
from flask import Flask
app = Flask(__name__)
app.debug = True
import FlaskWebProject1.views
And then made it throw a server error, in the project's views.py:
def bad_method():
return 1/0
#app.route('/')
def home():
"""Renders the home page."""
a = bad_method()
return render_template(...) # Never gets here
When I run this locally using the development server (runserver.py), I get a useful stacktrace in the console and also in the browser - this is what I want.
When I push the code up to Azure and visit the deployed site I get a plain The page cannot be displayed because an internal server error has occurred. 500 Error, with no stacktrace shown in the browser.
Is there a way that I can enable the same debug mode while developing that I have locally when my code is deployed in Azure? The stack trace in a log would be OK, but in the browser would be far better.
EDIT: I've modified my views to pass through app.debug to a template, and it shows as True. So this must be Azure somehow hiding the stack trace?

Getting plain text instead of Python script execution

I'm trying to execute this little request with jquery on a page load:
$.ajax({
type: "GET",
url: "/static/query.py",
cache: false,
success: function (data) {
$(body).text(data);
}
});
On a server running nginx, python, in a virtualenv, working with Flask framework and the return is the query.py sourcecode, not the data retrieved from the DB.
query.py is marked as executable and the script has the shebang:
#!/home/gabriel/project/bin
which points to the bin in my virtualenv. I think got the basis covered but yet, the problem persists.
Tips?
More info:
Flask script:
from flask import Flask, render_template
application = Flask(__name__)
#application.route('/')
def init():
return render_template('index.html')
if __name__ == "__main__":
application.run(host='0.0.0.0', debug=True)
uwsgi.py to load the Flask script:
from myapp import application
if __name__ == "__main__":
application.run()
The query.py:
from db import * //Database model, SQLAlchemy.
def something():
data = Kingdom.query.all()
return data
something()
You should be running the actual code that's in query.py inside flask. Do something like:
#application.route("/query"):
def get_data():
.. whatever code you need; currently in query.py, you would probably use sqlalchemy/ flask-sqlalchemy
data = your data (dictionary? list?)
return jsonify(data=data) # flask will turn your data into a proper JSON string to send back as a response to the ajax call.
Don't forget to import jsonify from flask, consult docs here.
Also rename "/static/query.py" to "/query" in example above, or anything else you see fit. You can also send flask parameters via the AJAX call to process in your query; e.g., filtering parameters. Focus the question for further guidance.

Categories