如何在flask-restful get处理程序中输出额外的标头?

时间:2017-11-14 04:51:43

标签: python flask flask-restful

我已经实现了一个flask-restful get处理程序,它返回一个数组中的许多记录。我想将标题“x-total-count”设置为返回的记录数。我能够使用@ api.representation为每个请求添加一个标头,但我正在寻找一种在我的获取处理程序中添加标头的方法,因为它特定于该特定端点。

@api.representation('application/json')
def output_json(data, code, headers=None):
    resp = make_response(json.dumps(data), code)
    headers = dict(headers) if headers else {}
    headers["X-Total-Count"] = str(len(data))
    resp.headers.extend(headers)
    return resp

class Customers(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('page', type=int, required=True)
        parser.add_argument('per-page', type=int, required=True)

        args = parser.parse_args()

        page_num = args['page']
        per_page = args['per-page']

        cxn = sqlite3.connect('chinook.db')
        sql = 'SELECT CustomerId, FirstName, LastName, Address, City, PostalCode, State FROM customers ' + \
              'WHERE CustomerId not in (SELECT CustomerId from customers ' + \
              'ORDER BY LastName ASC LIMIT ' + str((page_num-1) * per_page) + ')' + \
              'ORDER BY LastName ASC LIMIT ' + str(per_page)

        data = []
        for row in cxn.execute(sql):
            data.append({
                "id": row[0], "first-name": row[1], "last-name": row[2], "address": row[3],
                "city": row[4], "state": row[5], "postal-code": row[6] })

        cxn.close()
        return data

0 个答案:

没有答案