TypeError:'data'是此函数的无效关键字参数

问题描述 投票:1回答:2

我正在尝试修改函数request以根据api调用采用不同的参数。例如:在post_categories中,我需要它发送第三个参数data,其中包括我要发布的主体,但get_categories函数不需要第三个参数。我将**kwargs添加到请求函数中,但这是我得到的错误:TypeError: 'data' is an invalid keyword argument for this function

class ApiGateway():
    base_url = 'https://api.com/v3/'

    def request(self, method, endpoint, **kwargs):
        url = f'{self.base_url}{endpoint}'
        kwargs.setdefault('headers', {})
        kwargs['headers'].update({
            'Authorization': f'Bearer ${self.token}',
            'Accept': 'application/json',
        })
        response = requests.request(method, url, **kwargs)
        return response.json()

    def get_categories(self, merchant_id):
        endpoint = f'merchants/{merchant_id}/categories'
        return self.request('GET', endpoint)

    def post_categories(self, merchant_id):
        update = {
            'payment_method': {
                'token': 1234,
                'data': '123556'
            }
        }    
        endpoint = f'merchants/{merchant_id}/categories'
        return self.request('POST', endpoint, data=json.dumps(update)) 
python python-requests kwargs
2个回答
1
投票

我找到了解决方案。我必须指定我想传递给request函数的数据类型,而不是将数据作为kwargs参数传递。我刚刚更新了post_categories函数return self.request('POST', endpoint, data=json.dumps(update))的这一部分,所以现在函数看起来像这样

   def post_categories(self, merchant_id):
        update = {
            'payment_method': {
                'token': 1234,
                'data': '123556'
            }
        }    
        endpoint = f'merchants/{merchant_id}/categories'
   
        return self.request('POST', endpoint, json=update) # <-- updated third parameter

0
投票

你可以做的是在函数data中添加一个额外的参数request。通过将默认值设置为None,您不必每次都提供它,但仍然可以在需要时使用它。

def request(self, method, endpoint, data=None, **kwargs):
    ...
    response = requests.request(method, url, data=data, **kwargs)
© www.soinside.com 2019 - 2024. All rights reserved.