简体   繁体   中英

Handling HTTPS post request in python flask

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

当您运行脚本时(或者如果您愿意,可以从 flask run 开始),您会注意到 Flask 表明它正在运行一个 https:// 实例

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM