【问题标题】:CherryPy: Create Web Service running behind apache2 (mod_wsgi)CherryPy:创建在 apache2 后面运行的 Web 服务 (mod_wsgi)
【发布时间】:2017-04-28 04:13:10
【问题描述】:

我是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)

我做错了什么?

【问题讨论】:

    标签: python apache rest cherrypy


    【解决方案1】:

    问题 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 会话默认保存在内存中,并且与 mod_wsgi 不兼容。您需要使用文件存储进行会话,例如。调整配置:

    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')]
    }
    

    }

    【讨论】:

    • 直接来自他们的教程之一。错误是cherrypy.quickstartcherrypy.Application。像这样它可以工作,对于任何有同样问题的人来说,downvote 都是错误的。注意:我个人需要让它为我的骄傲工作,但我现在建议完全选择另一个框架,因为文档很少而且经常过时。
    猜你喜欢
    • 1970-01-01
    • 2016-06-06
    • 1970-01-01
    • 2011-08-08
    • 2021-04-09
    • 2015-03-17
    • 1970-01-01
    • 2011-07-27
    • 2016-06-26
    相关资源
    最近更新 更多