如何在Python中的POST请求中将字典传递给url

x7rlezfr  于 2022-12-10  发布在  Python
关注(0)|答案(3)|浏览(262)

我必须通过POST请求从市场的API获取有关产品库存的信息。API要求在URL中发送产品ID(SKU)示例:https://api.market.com/campaigns/{campaignId}/warehouse/{warehouseId}/stocks/actual.json?sku=sku1&sku=sku2&sku=sku3所以我想,我必须通过一个像{'sku':“1”、“SKU”:“2”、“SKU”:'3'}但是当然,用相同的键创建一个字典是不可能的。我不知道如何解决这个任务。我做了一个函数,使用urllib(urlencode),它工作。但是它创建了一个只有params中最后一个元素的url。params = {“sku”:“PS-22-1”、“sku2”:“PS-22-7-2”、“sku3”:“第22-7-3页”}

def get_stocks(self, campaign_id, warehouse_id, sku):
    """ Method for parse stocks
    Parameters:
        campaign_id (int):  client_id in Store
        warehouse_id (int): warehouse_id in Warehouse
        sku (str): product sku in Product
    Returns:
        data (json): JSON with stocks data """
    url = f"{self.url}campaigns/{campaign_id}/warehouses/{warehouse_id}/stocks/actual.json?"
    req = requests.get(url + urllib.parse.urlencode(sku), 
                            headers=self.headers)
    if req.status_code == 200:
        return True, '200', req.json()
    return False, req.json()["error"]["message"]

我在数据库中以这样的模式保存产品ID:

class Product(models.Model):
name = models.CharField(max_length=150)
sku = models.CharField(max_length=10)
uxh89sit

uxh89sit1#

在代码中,将以下行替换为

req = requests.get(url + urllib.parse.urlencode(sku), 
                   headers=self.headers)

payload = {"sku": "ps-22-1", "sku2": "ps-22-7-2", "sku3": "ps-22-7-3"}
req = requests.get('url', params=payload, headers=self.headers)
sczxawaw

sczxawaw2#

创建一个包含所有产品ID(sku)列表的字典,然后将其作为数据通过请求传递,如下所示:

def get_stocks(self, campaign_id, warehouse_id, sku):
    """ Method for parse stocks
    Parameters:
        campaign_id (int):  client_id in Store
        warehouse_id (int): warehouse_id in Warehouse
        sku (str): product sku in Product
    Returns:
        data (json): JSON with stocks data """
    
    url = f"{self.url}campaigns/{campaign_id}/warehouses/{warehouse_id}/stocks/actual.json?"
    
    data = {"sku_ids":["ps-22-1","ps-22-7-2","ps-22-7-3"]}
    
    req = requests.get(url + urllib.parse.urlencode(sku), 
                            headers=self.headers,
                            data=data)
    
    if req.status_code == 200:
        return True, '200', req.json()
    return False, req.json()["error"]["message"]

在下面的例子中,我使用的是SqlAlchemy ORM,你可以根据自己的ORM来修改你的API。

data = request.data()
session().query(Product).filter(Product.sku.in_(data['sku_ids'])).all()
5hcedyr0

5hcedyr03#

我解决了这个问题。困难在于需要从数据库中取出sku并动态替换。我从数据库中取出每个sku及其值,形成一个dict列表并将其传递给get_stocks方法。因此,这是可行的:

def get_stocks(self, campaign_id, warehouse_id, sku):
    url = f"{self.url}campaigns/{campaign_id}/warehouses/{warehouse_id}/stocks/actual.json?"
    sku_list = []
    for e in sku:
        parsed_sku = urllib.parse.urlencode(e)
        sku_list.append(parsed_sku)
    s = '&'.join(sku_list)
    try:
        req = requests.get(url + s, 
                            headers=self.headers)
        if req.status_code != 200:
            logger.warning(f"Yandex API returned "
                           f"{req.status_code}")
            return []
        return req.json()
    except (Timeout, HTTPError, Exception) as e:
        logger.warning(f"{e}, {e.__class__}")

相关问题