Flask Failed to connect, address not available - python

I'm new to python and flask, I'm following this tutorial to create an application with flask and angular.
To make things quicker, because I don't need a database at the moment, I skipped the steps of creating the model and the connection.
I ran this command touch src/__init__.py and in my myapp/backend/src/main.py I have this:
from flask import Flask, jsonify, request
app = Flask(__name__)
#app.route('/test')
def get_exams():
print('ou')
if __name__ == '__main__':
app.run(host='0.0.0.0',port=5000)
Also I created the myapp/backend/bootstrap.sh with this:
#!/bin/bash
export FLASK_APP=./src/main.py
source $(pipenv --venv)/bin/activate
flask run -h 0.0.0.0
But if I try to run curl http://0.0.0.0:5000/test I got this error curl: (7) Failed to connect to 0.0.0.0 port 5000: Address not available
Aside from the database steps, I made everything according to the tutorial.

You need named the route to the method exams /test.
So you need to call /test not /exams
curl http://0.0.0.0:5000/test
The route defines the URI/URL and calls the method associated with it. The names are totally independent and completely up to you. So you are very fine to also name the route /exams as well.

Related

How can i have connection to 0.0.0.0 port 5000?

I'm Creating an endpoint that retrieves the number of each objects by type. when i execute the code with:
curl -X GET http://0.0.0.0:5000/api/v1/stats
it says:
curl: (7) Failed to connect to 0.0.0.0 port 5000: Connection refused
i've been trying to see if I have a config file, checked my listed ports, Google on how to change/activate the port, & still haven't found something.
This is my full code:
''' module that makes this an app '''
from flask import Flask, abort, jsonify
from models import storage
from api.v1.views import app_views
from os import getenv
app = Flask(__name__)
app.register_blueprint(app_views)
#app.teardown_appcontext
def close(self):
''' method that close the yes '''
storage.close()
#app.errorhandler(404)
def invalid_route(e):
return jsonify({"error": "Not found"}), 404
if __name__ == '__main__':
app.run(host=getenv("HBNB_API_HOST", "0.0.0.0"),
port=int(getenv("HBNB_API_PORT", "5000")), threaded=True)```
Your code is completely right, you are not sending the request to the right host.
Your flask server is binded to 0.0.0.0, which means that your server will be bounded to the default address (either localhost or your actual ip address)
This should be fine:
curl -X GET http://localhost:5000/api/v1/stats
I used an executable command like this:
HBNB_MYSQL_USER=hbnb_dev HBNB_MYSQL_PWD=hbnb_dev_pwd HBNB_MYSQL_HOST=localhost HBNB_MYSQL_DB=hbnb_dev_db HBNB_TYPE_STORAGE=db HBNB_API_HOST=0.0.0.0 HBNB_API_PORT=5000 sudo python3 -m api.v1.app
but I forgot to add sudo before python3. Then you should open a new terminal and execute the curl command. THANKS

flask server with ssl_context freezes if it receives http request

I'm trying to create a simple flask server that redirects any http requests to https. I've created a certificate and key file and registered a before_request hook to see if the request is secure and redirect appropriately, following advise this SO answer.
The flask server responds to https requests as expected. However, when I send an http request, the before_request hook never gets called and ther server hangs forever. If I send the http request from the browser, I see an "ERR_EMPTY_RESPONSE". The server doesn't even respond to https requests afterwards. No logs are printed either.
Running the app with gunicorn didn't help either. The only difference was that gunicorn is able to detect that the worker is frozen and eventually kills and replaces it. I've also tried using flask-talisman, with the same results.
Below is the code I'm running
### server.py
from flask import Flask, request, redirect
def verify_https():
if not request.is_secure:
url = request.url.replace("http://", "https://", 1)
return redirect(url, 301)
def create_flask_app():
app = Flask(__name__)
app.before_request(verify_https)
app.add_url_rule('/', 'root', lambda: "Hello World")
return app
if __name__ == '__main__':
app = create_flask_app()
app.run(
host="0.0.0.0",
port=5000,
ssl_context=('server.crt', 'server.key')
)
Running it with either python3.8 server.py or gunicorn --keyfile 'server.key' --certfile 'server.crt' --bind '0.0.0.0:5000' 'server:create_flask_app()' and opening a browser window to localhost:5000 causes the server to hang.
Talking about freezes, its not. Flask and gunicorn can serve only one variant of connection. So it's not freezing because your browser canceled the request and is idling.
I think it is better to use a faster web server, for example, Nginx, if you want to change HTTP to HTTPS. I would recommend it to you.
But it's possible to trigger your verify_https function if you run multiple instances of gunicorn at the same time.
I took your example, generated a certificate, and then run this script in my console (it contains a background job and can be runned in twoo separate ter)
gunicorn --bind '0.0.0.0:80' 'server:create_flask_app()' & gunicorn --certfile server.crt --keyfile server.key --bind '0.0.0.0:443' 'server:create_flask_app()'
now chrome goes to the secure page as expected.
Typically servers don't listen for both http and https on the same port. I have a similar requirement for my personal portfolio, but I use nginx to forward http requests (port 80) to https (port 443) and then the https server passes it off to my uwsgi backend, which listens on port 3031. That's probably more complex than you need, but a possible solution. If you go that route I would recommend letsencrypt for your certificate needs. It will set up the certificates AND the nginx.conf for you.
If you don't want to go the full nginx/apache route I think your easiest solution is the one suggested here on that same thread that you linked.

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

flask with uwsgi nginx gateway timeout

I have set up a flask application to use uwsgi and nginx
I used the tutorials on the internet but I have the following issue
I have the following functions on the controller.py file
api_module = Blueprint('cassandra_api', __name__, url_prefix="/api")
#api_module.route('/', methods=['GET', 'POST'])
def home():
return "c"
the above works great when trying
myip/api/
but the following doesn't work at all
#api_module.route("/fault_prone_snippets/", methods=['GET'])
def get_fault_prone_snippets():
#code to connect with cassandra db and retrieve get parameters
When I visit
myip/api/faut_prone_snippets/
with or without get parameters, no code is executed, I don't see an error message and after the minute is over I get a gateway timeout. The problem is that when I run my flask from localhost it works great. Trying to use cassandra driver from the python console on my dev environment works too and connects with no error. How can I debug this kind of setup when it works locally but not in production?
As you're running behind nginx it might be that setting the keep_alive timeout in the http section of your nginx.conf will help. And/or proxy_send_timeout,
proxy_read_timeout parameters in the location section.

Problems with external visibility of Flask web-server

I have managed to to install flask and run the hello-world script:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
I was impressed how easy it was. Then I wanted to make my web-server visible externally. As recommended, I put host='0.0.0.0' as the argument of run function. Then I found my IP address (in Google) and put it in the address line of my web browser (while the hello-world-script was running).
As a result I got: "A username and password are being requested" and a dialogue box where I need to put a user name and password. I am not sure but I think it comes from my wireless network. Is there a way to change this behaviour?
How are you trying to run your application? If you run flask as app.run() - flask creates its own WSGI server on your host (by default 127.0.0.1) and port (by default 5000) (need permissions if port < 1000). If you run flask using nginx + WSGI or etc. your server resolves host and port.
Now it looks like you want get application by port which resolved your server like nginx or Apache. Try to get flask application by http://your-server-host-or-ip:5000 with the default port or try to change the port (set explicit) like app.run('0.0.0.0', 8080) and get it by http://your-server-host-or-ip:8080.
By the way, you can always get IP address using command-line tools e.g. ifconfig for Unix-like systems, or ipconfig /all for Windows.
To elaborate a little bit onto what #tbicr said, that password prompt indicates that you're trying to connect to your IP on port 80, which is most likely hosting an administration page for your router/modem. You want to connect to your IP on port 5000, the default port for Flask apps run with app.run().

Categories

Resources