本章將重點介紹通過內置CherryPy HTTP伺服器啓用的基於CherryPy的應用SSL。
Configuration
web應用程式中需要不同級別的配置設置;
Web伺服器−連結到HTTP伺服器的設置
引擎−與引擎宿主相關的設置
application&mins;application which is used by the user
Deployment
CherryPy應用程式的部署被認爲是一種非常簡單的方法,其中所有必需的包都可以從Python系統路徑獲得。在共享web託管環境中,web伺服器將駐留在前端,允許主機提供程序執行篩選操作。前端伺服器可以是Apache或lighttpd。
本節將介紹一些在Apache和lighttpd web伺服器後面運行CherryPy應用程式的解決方案。
cherrypy def setup_app(): class Root: @cherrypy.expose def index(self): # Return the hostname used by CherryPy and the remote # caller IP address return "Hello there %s from IP: %s " % (cherrypy.request.base, cherrypy.request.remote.ip) cherrypy.config.update({'server.socket_port': 9091, 'environment': 'production', 'log.screen': False, 'show_tracebacks': False}) cherrypy.tree.mount(Root()) if __name__ == '__main__': setup_app() cherrypy.server.quickstart() cherrypy.engine.start()
SSL
基於CherryPy的應用程式可以支持SSL(安全套接字層)。要啓用SSL支持,必須滿足以下要求&負;
- Have the PyOpenSSL package installed in user’s environment
- Have an SSL certificate and private key on the server
Creating a Certificate and a Private Key
我們來處理證書和私鑰的要求;
- First the user needs a private key −
openssl genrsa -out server.key 2048
- This key is not protected by a password and therefore has a weak protection.
- The following command will be issued −
openssl genrsa -des3 -out server.key 2048
程序將需要密碼短語。如果您的OpenSSL版本允許您提供空字符串,請執行此操作。否則,請輸入默認密碼短語,然後按以下方式將其從生成的密鑰中移除−
openssl rsa -in server.key -out server.key
- Creation of the certificate is as follows −
openssl req -new -key server.key -out server.csr
此過程將要求您輸入一些詳細信息。爲此,必須發出以下命令&負;
openssl x509 -req -days 60 -in server.csr -signkey server.key -out server.crt
新簽署的證書有效期爲60天。
下面的代碼顯示了它的實現−
import cherrypy import os, os.path localDir = os.path.abspath(os.path.dirname(__file__)) CA = os.path.join(localDir, 'server.crt') KEY = os.path.join(localDir, 'server.key') def setup_server(): class Root: @cherrypy.expose def index(self): return "Hello there!" cherrypy.tree.mount(Root()) if __name__ == '__main__': setup_server() cherrypy.config.update({'server.socket_port': 8443, 'environment': 'production', 'log.screen': True, 'server.ssl_certificate': CA, 'server.ssl_private_key': KEY}) cherrypy.server.quickstart() cherrypy.engine.start()
下一步是啓動伺服器;如果成功,您將在螢幕上看到以下消息−