인수의 유효성을 자동으로 확인하기 위해 RequestHandler를 어떻게 하위 클래스로 분류합니까?

StackOverflow https://stackoverflow.com//questions/23012316

  •  21-12-2019
  •  | 
  •  

문제

다음 코드가 있습니다.

class CounterIDHandler(RequestHandler):
    @gen.coroutine
    def get(self, counter_id):
        try:
            object_id = bson.objectid.ObjectId(counter_id)
        except bson.errors.InvalidId as e:
            self.finish(json_encode({'e': str(e)}))
            return
            # I want to finish execution here

class CounterHandler(CounterIDHandler):
    @gen.coroutine
    def get(self, counter_id):
        super().get(counter_id)
        print("this should not print if we get exception in super().get")
        try:
            # I want to use object_id here
        except Exception as e:
            self.finish(json_encode({'e': str(e)}))

이것은 분명히 작동하지 않지만 내가하려는 일을 보여줍니다.self.finish() 클라이언트와의 연결은 종료되지만 실행은 종료되지 않습니다.

모든 핸들러에 코드를 복사하여 붙여넣지 않고 counter_id가 유효한 object_id인지 확인하고 싶습니다.

도움이 되었습니까?

해결책

이걸 왜 넣는거야? get() 기본 수업에서?이건 따로 들어가야 할 것 같네요 get_object_id 방법.어떤 경우든 공유 메서드가 호출자에게 영향을 미치는 방법에는 두 가지가 있습니다.예외 및 반환 값.

호출자가 중지해야 함을 알리기 위해 None 반환 값을 사용합니다.

class CounterIDHandler(RequestHandler):
    def get_object_id(self, counter_id):
        try:
            return bson.objectid.ObjectId(counter_id)
        except bson.errors.InvalidId as e:
            self.finish(json_encode({'e': str(e)}))
            return None

class CounterHandler(CounterIDHandler):
    def get(self, counter_id):
        object_id = self.get_object_id(counter_id)
        if object_id is None:
            return

또는 예외가 있는 경우 write_error 매니저:

class CounterIDHandler(RequestHandler):
    def get_object_id(self, counter_id):
        return bson.objectid.ObjectId(counter_id)

    def write_error(self, status_code, **kwargs):
        if 'exc_info' in kwargs:
            typ, exc, tb = kwargs['exc_info']
            if isinstance(exc, bson.errors.InvalidId):
                self.finish(json_encode({'e': str(e)}))
                return
        super(CounterIDHandler, self).write_error(status_code, **kwargs)

class CounterHandler(CounterIDHandler):
    def get(self, counter_id):
        object_id = self.get_object_id()

다른 팁

데코레이터를 만들 수 있습니다.이 (테스트되지 않은) :

def oid_validator(f):
    @web.asynchronous
    def wrapped(self, oid_str):
        try:
            oid = bson.objectid.ObjectId(oid_str)
        except bson.errors.InvalidId as e:
            self.finish(json_encode({'e': str(e)}))
        else:
            coro = gen.coroutine(f)
            coro(self, oid)
.

그런 다음 get()를 사용하여 @gen.coroutine 메소드를 장식하는 대신 @oid_validator로 장식 할 수 있습니다.

class CounterIDHandler(RequestHandler):
    @oid_validator
    def get(self, counter_id):
        # counter_id is now an ObjectId instance
.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top