2014年5月13日 星期二

Python-flask SSL

最近為了web的final project,小研究了一下flask,發現flask實在是太棒喏

自從開始寫nodejs後,覺得nodejs實在是個好東西,最近要寫關於dropbox的app,好死不死竟然沒有nodejs的SDK,剛好我對python情有獨鍾,於是就下載了python來研究,沒想到python SDK裡面附的example都用flask來寫的,查了一下flask的官網,實在是太shock喏,寫法完全跟nodejs的寫法一樣,想當初還一直努力的看Django,花了好一段時間去看Document才了會用,flask短短的幾行範例code就把我教會惹!太開心了!改天再來筆記相關的寫法!

為了web的final,不得已需要使用HTTPS才能work(dropbox的api限制除了localhost可以用http之外,其餘的一律https),上官網查了一下要讓flask的app支援https,需要增加下面幾個步驟

1. 安裝openSSL:

在cent-os系列下可以使用

$ yum install openssl-devel

在debian系列下可以使用

$ apt-get install libssl-dev

Reference: stackoverflow

2. generate key and certificate:

執行以下指令來generate private key

$ openssl genrsa 1024 > ssl.key

generate certificate

$ openssl req -new -x509 -nodes -sha1 -days 365 -key ssl.key > ssl.cert

Reference: Serving WSGI Applications

3. add some code in app:

最後在自己建立的flask app的py檔裡面增加以下幾行code,即可讓app以https來傳輸

from OpenSSL import SSL
context = SSL.Context(SSL.SSLv23_METHOD)
context.use_privatekey_file('yourserver.key')
context.use_certificate_file('yourserver.crt')

then

app.run(host='0.0.0.0',port='5566', 
        debug = False/True, ssl_context=context)

Reference: How to serve HTTPS *directly* from Flask

沒有留言:

張貼留言