django-腾讯paas-appengine阅读

时间:2022-03-23 18:15:16

1 重写View基类的dispatch函数

api/baseview.py

把application/json做json.loads改成dict类型

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)

  

5 写JsonResponse的子类来处理json信息