本章将重点介绍通过内置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()
下一步是启动服务器;如果成功,您将在屏幕上看到以下消息−