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

标签 python apache rest cherrypy

我是 Cherrypy 的新手,并选择它来创建用于其他 Web 应用程序的 Web 服务。我想使用 apache2 和 mod_wsgi 运行它。我关注的是old documentation hello world 示例运行得很好。

我现在正在查看教程,当然还有 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 installcherrypy 安装的 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')]
}

}

关于python - CherryPy:创建在 apache2 后面运行的 Web 服务 (mod_wsgi),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41115369/

相关文章:

python - 通过python mechanize上传文件

python - 改变表 Sqlite : how to check if a column exists before alter the table?

apache - 在 rewriteCond 中匹配 HTTP_HOST?

rest - Cereal ,随着休息而延伸

javascript - 使用未定义的数据库列中的快速结果将 html 形式的数据发送到 mysql 数据库

python - 混合 matplotlib 交互式图和内联图?

java - 通过 JSCH (SSH) 和 HTTPS 的反向隧道

linux - FastCGI with perl - 在共享 Linux 虚拟主机上

java - 在 RESTful API 和 WSO2 的背景下,Apache Tomcat 和 Apache Axis2 之间的关系是什么

Python:__subclasses__ 顺序