【问题标题】:How do I dynamically change a parameter in a Python API call如何动态更改 Python API 调用中的参数
【发布时间】:2019-09-02 02:49:19
【问题描述】:

我正在尝试在 Python 的 API 调用中动态更改页面参数,以便可以访问 Vimeo 上文件的所有 JSON 数据。我不明白的是如何动态更改参数而不是硬编码数字。正如您在下面的代码中看到的,“页面”为 3,但我不明白如何插入参数,因此我可以遍历页面并获取每个页面的 JSON 数据。感谢您的帮助。

uri = 'https://api.vimeo.com/me/videos'
# Asking the JSON to only get the two fields we are interested in
response = v.get(uri, params={'fields': 'name, uri', 'page': 3, 'per_page': 100})

这是 API 返回的一部分。

{
  'total': 3278,
  'page': 1,
  'per_page': 100,
  'paging': {
    'next': '/me/videos?fields=name%2C%20uri&per_page=100&page=2',
    'previous': None,
    'first': '/me/videos?fields=name%2C%20uri&per_page=100&page=1',
    'last': '/me/videos?fields=name%2C%20uri&per_page=100&page=33'
  },
  'data': [
    {
      'uri': '/videos/356967749',
      'name': 'Connecting Smallholder Farmers to Science'
    },
    {
      'uri': '/videos/356880620',
      'name': 'pro_test_upload'
    },
    {
      'uri': '/videos/356880402',
      'name': 'Amazing Apollo Stories with Charles Fishman'
    },
    {
      'uri': '/videos/356728892',
      'name': 'tot_190829'
    },
    {
      'uri': '/videos/356481229',
      'name': 'com_acw_johnson.mov'
    },
    ...
}

【问题讨论】:

    标签: json python-3.x vimeo-api


    【解决方案1】:

    使用第一页获取结果总数,然后使用该值进行分页:

    import math
    uri = 'https://api.vimeo.com/me/videos'
    first_page = requests.get(
        uri, 
        params={
            'fields': 'name, uri', 
            'page': 1, 
            'per_page': 100}).json()
    total_pages = math.ceil(first_page["total"] / first_page["per_page"])
    for page in total_pages:
        response = requests.get(
            uri, 
            params={
                'fields': 'name, uri', 
                'page': page, 
                'per_page': 100})
        # do things
    

    【讨论】:

    • 感谢您的快速回复。我会试试这个。我很感激。
    • 对此还有一个问题。如果我的代码行超过 79 个字符并且涉及类似于下面的行,那么分隔这些行的最佳方法是什么?我用谷歌搜索了这个,但没有发现任何一致的东西。谢谢你。 first_page = requests.get(uri, params={'fields': 'name, uri', 'page': 1, 'per_page': 100}).json()
    • @user3324136 这是个人喜好问题,没有“最佳方式”,但推荐的方法可以在PEP-8中找到。我更新了我的答案以演示 I 通常如何格式化它。请注意,80 个字符也不是硬性规定;它本身就是 PEP-8 建议。
    猜你喜欢
    • 1970-01-01
    • 2022-01-19
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    相关资源
    最近更新 更多