Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用于使用外部api的Django中间件_Django_Python 3.x - Fatal编程技术网

用于使用外部api的Django中间件

用于使用外部api的Django中间件,django,python-3.x,Django,Python 3.x,这里的交易,我需要消费一个API,每次我执行一个请求,需要附加一个头,我已经检查了 但这仅适用于传入请求,在这种情况下是否有任何东西可以使用。如评论中所述: class ServiceAPIClient(object): def __init__(self): self.base_url = "http://example.com/api" self.custom_header = "custom: header example" def co

这里的交易,我需要消费一个API,每次我执行一个请求,需要附加一个头,我已经检查了
但这仅适用于传入请求,在这种情况下是否有任何东西可以使用。

如评论中所述:

class ServiceAPIClient(object):

    def __init__(self):
        self.base_url = "http://example.com/api"
        self.custom_header = "custom: header example"

    def consume_endpoint(self, endpoint):
        return requests.get(self.base_url+endpoint, headers=self.custom_header)
然后在视图/模型中使用它,如:

response = ServiceAPIClient().consume_endpoint("/endpoint")

请记住,这是一个愚蠢的例子…

如评论中所述:

class ServiceAPIClient(object):

    def __init__(self):
        self.base_url = "http://example.com/api"
        self.custom_header = "custom: header example"

    def consume_endpoint(self, endpoint):
        return requests.get(self.base_url+endpoint, headers=self.custom_header)
然后在视图/模型中使用它,如:

response = ServiceAPIClient().consume_endpoint("/endpoint")

请记住,这是一个愚蠢的例子…

您是如何使用API的?我正在导入
请求
并像这样使用
请求。get('API/url',headers=custom_header)
为什么不在
custom_header
中传递您需要的头呢?实际上我一直在做,但是,由于我必须执行几个请求,我想知道是否有任何方法可以在每次调用api时自动附加标头。您可以使用python类创建一个哑api客户端,该类只为您执行一次。您如何使用api?我正在导入
请求
并像这样使用
请求。get('api/url',headers=custom_header)
为什么不在
custom_header
中传递所需的头呢?事实上,这就是我一直在做的事情,但由于我必须执行多个请求,我想知道是否有任何方法可以在每次调用api时自动附加头。您可以使用python类创建一个哑api客户端,为您执行一次。