flask配置https
程序员文章站
2022-03-07 11:08:36
...
登录linux机器,centos自带openssl
openssl genrsa -des3 -out server.key 1024
openssl req -new -key server.key -out server.csr
cp server.key server.key.or
openssl rsa -in server.key.org -out server.key
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
1 flask自身配置https
flask启动按照下面进行配置
app.run(host='0.0.0.0',port=5000,debug=True,ssl_context=('./server.crt','./server.key'))
2 nginx配置https
一般情况并不会由flask自己做https,总需要nginx做反向代理,进行内外网隔离。故可以在nginx中增加配置
server {
listen 443 ssl;
client_max_body_size 100M;
#mycom
server_name www.dzmsoft.com ;
charset utf-8;
ssl on;
#ssl_certificate /application/nginx/nginx/conf/eds_ca/server.crt;
#ssl_certificate_key /application/nginx/nginx/conf/eds_ca/server.key;
ssl_certificate /application/nginx/nginx/conf/mycert.pem;
ssl_certificate_key /application/nginx/nginx/conf/server.key;
ssl_session_cache shared:SSL:10m;
ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
ssl_prefer_server_ciphers on;
index index.jsp default.jsp index.do default.do index.html index.htm index.php forum.php;
access_log logs/dzmsoft_access.log main;
location / {
proxy_pass http://dzmsoft_p;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|ico|svg|flv|xml)(.*)$
{
expires 15d;
proxy_pass http://dzmsoft_p;
}
location ~ .*\.(js|css|gzcss|gzjs)(.*)$
{
expires 1d;
proxy_pass http://dzmsoft_p;
}
location /(WEB-INF)/ {
deny all;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|ico|svg|flv|js|css|gzcss|gzjs)?$
{
if (-f $request_filename) {
expires 1d;
break;
}
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
这时flask的启动,应该是
app.run(host='0.0.0.0',port=5000,debug=True)
这里有一点需要注意,nginx配置了https了,那么flask是可以不用配置的https了。
另外下面的配置,也代表了nginx转发请求到flask的web服务是http的,
location / {
proxy_pass http://dzmsoft_p;
}
如果proxy_pass https://dzmsoft_p;
,那么就要求flask也应该是https的,否则接口协议转换就会出现异常,提示HTTP/0.9的问题,以及nginx出现502的问题,和flask接收到乱码。
因为nginx负责转发,而且nginx配置了https,那么nginx已经做了协议转换,就不需要flask再多次一举,故这里配置http即可。
3 python调用https请求示例
重点是verify=False
配置。
import requests
import json
requests.packages.urllib3.disable_warnings()
edata ={
"code" : str(4201),
'paper': str(1)
}
r = requests.post('https://www.dzmsoft.com/api/edata',params = edata, verify=False)
try:
dic_source = json.loads(r.text)
# print(len(dic_source['_source']))
print("总共查询到{}条数据".format(dic_source['total']))
except:
print(r.text)