# middleware\_status

## 1 路径

```
butterfly/handlers/middleware.py
```

## 2 代码

```
from xlib.util import http_util
from conf import config

class Middleware():
    '''
    Middleware
    '''

    def __init__(self, protocol):
        self.protocol = protocol
        self.addr = config.URLS["xinghe_addr"]

    def xinghe_report(self, req):
        """
        xinghe_report
        """
        url = "{addr}/xinghe/api_collect".format(addr=self.addr)
        if req.log_ret_code == "OK" or req.log_ret_code == "ERR_TASK_ING":
            # 正常
            api_stat = 0
        else:
            api_stat = 1

        # "/xx/xx_1" ==> "xx"
        user_flag = req.funcname.split("/")[1]

        data = {
                "user_flag": user_flag,
                "api_name": req.funcname,
                "api_requestid": req.reqid,
                "api_stat": api_stat,
                "api_errmsg": req.log_ret_code,
                }
        http_util.post_json(url, data=data)

    def __call__(self, req):
        httpstatus, headers, content = self.protocol(req)
        self.xinghe_report(req)
        return httpstatus, headers, content
```

自定义返回 HTTP code

```
import httplib
status = 401
status_line = "%s %s" % (status, httplib.responses.get(status, ""))
return status_line, [], ""
```
