- Django应用
#重写函数,返回json
class JSONResponse(HttpResponse):
"""
An HttpResponse that renders its content into JSON.
"""
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
#返回json
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
- 模板
# 模板1
class LayerChart(TopLevelMixin, _EncodingMixin, core.TopLevelLayerSpec):
def __init__(self, data=Undefined, layer=(), **kwargs):
for spec in layer:
_check_if_valid_subspec(spec, "LayerChart")
_check_if_can_be_layered(spec)
super(LayerChart, self).__init__(data=data, layer=list(layer), **kwargs)
self.data, self.layer = _combine_subchart_data(self.data, self.layer)
# 模板2
#1. 定义
from log import logger
class AsstException(Exception):
def __init__(self, message):
super().__init__(message)
logger.error(message)
#2. 使用
from exception import AsstException
class Messenger(object):
def __init__(self, sc_key):
if not sc_key:
raise AsstException('sc_key can not be empty')
#模板3
# 装饰类中函数的装饰器第一个参数是self
def connection_closed_handler(function):
@wraps(function)
def _wrap(inst, *args, **kwargs):
try:
return function(inst, *args, **kwargs)
except (ConnectionClosedException, WebSocketConnectionClosedException):
inst.logger.warn("the connection lost. Resetting ...")
inst.reset(args[1])
return function(inst, *args, **kwargs)
return _wrap
#模板4
class A:
def add(self, x):
y = x+1
print(y)
class B(A):
def add(self, x):
super().add(x)
b = B()
b.add(2) # 3