【问题标题】:How to fetch only parts of json file in python3 requests module如何在python3请求模块中仅获取部分json文件
【发布时间】:2021-04-12 07:34:06
【问题描述】:

所以,我正在用 Python 编写一个程序,使用 requests 模块从谷歌课堂 API 获取数据。我从课堂上得到了完整的 json 响应,如下所示:

{'announcements': [{'courseId': '#############', 'id': '###########', 'text': 'This is a test','state': 'PUBLISHED', 'alternateLink': 'https://classroom.google.com/c/##########/p/###########', 'creationTime': '2021-04-11T10:25:54.135Z', 'updateTime': '2021-04-11T10:25:53.029Z', 'creatorUserId': '###############'}, {'courseId': '############', 'id': '#############', 'text': 'Hello everyone', 'state': 'PUBLISHED', 'alternateLink': 'https://classroom.google.com/c/#############/p/##################', 'creationTime': '2021-04-11T10:24:30.952Z', 'updateTime': '2021-04-11T10:24:48.880Z', 'creatorUserId': '##############'}, {'courseId': '##################', 'id': '############', 'text': 'Hello everyone', 'state': 'PUBLISHED', 'alternateLink': 'https://classroom.google.com/c/##############/p/################', 'creationTime': '2021-04-11T10:23:42.977Z', 'updateTime': '2021-04-11T10:23:42.920Z', 'creatorUserId': '##############'}]}

我实际上无法将它转换成漂亮的格式,所以我只是在从 http 请求中获取它时粘贴它。我真正想要做的只是从服务中请求前几个公告(比如 1、2、3 取决于要求),而我得到的是所有公告(如示例 3 公告)已经自从教室创建以来就制作了。现在,我相信获取所有公告可能会使程序变慢,所以我希望我只能获得所需的公告。有没有办法通过传递一些参数或任何东西来做到这一点?谷歌教室提供了一些直接功能,但是我稍后遇到了这些功能,并且已经使用请求模块编写了所有内容,这需要更改很多我想避免的事情。但是,如果不可避免,我也会走那条路。

【问题讨论】:

    标签: python-3.x python-requests google-classroom


    【解决方案1】:

    答案:

    使用pageSize 字段来限制您希望在announcements: list 请求中的响应数量,其中orderBy 参数为updateTime asc

    更多信息:

    根据documentation

    orderBy:string

    结果的可选排序。带有可选排序方向关键字的以逗号分隔的字段列表。支持的字段是updateTime。支持的方向关键字为ascdesc。如果未指定,updateTime desc 是默认行为。示例:updateTime ascupdateTime

    和:

    pageSize:integer

    要返回的最大项目数。零或未指定表示服务器可以分配最大值。

    所以,假设您想要一门课程的前 3 个公告,您将使用 3 中的 pageSizeupdateTime asc 中的 orderBy

    # Copyright 2021 Google LLC.
    # SPDX-License-Identifier: Apache-2.0
    
    service = build('classroom', 'v1', credentials=creds)
    
    asc = "updateTime asc"
    pageSize = 3
    
    # Call the Classroom API
    results = service.courses().announcements().list(pageSize=3, orderBy=asc ).execute()
    

    或 HTTP 请求示例:

    GET https://classroom.googleapis.com/v1/courses/[COURSE_ID]/announcements
          ?orderBy=updateTime%20asc
          &pageSize=2
          &key=[YOUR_API_KEY] HTTP/1.1
    
    Authorization: Bearer [YOUR_ACCESS_TOKEN]
    Accept: application/json
    

    参考资料:

    【讨论】:

    • 这给了我这个想法,但没有给我直接的解决方案,但是谢谢。我想要的是使用 requests 库来发送一个 GET 请求,而不是使用 Google 提供的函数,比如 build。你说 pageSize 和 orderBy 作为字段给了我尝试将它们作为参数的想法并且它起作用了。所以再次感谢!!干杯。
    猜你喜欢
    • 2018-05-15
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多