Python bottle: 返回 JSON 和 @route 属性相关

0 投票
1 回答
882 浏览
提问于 2025-04-17 16:02

我正在尝试用Python的bottle框架写一个WSGI应用。我已经安装了bottle,并且现在和Apache的mod_wsgi模块一起运行,具体的设置可以参考这里:http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide

我想做的是根据URL(请求)返回一个JSON文件。我虽然实现了这个功能,但我觉得这样做不太对,因为方法上有很多绕圈子的地方。我的意思是,

RuntimeError: response has not been started

首先,我不能直接返回一个JSON变量,因为Apache会报错。

其次,mod_wsgi要求我的可调用对象必须命名为“application”,并且需要两个参数,这就意味着我不能使用“@route”这个装饰器,具体的说明可以在这里找到:http://webpython.codepoint.net/wsgi_application_interface

所以,对于第一个问题,我使用了json.dumps方法;而对于第二个问题,我把路由当作环境变量来处理。你能帮我解释一下如何使用“@route”这个装饰器,以及在这种情况下Python bottle的最佳实践吗?我处理这两个问题的方法如下:

#!/usr/bin/python

import  sys, os, time
import  json
import  MySQLdb
import  bottle
import  cgi

os.chdir( os.path.dirname( __file__ ) )
bottle.debug( True )
application = bottle.default_app( )

@bottle.route( '/wsgi/<parameter>' )
def     application( environ, start_response ) :

        # URL   = bottle.request.method
        URL = environ["PATH_INFO"]

        status                  = '200 OK'
        response_headers        = [('Content-type', 'application/json')]
        start_response( status, response_headers )

        demo    = { 'status':'online', 'servertime':time.time(), 'url':URL }
        demo    = json.dumps( demo )

        return  demo

1 个回答

0

根据评论的内容,你应该像这样写一个瓶子应用程序(这是根据你的代码改编的):

#!/usr/bin/python

import  sys, os, time
import  bottle

@bottle.route( '/wsgi/<parameter>' )
def application(parameter):
    return {'status':'online', 'servertime': time.time(), 'url': bottle.request.path}

if __name__ == '__main__':
    bottle.run(host="localhost", port=8080, debug=True)

用curl进行测试:

$curl -i http://127.0.0.1:8080/wsgi/test
HTTP/1.0 200 OK
Date: Tue, 02 Apr 2013 09:25:18 GMT
Server: WSGIServer/0.1 Python/2.7.3
Content-Length: 73
Content-Type: application/json

{"status": "online", "url": "/wsgi/test", "servertime": 1364894718.82041}

撰写回答