1 重写View基类的dispatch函数
api/baseview.py
在一个post请求中,在header中,CONTENT_TYPE为application/json,然后在request.body中发送json格式的数据(exp:{"mode":"test","agent_ip":"192.168.1.1","web_port":8000,"agent_port":12345}),这时,在django的request参数中,它是一个bytes数据。
在CBV中,View类都实现了dispatch函数,我们可以通过重写dispatch方法来自定义处理请求(参考https://www.jianshu.com/p/8c23d72878d9)
这个dispatch就把这个bytes数据转化为dict数据,赋值给request.json_data。
class BaseView(View): def dispatch(self, request, *args, **kwargs): if request.method == "POST": if "application/json" in self.request.META["CONTENT_TYPE"]: if request.body: request.json_data = json.loads(request.body) else: request.json_data = {} return super(BaseView, self).dispatch(request, *args, **kwargs)
2 自定义异常
api/response.py
class FailJsonResponse(JsonResponse): def __init__(self, message, **kwargs): data = {} if kwargs: data.update(kwargs) # high priority data.update({ "result": False, "message": message }) if "data" not in data: data["data"] = {} super(FailJsonResponse, self).__init__(data)
3 对app做健康检查
api/utils.py
def agent_header(sid, token): return { "Content-Type": "application/json", "X-ID": str(sid), "X-TOKEN": str(token) } def check_agent_health(bk_server): resp = http.http_request( method="GET", url="http://%s:%s/v1/app/healthz" % (bk_server.ip_address, bk_server.ip_port), headers=agent_header(bk_server.s_id, bk_server.token) ) if resp.get("error") != 0: raise Exception("%s agent return not zero" % bk_server.ip_address) return resp
4 使用UUIDField
api/models.py
class BkServer(models.Model): name = models.CharField(u‘名称‘, max_length=20) s_id = models.UUIDField(u‘服务ID‘, default=uuid.uuid4, editable=False) token = models.UUIDField(default=uuid.uuid4, editable=False)