Reputation: 4915
I made a simple server using python flask in mac. Please find below the code.
from flask import Flask
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def hello():
print("request received")
return "Hello world!"
if __name__ == "__main__":
app.run(debug=True)
I run it using python3 main.py
command.
While calling above API on url http://localhost:5000/
from Postman using GET / POST method, it always returns http 403 error.
Python version : 3.8.9
OS : Mac OS 12.4
Flask : 2.1.2
Upvotes: 50
Views: 35699
Reputation: 81
In addition to ShivaGaire's solution, had to change the first parameter within the Flask class from __name__
to the app directory per the official docs:
For example if your application is defined in
yourapplication/app.py
you should create it with one of the two versions below:
app = Flask('yourapplication')
app = Flask(__name__.split('.')[0])
Why is that? The application will work even with name, thanks to how resources are looked up. However it will make debugging more painful. Certain extensions can make assumptions based on the import name of your application.
So the two snippets in my app.py
look like this:
# app = Flask(__name__) # default
app = Flask("openai-quickstart-python") # custom w/host, port, debug options
...
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000, debug=True)
Finally, the app can be run as-is via python app.py
; note that flask run
won't respect the overrides and would need to be adjusted manually — which defeats the purpose.
To do the latter, use
flask run --host 0.0.0.0 --port 8000 --debugger
Upvotes: 2
Reputation: 2841
Mac OSX Monterey (12.x) currently uses ports 5000 and 7000 for its Control centre hence the issue.
Try running your app from port other than 5000
and 7000
use this:
if __name__ == "__main__":
app.run(port=8000, debug=True)
and then run your flask file, eg: app.py
python app.py
You can also run using the flask
command line interface using this command provided you have set the environment variable necessary for flask CLI.
flask run --port 8000
You can also turn off AirPlay Receiver
in the Sharing
via System Preference.
Related discussion here: https://developer.apple.com/forums/thread/682332
Update(November 2022):
Mac OSX Ventura(13.x) still has this problem and is fixed with the change in default port as mentioned above.
Upvotes: 115