Snake's Home

SSL on flask

比较喜欢flask这个框架,轻便好用。
在搭建web时,有时候需要用到https.作者在搭建IOS分发的时候,itms-services 就需要https.
本文就以自己搭建的做个说明。

Before starting a server with SSL, you need to create private key and a certificate.

1) .key –> private key
2) .ct –>Self signed certificate

eg: 在主路径下建一个文件夹来存认证文件

1
openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout anderson.key -out anderson.crt

代码应该是这样子的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from flask import Flask
from OpenSSL import SSL

import os

context = SSL.Context(SSL.SSLv23_METHOD)
cer = os.path.join(os.path.dirname(__file__), 'resources/anderson.crt')
key = os.path.join(os.path.dirname(__file__), 'resources/anderson.key')

app = Flask(__name__)

@app.route('/')
def hello_world():
return 'Hello World!'

if __name__ == '__main__':
context = (cer, key)
app.run( host='0.0.0.0', port=5000, debug = True, ssl_context=context)

运行起来:

1
2
3
* Running on https://0.0.0.0:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!

页面打开,就有https了。

参考:
Python Flask API in HTTPS

给Rails加上https支持