TechnoBabbler

Google App Engine에서 Python으로 작업시에 Custom Status Code 등록하기

naggingmachine 2013. 4. 25. 12:32

GAE에서 python으로 작업하다보면 status code를 등록하고 싶은 경우가 있는데, 실제로는 안됩니다. 임의의 상태 코드를 입력하면 일괄적으로 500 에러가 발생하거든요. 이 경우 다음과 같이 코드를 작성하면 됩니다. 정상적인 방법은 아니므로 잘 작동하는지 항상 확인하세요~ 구글에서 검색해보니 많은 사람들이 같은 고민을 하고 있는것 같아 영어로도 적어둡니다.


When you try to set a custom status code with Python in Google App Engine, you might use Response.set_status() method, but unfortunately you will get 500 error not the custom code you set because set_status() checks whether the code is known, and it will set 500 code if the custom code is unknown. Here is the solution. As you can see, in this solution, I registered the CUSTOM_STATUS_CODE in webapp2._webapp_status_reasons and force to update the status code. I found that status_reasons variable is referenced by other code to check the status code is known or not in webapp2.py. I should say this is not the right way to resolve the problem, but it works well. Use the code at your own risk. :-)


import webapp2

from webob.util import status_reasons


CUSTOM_STATUS_CODE = 290


class CustomPage(webapp2.RequestHandler):

        def get(self):

        # Do your job

                self.response.set_status(CUSTOM_STATUS_CODE)


# Add your new status code

webapp2._webapp_status_reasons[CUSTOM_STATUS_CODE] = 'Some Error'

status_reasons.update(webapp2._webapp_status_reasons)


app = webapp2.WSGIApplication([('/', CustomPage)], debug=False)