【问题标题】:pass query param as dictionary with many values in postman将查询参数作为字典传递,在邮递员中有许多值
【发布时间】:2019-07-02 15:48:16
【问题描述】:

我正在使用 postman 访问我的 API。我有一个关于通过邮递员params 发送查询参数的问题。在我的 API 中,我使用 services = request.GET.get('services') 获取参数,然后返回服务响应。

我的问题是,如果有多个服务,如“A”、“B”、“C”,那么我们如何使用邮递员在参数中发送这些服务?

views.py

class SomeAPIView(ModelViewSet):
    def get_queryset(self):
        services = self.request.GET.get('services')
        print(services)            # getting  services
        print(type(services))      #type is string
        response_list = []
        for service in services:
            result = API(service=service)
            response_list.append(result)
        return response_list

我想要获取服务列表,然后遍历该列表以返回对该服务的响应。

【问题讨论】:

  • 你能添加你的代码你做了什么
  • 嗨,我已经添加了我的代码示例。

标签: django python-3.x postman


【解决方案1】:

这取决于您将如何在生产中使用此 API 条目。

首先,django中的好方法是使用request.query_params获取查询参数。此外,您必须为 get() 方法提供默认值,以避免在没有传递“服务”参数时出现异常。

然后,如果您的服务参数包含某些对象的名称或 ID,您可以在 GET 请求中将其与参数一起传递为 http://someurl?services=A,B,C,或在选项卡中,在邮递员中命名为“Params”。所以request.query_params.get('sevices', '') 将返回字符串,包含'A,B,C'。现在你可以用','来分割它,比如services_names = str.split(',')

无论如何,GET 请求的参数可能只返回str 值。

根据您的示例,它可能看起来像:

class SomeAPIView(ModelViewSet):
    def get_queryset(self):
        services = self.request.query_params.get('sevices', '').split(',')
        print(services)            # getting  services
        print(type(services))      # now it will be List[str]
        response_list = []
        for service in services:
            result = API(service=service)
            response_list.append(result)
        return response_list

【讨论】:

    猜你喜欢
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 2021-09-27
    • 2023-03-26
    • 1970-01-01
    • 2021-12-14
    • 2019-11-18
    相关资源
    最近更新 更多