I wrote these classes to define a HTTP response:
from django.http import HttpResponse
import json
class BaseResponse:
code = {
'SUCCESS': [0, ''],
'FAIL':[-1, '']
}
def __init__(self):
pass
@classmethod
def response(cls, error, code, ret):
ret = {
'error':error,
'code':code,
'ret':ret
}
return HttpResponse(json.dumps(ret))
@classmethod
def responseWithCodeName(cls, codeName, ret):
print "%s\t%s" % (codeName, ret)
# return cls.response(cls.code[codeName][1], cls.code[codeName][0], ret)
@classmethod
def addCoding(cls, codename, code, msg):
cls.code[codename]=[code, msg]
@classmethod
def inherCode(cls):
cls.code.update(BaseResponse.code)
@classmethod
def generateResponseProperties(cls):
for item in cls.code.keys():
print item
print cls.code[item]
cls.__dict__[item] = staticmethod(
lambda ret : cls.responseWithCodeName(item, ret)
)
class BannerResponse(BaseResponse):
code = dict()
class AuthResponse(BaseResponse):
code = dict()
if __name__ =="__main__":
BannerResponse.inherCode()
BannerResponse.addCoding('NOBANNER', '1', "no banner got")
BannerResponse.generateResponseProperties()
BannerResponse.NOBANNER('nobanner')
BannerResponse.SUCCESS('success')
BannerResponse.FAIL('fail')
The results of running this code are:
FAIL
[-1, '']
NOBANNER
['1', 'no banner got']
SUCCESS
[0, '']
SUCCESS nobanner // This should be 'NOBANNER nobanner'
SUCCESS success
SUCCESS fail // This should be "FAIL fail"
Note that the output of generateResponseProperties()
is correct! Is there any secret of python when I use class in this way?
Sorry that the answer in local-variables-in-python-nested-functions do not help me. I have tried the solution in that question, but I still can't figure it out.