2011-08-24 18 views
14

बोतल HTTP जहाजों को फेंकने के लिए आयात के साथ जहाजों और एक समारोह के लिए मार्ग।Bottle.py त्रुटि रूटिंग

सबसे पहले, प्रलेखन दावों मैं (और इसलिए कई उदाहरण है) कर सकते हैं: हालांकि

from bottle import error 

@error(500) 
def custom500(error): 
    return 'my custom message' 

, जब इस बयान त्रुटि का आयात समाधान नहीं हुआ है लेकिन पर आवेदन चल रहा है इस पर ध्यान नहीं देता और सिर्फ सामान्य त्रुटि के लिए मुझे निर्देशन पृष्ठ।

मैं एक तरह से इस के आसपास पाने के लिए मिला:

from bottle import Bottle 

main = Bottle() 

@Bottle.error(main, 500) 
def custom500(error): 
    return 'my custom message' 

लेकिन इस कोड मुझे सभी एक अलग मॉड्यूल में मेरी त्रुटियों को एम्बेड गंदगी है कि अगर मैं उन्हें अपने मुख्य में रखा पीछा होगा नियंत्रित करने के लिए से रोकता है। पाई मॉड्यूल क्योंकि पहला तर्क एक बोतल उदाहरण होना चाहिए।

तो मेरे सवालों का:

  1. किसी और को यह अनुभव किया है?

  2. क्यों नहीं देता है त्रुटि केवल मेरे मामले (मैं से स्थापित पिप बोतल स्थापित) में हल करने के लिए लग रहे हैं?

  3. क्या एक अलग पायथन मॉड्यूल से मुख्य त्रुटि में मेरी त्रुटि रूटिंग आयात करने का एक निर्बाध तरीका है?

उत्तर

24

यदि आप किसी अन्य मॉड्यूल में अपने त्रुटियों एम्बेड करना चाहते हैं, तो आप कुछ इस तरह कर सकता है:

error.py

def custom500(error): 
    return 'my custom message' 

handler = { 
    500: custom500, 
} 

app.py

from bottle import * 
import error 

app = Bottle() 
app.error_handler = error.handler 

@app.route('/') 
def divzero(): 
    return 1/0 

run(app) 
+0

वाह। वह सरल और सही था। – comamitc

7

यह मेरे लिए काम करता है:

from bottle import error, run, route, abort 

@error(500) 
def custom500(error): 
    return 'my custom message' 

@route("/") 
def index(): 
    abort("Boo!") 

run() 
0

कुछ मामलों में मुझे लगता है कि बोतल को उपclass करना बेहतर है। ऐसा करने का एक उदाहरण यहां एक कस्टम त्रुटि हैंडलर जोड़ना है।

#!/usr/bin/env python3 
from bottle import Bottle, response, Route 

class MyBottle(Bottle): 
    def __init__(self, *args, **kwargs): 
     Bottle.__init__(self, *args, **kwargs) 
     self.error_handler[404] = self.four04 
     self.add_route(Route(self, "/helloworld", "GET", self.helloworld)) 
    def helloworld(self): 
     response.content_type = "text/plain" 
     yield "Hello, world." 
    def four04(self, httperror): 
     response.content_type = "text/plain" 
     yield "You're 404." 

if __name__ == '__main__': 
    mybottle = MyBottle() 
    mybottle.run(host='localhost', port=8080, quiet=True, debug=True) 
संबंधित मुद्दे