flask下https教程

一、定义

  1. linux 下flask https 协议

二、实现

  1. linux 下flask https 协议

  2. 生成SSL证书和密钥文件。您可以使用工具如openssl来生成自签名SSL证书和密钥文件。运行以下命令生成证书和密钥文件:

openssl req -x509 -newkey rsa:4096 -nodes -out cert.pem -keyout key.pem -days 365

flask下https教程_第1张图片
2. 将生成的cert.pem和key.pem文件放置在您的Flask应用程序目录中。
3.在您的Flask应用程序中添加以下代码来配置HTTPS:

from flask import Flask
from flask_sslify import SSLify
# pip install flask-sslify
app = Flask(__name__)

# 为Flask应用程序启用SSLify
sslify = SSLify(app)

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=8002,ssl_context=('cert.pem', 'key.pem'))

客户端

import requests


res = requests.post("https://127.0.0.1:8012/test",verify=False)   #无ssh 证书

print(res.json())

方式二、

#coding=utf8
from gevent import monkey
monkey.patch_all()
from flask import Flask,Response,stream_with_context,request,send_file
from gevent.pywsgi import WSGIServer
import json
import sys
import os
sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))
sys.path.append("..")
import logging

import time
logging.basicConfig(level=logging.INFO,format="%(asctime)s-%(filename)s-%(lineno)d-%(levelname)s-%(message)s")
from flask_sslify import SSLify
from flask import Flask

app = Flask(__name__)

now = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time()))

sslify = SSLify(app)


'''返回标准格式'''
class ResponseSocket():
    def BasicResponse(self,code=200,msg="成功",ans="",html=False,healthy=1,finish=False,use_time=0):
        return {"code":str(code),"msg":msg,"ans":ans,"html":html,"healthy":healthy,"finish":finish,"uesd_time":use_time}





@app.route('/test',methods=["POST","OPTIONS","GET"])
def modularity():
    res = "成功"
    return json.dumps(ResponseSocket().BasicResponse(ans=res,finish=True),ensure_ascii=False)


if __name__ == "__main__":
    print("server start")
    http_server = WSGIServer(('0.0.0.0', int(8012)), app,keyfile='key.pem', certfile='cert.pem')
    http_server.serve_forever()

方式三、

from flask import Flask  
  
app = Flask(__name__)  
  
class ResponseSocket():
    def BasicResponse(self,code=200,msg="成功",ans="",html=False,healthy=1,finish=False,use_time=0):
        return {"code":str(code),"msg":msg,"ans":ans,"html":html,"healthy":healthy,"finish":finish,"uesd_time":use_time}

@app.route('/test',methods=["POST","OPTIONS","GET"])
def modularity():
    res = "成功"
    return json.dumps(ResponseSocket().BasicResponse(ans=res,finish=True),ensure_ascii=False)

gunicorn --workers 3 --worker-class gevent --certfile=cert.pem --keyfile=key.pem app:app -b 0.0.0.0:8012

你可能感兴趣的:(flask,flask,https,python)