2013-05-19 13 views
17

Come si imposta il codice di stato HTTP della mia risposta in Bottiglia?Impostazione del codice di stato HTTP in Bottiglia?

from bottle import app, run, route, Response 

@route('/') 
def f(): 
    Response.status = 300 # also tried `Response.status_code = 300` 
    return dict(hello='world') 

'''StripPathMiddleware defined: 
    http://bottlepy.org/docs/dev/recipes.html#ignore-trailing-slashes 
''' 

run(host='localhost', app=StripPathMiddleware(app())) 

Come si può vedere, l'uscita non restituisce il codice di stato HTTP ho impostato:

$ curl localhost:8080 -i 
HTTP/1.0 200 OK 
Date: Sun, 19 May 2013 18:28:12 GMT 
Server: WSGIServer/0.1 Python/2.7.4 
Content-Length: 18 
Content-Type: application/json 

{"hello": "world"} 
+0

non risponde alla richiesta di importazione della bottiglia; response.status = 300' lavoro? http://bottlepy.org/docs/dev/api.html#bottle.response – dm03514

+1

Sì, questo ha fatto il trucco. Grazie :) –

risposta

30

Credo che si dovrebbe utilizzare response

from bottle import response; response.status = 300

12

Bottiglia del costruito -in tipo di risposta gestisce i codici di stato con garbo. Prendere in considerazione qualcosa di simile:

return bottle.HTTPResponse(status=300, body=theBody) 

Come in:

import json 
from bottle import HTTPResponse 

@route('/') 
def f(): 
    theBody = json.dumps({'hello': 'world'}) # you seem to want a JSON response 
    return bottle.HTTPResponse(status=300, body=theBody) 
+0

La risposta di dm03514 era ciò che stavo cercando. Mi dà tutto quello che cercavo, senza richiedere alcuna modifica al mio codice (a parte il nome rinominato da 'Response' a' response'. –

-1

rilancio può essere utilizzato per ottenere più potenza con HTTPResponse per mostrare il codice di stato (200.302.401):

Come si può semplicemente fare questo way:

import json 
from bottle import HTTPResponse 

response={} 
headers = {'Content-type': 'application/json'} 
response['status'] ="Success" 
response['message']="Hello World." 
result = json.dumps(response,headers) 
raise HTTPResponse(result,status=200,headers=headers) 
Problemi correlati