2012/02/29

Tornado web framework + HTTPS

官網得知 Tornado web framework 原本就有支援SSL協定
HTTPServer can serve SSL traffic with Python 2.6+ and OpenSSL. To make this server serve SSL traffic, send the ssl_options dictionary argument with the arguments required for the ssl.wrap_socket method, including “certfile” and “keyfile”:
    HTTPServer(applicaton, ssl_options={
        "certfile": os.path.join(data_dir, "mydomain.crt"),
        "keyfile": os.path.join(data_dir, "mydomain.key"),
    })

SSL Sample
import os
from tornado.httpserver import HTTPServer
from tornado.web import Application, RequestHandler
from tornado.ioloop import IOLoop

class MainHandler(RequestHandler):
    def get(self):
        self.write("Hello world!")

def main():
    application = Application([
        (r"/", MainHandler), 
    ])  

    http_server = HTTPServer(application,  
        ssl_options={
            "certfile": os.path.join(os.path.abspath("."), "test.crt"), 
            "keyfile": os.path.join(os.path.abspath("."), "test.key"), 
        }   
    )

    http_server.listen(8080)
    IOLoop.instance().start()

if __name__ == "__main__":
    main()

過程中需要ssl certificate 與 private key,可以用openssl產生,不過過程很繁雜,建議可以利用online tool:Create self-signed SSL certificates online

測試
開啓 http://localhost:8080 遇到錯誤:
ERROR:root:Exception in I/O handler for fd 3 Traceback (most recent call last): File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/tornado-2.0-py2.6.egg/tornado/ioloop.py", line 287, in start self._handlers[fd](fd, events) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/tornado-2.0-py2.6.egg/tornado/stack_context.py", line 159, in wrapped callback(*args, **kwargs) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/tornado-2.0-py2.6.egg/tornado/httpserver.py", line 294, in _handle_events except ssl.SSLError, err: AttributeError: 'module' object has no attribute 'SSLError' 

少了甚麼module嗎?
重裝openssl 0.9.8t -> 不行


安裝ssl package
# pip install ssl
ValueError: This extension should not be used with Python 2.6 or later (already built in), and has not been tested with Python 2.3.4 or earlier.
python 2.6以後的版本已經內建了


安裝pyopenssl package
# pip install pyopenssl
安裝成功,但結果還是一樣。看起來該有的都有了阿!


最後把deploy系統從mac os換到centos 5,一模一樣的步驟就...成功了!上面的問題至今未解...


如果看到這個warning,表示client的request是用http不是https,並不是server的問題唷!
WARNING:root:SSL Error on 7: [Errno 1] _ssl.c:490: error:1407609C:SSL routines:SSL23_GET_CLIENT_HELLO:http request


沒有留言:

張貼留言