Handling HTTPS post request in python flask - python

I have made a simple python flask program :
# save this as app.py
from flask import request
from flask import Flask
app = Flask(__name__)
#app.route("/", methods=['POST'])
def hello():
return "Hello, World!"
#app.route("/sms", methods=['POST'])
def sms():
print(request.get_json())
return "sms world"
if __name__ == '__main__':
app.run(port=443, host='0.0.0.0', ssl_context='adhoc')
This handles the HTTP post request. How can I make it handle HTTPS post requests?
When I execute the command flask run I get the following:
Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server
instead. * Debug mode: off * Running on http://127.0.0.1:5000/
(Press CTRL+C to quit)
So it still uses HTTP instead of https

pip install pyopenssl
When you run the script (or start with flask run if you prefer), you will notice that Flask indicates that it is running an https:// istance

first install pyopenssl with the command:
pip install pyopenssl
to launch it in https just add the parameter: ssl_context='adhoc'
if __name__ == '__main__':
app.run(port=443, host='0.0.0.0', ssl_context='adhoc')
Once started the following message will be shown:
* Serving Flask app 'test' (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: off
* Running on all addresses.
WARNING: This is a development server. Do not use it in a production deployment.
* Running on https://192.168.0.62:443/ (Press CTRL+C to quit)
Obviously then once the application goes into production this parameter will no longer be needed, but you will have to set your wsgi to communicate in https

You can try ngrok, it is a useful tool to deploy an HTTPS and HTTP service from local to public net.
https://ngrok.com/

Related

Name error depending on debug mode of python flask application

When running the flask app 'app.py' without debug mode, everything runs fine:
app = Flask(__name__)
#app.route("/")
def home():
return "Hey there"
if __name__=="__main__":
app.run()
Server startign:
* 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: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
When running the Flask app in debug mode
app.run(debug=True) I'll get "No module named app" error and the server won't start:
* 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
* Restarting with stat
No module named app
I have noticed that when starting the script in vsCode without debug mode (ctrl+f5) or press the button 'Run Python File' everything works fine.
When I start debugging (f5) in vsCode the 'No module named app' occurs and after the failed server start I jump back to the parent folder (app.py is in /folder/app/app.py - after server start failed I am in the terminal in the '/folder' rather then '/folder/app' like before starting the script.
Does anyone got an idea where the problem is? Appreciate any help
The problem can be resolved by adding a launch.json file to the workspace and adding either an absolute to your app.py file:
"cwd":"path/to/folder/"
or a relative path to the directory of the executed script:
"cwd":"${fileDirname}"

Flask auto-reload functionality not working with Pycharm Remote Deployment

It's hard to remember when, but at one point the auto-reload function of Flask started to not work anymore in my project.
This is the output upon starting my app :
FLASK_APP = back/python/app/app.py:app
FLASK_ENV = development
FLASK_DEBUG = 1
In folder C:/path/to/project
ssh://[VirtualMachineIP]:22/root/env/bin/python3.7 -u -m flask run -h 0.0.0.0 -p 1234
* Serving Flask app 'back/python/app/app.py:app' (lazy loading)
* Environment: development
* Debug mode: on
* Running on all addresses.
WARNING: This is a development server. Do not use it in a production deployment.
* Running on http://[VirtualMachineIP]:1234/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 106-048-128
The development environment and Debug mode are both on. Thus, upon saving changes in a file (while the app is deployed) I get the usual message :
* Detected change in '/path/to/changed/file.py', reloading
Signaling that the app is reloading with the new code. Except it doesn't reload anything, and the message doesn't appear on any further changes until I'm forced to restart the app.
PyCharms runs on Windows and communicates via ssh to my Virtual Machine, where the code is executed. I have installed the following modules:
flask
flask-socketio
eventlet
flask-cors
Any help is welcomed. Thanks :)
The FLASK_DEBUG environment variable is badly supported, it may not behave as expected if set in code. (Quoted from the source of flask).
It suggest to use flask run in debug mode.
eg: $ flask --app hello --debug run
If it still not work, you can force to use reloader like this:
if __name__ == '__main__':
app.run(host=config.HOST, port=config.PORT, debug=True)
Take care, the app.run() must be wrapped with if __name__ == '__main__'.
doc: https://flask.palletsprojects.com/en/2.2.x/config/#DEBUG

python flask to production server

I have made a small API to connect to a database using Flask.
When I run it I get this output on local (which works fine in postman)
* Serving Flask app "main" (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: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
I want to run this file (main.py) on a server that I have at 172.22.98.254. But when I run it there it still gives me this output:
* Serving Flask app "main" (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: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
So, when I use my postman doing this
where my post URL is http://172.22.98.254:5000/test, How can I use this from the server that I have. I have an ubuntu server.
By default, app.run() hosts server on localhost(127.0.0.1). To make it accessible,
app.run('0.0.0.0', port=5000)
Although, the server bundled with Flask is not for production, it is recommended to use WSGI server(mod_wsgi, nginx, gunicorn, etc.)
https://flask.palletsprojects.com/en/1.0.x/deploying/wsgi-standalone/
I have changed the host default ip address to server or Local network computer ip address. it works fine. My local ip address is 192.168.1.34, using same port as 5000.
app.run(host='192.168.1.34', port=5000)

Trying to run flask with the following code [duplicate]

This question already has answers here:
Warning message while running Flask
(12 answers)
Closed 2 years ago.
from flask import Flask
app = Flask(_name_)
#app.route('/')
def index():
return '<h1>Hello, world</h1>'
I get this error
* Serving Flask app "application.py"
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
This is just a warning as flask server is not meant for production.
You can use
export FLASK_ENV=development
before flask run
It depends if you are running it from command line or adding python code to run it.
If you want to run it with Python, add this to the bottom of your code.
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
(you can change the port number, to access it on a browser, type: 127.0.0.1:80)
If you are running it from command line, you run
flask run
Note this appears every time:
Serving Flask app "application.py" * Environment: production WARNING:
This is a development server. Do not use it in a production
deployment. Use a production WSGI server instead. * Debug mode: off
All it tells you is that this server is only used for development or production. Hosting it for commercial/public use would require additional files and web hosting.
You can allow debugging to be on with
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, DEBUG=True)
OR
export FLASK_ENV=development (linux/macos)
set FLASK_ENV=development (Windows)
Hope this helps (follow me on GitHub #haydenso)

Flask at first run: Do not use the development server in a production environment

I installed the Flask plugin in PyCharm Community Edition and I just have this simple code in my flask app:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return '<h1>Hello!</h1>'
if __name__ == "__main__":
app.run(debug=True)
And I get this message:
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead
* Restarting with stat
* Debugger is active!
* Debugger PIN: 123-456-789
* Running on http://127.0.0.1:5000/
Why am I getting this error when I run Flask?
A previous version of the message read "Do not use the development server in a production environment."
For deploying an application to production, one option is to use Waitress, a production WSGI server.
Here is an example of using waitress in the code.
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "<h1>Hello!</h1>"
if __name__ == "__main__":
from waitress import serve
serve(app, host="0.0.0.0", port=8080)
Running the application:
$ python hello.py
Waitress also provides a command line utility waitress-serve. To use that, you can modify the code to the following:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "<h1>Hello!</h1>"
def create_app():
return app
Then we can use waitress-serve as the following:
waitress-serve --port=8080 --call hello:create_app
And BTW, 8080 is the default port.
To validate the deployment, open a separate window:
% curl localhost:8080
<h1>Hello!</h1>%
Or directly in your browser http://localhost:8080/.
Other alternatives to deploy your app include Gunicorn and uWSGI. For more details, please refer to the flask deploy doc.
As of Flask 2.2, the development server always shows this warning, it is not possible to disable it. The development server is not intended for use in production. It is not designed to be particularly efficient, stable, or secure. Use a production WSGI server instead. See the deployment docs from Flask for more information.
That warning is just a warning though, it's not an error preventing your app from running. If your app isn't working, there's something else wrong with your code.
That warning applies to the development server, not Flask itself. The Flask framework is appropriate for any type of application and deployment.
To avoid these messsages, inside the CLI (Command Line Interface), run these commands.
export FLASK_APP=app.py
export FLASK_ENV=development
export FLASK_DEBUG=0
flask run
If for some people (like me earlier) the above answers don't work, I think the following answer would work (for Mac users I think)
Enter the following commands to do flask run
$ export FLASK_APP=hello.py
$ export FLASK_ENV=development
$ flask run
Alternatively you can do the following (I haven't tried this but one resource online talks about it)
$ export FLASK_APP=hello.py
$ python -m flask run
source: For more
Try gevent:
from flask import Flask
from gevent.pywsgi import WSGIServer
app = Flask(__name__)
#app.route('/api', methods=['GET'])
def index():
return "Hello, World!"
if __name__ == '__main__':
# Debug/Development
# app.run(debug=True, host="0.0.0.0", port="5000")
# Production
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()
Note: Install gevent using pip install gevent
This worked for me on windows:
$env:FLASK_APP="flask_project.py"
$env:FLASK_ENV="development"
flask run
flask_project.py is on the same path as my virtual environment.

Categories

Resources