How to run server in development mode with flask? - python

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)

Related

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"

Docker - Can't get user webcam: getUserMedia() no longer works on insecure origins

WHAT WORKS
I created a simple Web Application in Flask that takes care of operating a simple return render_template("index.html") when the root node is accessed by a Web Browser.
# app.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def show_index():
return render_template("index.html")
if __name__ == "__main__":
app.run(port=80)
The index.html is a simple page that uses tracking.js in order to get the user webcam and track his/her face in the live video stream.
Opening cmd and typing python app.py results in Running on http://127.0.0.1:80/
Accessing the above mentioned URL results in the correct display of the page, that asks me for permission to use the camera, opens it and correctly tracks my face in the live video feed. So it's all working fine till here.
WHAT DOES NOT WORKS
The problem I'm experiencing arises when I dockerize my application using Docker. docker-machine ip is 192.168.99.100
Opening cmd and typing: docker run -p 4000:80 my_face_track_app results in: Running on http://0.0.0.0:80/
Accessing 192.168.99.100:4000 results in the correct display of index.html but I am not asked anymore for permission on the camera and inspecting the JS console I read the following exception:
getUserMedia() no longer works on insecure origins
Here the full error log:
I know the error is telling me I'm not serving the page in HTTPS.
Has anyone else encountered this problem?
What would be the proper solution to the issue or a possible walkaround?
Any help will be highly appreciated, thank you a lot in advance
WHAT I HAVE TRIED TO DO IN ORDER TO SOLVE THE PROBLEM
Since an HTTPS serving of the page is needed in order for JS to execute the function getUserMedia() I tought about serving my Flask application with an SSL certificate by modifying app.py like this:
# app.py
from flask import Flask, render_template
import OpenSSL
app = Flask(__name__)
#app.route("/")
def show_index():
return render_template("index.html")
if __name__ == "__main__":
app.run(port=80, ssl_context="adhoc")
I then dockerized the app building a new image. Typing:
docker run -p 443:80 facetrackapphttps
Results in
Running on https://127.0.0.1:80
So yeah, here HTTPS is ON: the problem is that the port 80 of the HTTPS Flask App is mapped to the port 443 of the docker-machine ip 192.168.99.100.
Trying to access 192.168.99.100:443 does not work and nothing is shown.
Does anybody have an idea about how to do this?
If your application is bound to 127.0.0.1 inside the container, you're not going to be able to access it from your host. According to the flask docs, flask will bind to 127.0.0.1 by default.
You'll need to modify your service so that it binds to 0.0.0.0 inside the container:
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, ssl_context="adhoc")

Python script with flask server takes too long to exit on Windows

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)

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?

Categories