Flask app not running on localhost, no error - python

Similar code to this was working fine, then suddenly not and I have no idea why. Hoping somebody can help. I have the following:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def home():
return "Hi"
if __name__ == "__main__":
app.run(debug=True)
When I run that, the output is the following:
* Serving Flask app "app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
There is no error, but also no "Running on http://localhost:5000/" and nothing loads at that URL ("This site can't be reached") etc.
I have tried specifying the host many ways and many other things. Still get the same. Previously it was working fine, said "Running on http://localhost:5000/," was loading fine in my browser, etc.
What am I missing here?

You can explicitly set the host and the port on your script:
# ...
if __name__ == "__main__":
app.run(host='localhost', port=5000, debug=True) # or setting host to '0.0.0.0'

Related

FLASK: curl: (7) Failed to connect to 127.0.0.1 port 5500: Connection refused

I am trying to transition from making Rshiny apps to flask-react apps. Its definitely a steep learning curve so far!
I am sort of following a few tutorials e.g (https://dev.to/arnu515/build-a-fullstack-twitter-clone-using-flask-and-react-1j72) to try and get some basic functionality down .
However some reason curl can't seem to interact with my app. I've tried putting the urls with and without quotes but get the same response. Also I tried the default 5000 port as well. I am running the app in windows:
C:\Users\Marc\flaskTest\backend>curl "http://127.0.0.1:5500"
curl: (7) Failed to connect to 127.0.0.1 port 5500: Connection refused
app.py code
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
#app.route('/')
def index():
return "hello"
#app.route('/message', methods=["GET"])
def message():
message ="my message"
return jsonify({"message": message})
if __name__ == "__main__":
app.run(debug=True, port=5500)
You used jsonify in the view function but haven't imported it before, so there would be error when Flask app runs.
Actually you can just write code like return {"message": message}, it would do the same thing with jsonify does if you are using latest version of flask.
Try:
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True, port=5500)
Also in windows cmd type ipconfig IPV4 address. Suppose your IPV4 address is 192.168.X.X, access the website as http://192.168.X.X:5500.
Read what it does: Externally Visible Server

Not Found page when waitress start

I get this error when I access the default page after starting the flask server using the waitress.
The code is:
from app import app
from waitress import serves
if __name__ == '__main__':
serves (app, host = "0.0.0.0", port = 8080)
I access the page http://localhost:8080 in the browser
erro:
Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
You need a url handler:
#app.route('/')
def index():
return "hello"

Serving Flask app with waitress on windows using SSL public/private key

How do I run my Flask app which uses SSL keys using waitress. The SSL context is specified in my Flask's run() as in
app.run(ssl_context=('cert.pem', 'key.pem'))
But app.run() is not used when using waitress as in the code below. So, where do I specify the keys? Thanks for the help.
from flask import Flask, request
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == '__main__':
# app.run(ssl_context=('../cert.pem', '../key.pem'))
from waitress import serve
serve(app, host="0.0.0.0", port=5000)
At the current version (1.4.3), Waitress does not natively support TLS.
See TLS support in https://github.com/Pylons/waitress/blob/36240c88b1c292d293de25fecaae1f1d0ad9cc22/docs/reverse-proxy.rst
You either need a reverse proxy in front to handle the tls/ssl part, or use another WSGI server (CherryPy, Tornado...).

Docker and WSGI with a Python Pyramid app?

I am looking at two articles on how to Dockerize a Pyramid app. I am not that familiar with Python, but I am fairly certain with a Pyramid app you need to use WSGI.
This article uses WSGI:
https://medium.com/#greut/minimal-python-deployment-on-docker-with-uwsgi-bc5aa89b3d35
This one just runs the python executable directly:
https://runnable.com/docker/python/dockerize-your-pyramid-application
It seems unlikely to me that you can run python directly and not incorporate WSGI, can anyone provide an explanation for why the runnable.com article's docker solution would work?
Per the scripts in the second link:
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
~snip~
if __name__ == '__main__':
config = Configurator()
config.add_route('hello', '/')
config.add_view(hello_world, route_name='hello')
app = config.make_wsgi_app() # The wsgi server is configured here
server = make_server('0.0.0.0', 6543, app) # and here
This contains an explanation of why the wsgi server is built in the if __name__=="__main__" block

nginx + uwsgi + flask - disabling custom error pages

Is it possible to disable nginx's custom error pages - if I may call them that - to display my framework's exception pages?
I can't really see my werkzeug debugger tool rendered in html...
UPDATE
OK, I got to make a very very simple flask application to work and I'll post the bits:
/home/my_user/.virtualenvs/nginx-test/etc/nginx.conf
worker_processes 1;
events { worker_connections 1024; }
http {
server {
listen 5000;
server_name localhost;
access_log /home/my_user/.virtualenvs/nginx-test/lib/nginx/access.log;
error_log /home/my_user/.virtualenvs/nginx-test/lib/nginx/error.log;
location / {
include uwsgi_params;
uwsgi_pass unix:/tmp/uwsgi.sock;
}
}
}
/home/my_user/dev/nginx_test/___init___.py
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
raise Exception()
if __name__ == '__main__':
app.run('0.0.0.0', debug=True)
PYTHONPATH environment variable:
$ echo $PYTHONPATH
/home/my_user/dev/
How I run uwsgi:
$ uwsgi -s /tmp/uwsgi.sock --module nginx_test --callable app
How I run nginx:
$ nginx -c ~/.virtualenvs/nginx-test/etc/nginx.conf -p ~/.virtualenvs/nginx-test/lib/nginx/
If I hit the root page:
If I run nginx manually like:
python /home/my_user/dev/nginx_test/___init___.py
I will see instead, and what I want to see:
Of course I made sure it would work when I didn't raise the exception, but returned 'Hello World' for example on my index() function.
This is referred to custom error pages in .NET. I want to disable this and let nginx/uwsgi pass the html generated by the debugger directly to the browser instead of the internal server error thing.
UPDATE 2
Now if I change my flask app to enable debugging mode by:
/home/my_user/dev/nginx_test/___init___.py
from flask import Flask
app = Flask(__name__)
app.config.update(DEBUG=True)
#app.route('/')
def index():
raise Exception()
if __name__ == '__main__':
app.run('0.0.0.0', debug=True)
Then I get 502 error.
But if I instead of raise Exception:
/home/my_user/dev/nginx_test/___init___.py
from flask import Flask
app = Flask(__name__)
app.config.update(DEBUG=True)
#app.route('/')
def index():
return 'Hello World'
if __name__ == '__main__':
app.run('0.0.0.0', debug=True)
I get 'Hello World' on my browser when I hit the page (http://localhost:5000).
This "Internal Server Error" page is not from nginx but from Flask. It does so when debug mode is off.
uwsgi is importing your code as a module, not running at as a script. __name__ == '__main__' is False and the if statement is not executed. Try setting debug mode outside of the if:
app = Flask(__name__)
app.debug = True
However, it is strongly recommended to never leave the debug mode on a server on the public internet, since the user can make the server run any code. This is a serious security issue.
Use Flask#errorhandler to register your own error handlers in flask. For example to replace the 404 you would do something like:
app = Flask()
#app.errorhandler(404)
def handel_404(error):
return render_template('404.html')
Simon Sapin has really given you the correct answer. You need to enable debug in Flask. Nginx does not return any custom error pages unless you explictly configure it to do so.
If you use the following code you will see your debug messages from flask, proxied via Nginx.
from flask import Flask
app = Flask(__name__)
app.debug = True
#app.route('/')
def index():
raise Exception()
As per your update 2. You are seeing a 502 (bad gateway) because Flask is simply not returning any response at all, or a response that Nginx does not understand. A 502 is not a problem with Nginx. It means that whatever Nginx is trying to talk (your flask app in this case) is not working properly at all.
However, in many ways you shouldn't be doing this. Debugging mode should only be enabled when you are running flask on your local dev machine. Which is the whole point of the if __name__ == "__main__": line anyway.

Categories

Resources