2010-08-17 28 views
24

如何從瓶子請求處理程序返回json數據。我在瓶子src中看到一個dict2json方法,但我不知道如何使用它。Bottle和Json

什麼是文檔中:

@route('/spam') 
def spam(): 
    return {'status':'online', 'servertime':time.time()} 

給了我這個當我打開該頁面:

<html> 
    <head></head> 
    <body>statusservertime</body> 
</html> 
+1

I轉移到燒瓶,它工作正常。 – arinte 2010-09-20 19:57:26

+0

你也可以使用import json然後json.dumps(dict)。但好的舉動,我也走瓶和燒瓶之間,最終選擇燒瓶。我喜歡瓶子是輕量級的,沒有一個更大的框架。但是像類型化的url params這樣的東西總是會贏回我的日常檢測或索引,例如/ blog/////Where bottle only:param names。所以具有4個斜線的路徑並不總是日期/博客類型的URL。由於這樣的東西,我使用這兩種方式,但傾向於爲更大的應用程序燒瓶。 – 2011-01-05 18:45:17

+0

我也有這個問題。當我使用curl -I時,我發現內容類型是錯誤的:Content-Type:text/html; charset = UTF-8 – 2013-04-23 22:04:37

回答

43

簡單地返回一個字典。 Bottle爲您處理轉換爲JSON。

即使是字典也是允許的。它們被轉換爲json,並將Content-Type頭部設置爲application/json。要禁用此功能(並將字典傳遞給中間件),可以將bottle.default_app()。autojson設置爲False。

@route('/api/status') 
def api_status(): 
    return {'status':'online', 'servertime':time.time()} 

the documentation.

兩者http://bottlepy.org/docs/stable/api.html#the-bottle-class

+2

這實際上並沒有回答問題 – 2013-10-10 18:11:55

+4

什麼?它當然... – 2015-02-09 20:06:06

3

return {'status':'online', 'servertime':time.time()}作品非常適合我。你有沒有進口time

這工作:

import time 
from bottle import route, run 

@route('/') 
def index(): 
    return {'status':'online', 'servertime':time.time()} 

run(host='localhost', port=8080) 
+0

這並不適合我。我沒有進口時間。我想這是一個與版本相關的行爲變化。 – 2013-04-23 21:58:38

6

出於某種原因,瓶的自動JSON功能不會爲我工作。如果它不爲你工作,要麼,你可以使用這個裝飾:

def json_result(f): 
    def g(*a, **k): 
     return json.dumps(f(*a, **k)) 
    return g 

也很方便:

def mime(mime_type): 
    def decorator(f): 
     def g(*a, **k): 
      response.content_type = mime_type 
      return f(*a, **k) 
     return g 
    return decorator 
+0

這對我來說很適合返回字典的數組,這不是瓶子處理的 – 2013-05-11 18:27:32

+1

你不應該返回一個字典列表,這就是爲什麼瓶子如此困難(以及瓶子)。看到這裏:http://flask.pocoo.org/docs/security/#json-security – 2013-07-24 14:44:00

+0

哇,謝謝指出。 – 2013-09-26 18:40:35

0

嘗試這應該按預期工作

from bson.json_util import dumps 
from bottle import route, run 
import time 

@route('/') 
def index(): 
    return {'status':'online', 'servertime':dumps(time.time()) } 

run(host='localhost', port=8080) 
0

很容易讓JSON使用瓶子的請求模塊

from bottle import request 

json_data = request.json # json_data is in the dictionary format 
相關問題