Skip to main content
 首页 » 编程设计

python之CherryPy:创建在 apache2 (mod_wsgi) 后面运行的 Web 服务

2024年10月17日30bluestorm

我是 cherrypy 的新手,选择它来创建用于其他网络应用程序的网络服务。我想使用 apache2 和 mod_wsgi 来运行它。我跟着相当 old documentation Hello World 的例子工作得很好。

我现在正在查看 turotials,当然还有 REST tutorial .但是我无法让它运行。我在 apache 日志中获得状态 500 和错误:

TypeError: expose_() missing 1 required positional argument: 'func' 

为了做到这一点,我调整了教程中类似于 hello world 示例的脚本以使用 apache:

import sys 
sys.stdout = sys.stderr 
 
import random 
import string 
 
import cherrypy 
 
cherrypy.config.update({'environment': 'embedded'}) 
 
@cherrypy.expose 
class StringGeneratorWebService(object): 
 
    @cherrypy.tools.accept(media='text/plain') 
    def GET(self): 
        return cherrypy.session['mystring'] 
 
    def POST(self, length=8): 
        some_string = ''.join(random.sample(string.hexdigits, int(length))) 
        cherrypy.session['mystring'] = some_string 
        return some_string 
 
    def PUT(self, another_string): 
        cherrypy.session['mystring'] = another_string 
 
    def DELETE(self): 
        cherrypy.session.pop('mystring', None) 
 
 
conf = { 
    '/': { 
        'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 
        'tools.sessions.on': True, 
        'tools.response_headers.on': True, 
        'tools.response_headers.headers': [('Content-Type', 'text/plain')], 
    } 
} 
cherrypy.quickstart(StringGeneratorWebService(), '/', conf) 

我做错了什么?

请您参考如下方法:

问题 1:

TypeError: expose_() missing 1 required positional argument: 'func' 

是因为我使用的是 anaconda python 并且使用 conda install cherrypy 安装的 cherrypy 版本已过时 (3.8.0)。删除该版本并使用 pip 安装最新版本解决了这个问题。

问题 2:

路线错误。

cherrypy.quickstart(StringGeneratorWebService(), '/', conf) 

应该是

cherrypy.Application(StringGeneratorWebService(), script_name=None, config=conf) 

然后只需输入脚本文件的路径即可。

问题 3:

cherrypy session 默认在内存中,不能很好地与 mod_wsgi 配合使用。您需要为 session 使用文件存储,例如。调整配置:

conf = { 
'/': { 
    'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 
    'tools.sessions.on': True, 
    'tools.sessions.storage_type': 'file', 
    'tools.sessions.storage_path': '/path/to/sessions', # in case of 500 error check privileges of session folder!!! 
    'tools.response_headers.on': True, 
    'tools.response_headers.headers': [('Content-Type', 'text/plain')] 
}