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"
Related
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'
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
My application is hosted in Azure VM. I have created a static IP and a Public IP for the VM. Here are my steps.
Created the VM
Open the port 5000 using the inbound port rule.
Created a port forwarding rule in my router that has original port
as 5000, the static IP of VM and the to port as 5000
Added my code and ran the program
Works with static IP
When I try to access it outside, it doesn't work. I have been on this for the whole day and still unable to figure out anything. Can you please guide here on how to access it outside of VM?
Below is my code:
from flask import Flask, render_template, redirect, url_for
from flask import request
app = Flask(__name__)
#app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != 'admin' or request.form['password'] != 'admin':
error = "Invalid Credentials. Please try again."
else:
return render_template('link.html')
return render_template('login.html',error = error)
if __name__ == '__main__':
app.run(host = 'static IP')
I have a basic flask server I am using for Python development with a Google Chat Bot. I would like to limit the range of IP's that can access the server to any within a certain range. For the purposes of this, say 123.0.0.1 to 123.255.255.255.
I know how to easily do this for a single IP, from similar issues seen online.
from flask import abort, request
#app.before_request
def limit_remote_addr():
if request.remote_addr != '123.0.0.1':
abort(403) # Forbidden
But I don't want to do this for every IP, or have to make a list. Is that possible? Or am I better off configuring my firewall to remove this step?
As #Klaus D. mentioned you can check if the remote address starts with a portion of the address.
You can check if the remote address is listed in a specific list of IP addresses in #before_request decorator.
Here I am showing an example of white listing IP addresses in Python.
Used local network(connected via WiFi) to test it.
Local IP address for Flask server: 192.168.0.107
app.py:
from flask import abort, Flask, render_template, request
ALLOWED_IPS = ['192.168.1.', '127.0.0.1']
app = Flask(__name__)
#app.errorhandler(403)
def permission_error(e):
return render_template('403.html', error_code=403), 403
#app.before_request
def limit_remote_addr():
client_ip = str(request.remote_addr)
valid = False
for ip in ALLOWED_IPS:
if client_ip.startswith(ip) or client_ip == ip:
valid = True
break
if not valid:
abort(403)
#app.route('/', methods = ['GET'])
def home():
return "Your IP: {}".format(request.remote_addr)
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
403.html:
<h3>Your IP address is not white listed</h3>
Output:
Accessing the app from a IP which is not in ALLOWED_IPS list:
Accessing the app from a IP which is in ALLOWED_IPS list:
After updating the ALLOWED_IPS list to ALLOWED_IPS = ['192.168.0.', '127.0.0.1'], I can access the Flask app from 192.168.0.107:
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.