通过Python努力理解Guardian API

通过Python努力理解Guardian API,python,json,api,Python,Json,Api,我在Windows Vista 64位上使用Python.org 2.7 64位版本。我收集了一些代码,这些代码是使用卫报支持团队提供的API密钥的身份验证方法和他们网站的内容API代码生成器生成的一些Javascript的组合: import requests def get_content(): api_url = 'http://content.guardianapis.com/#/search?q=football' payload = { 'api-k

我在Windows Vista 64位上使用Python.org 2.7 64位版本。我收集了一些代码,这些代码是使用卫报支持团队提供的API密钥的身份验证方法和他们网站的内容API代码生成器生成的一些Javascript的组合:

import requests 
def get_content():
    api_url = 'http://content.guardianapis.com/#/search?q=football'
    payload = {
        'api-key':              '',
        'page-size':            10,
        'show-editors-picks':   'true',
        'show-elements':        'image',
        'show-fields':          'all'

    }
    response = requests.get(api_url, params=payload)
    data = response.json() # convert json to python-readable format
    return data
    print data


{
  "response": {
    "status": "ok",
    "userTier": "free",
    "total": 1,
    "results": [
      {
        "id": "football",
        "webTitle": "Football",
        "webUrl": "http://www.theguardian.com/football",
        "apiUrl": "http://content.guardianapis.com/football",
        "editions": [
          {
            "id": "football",
            "webTitle": "Football",
            "webUrl": "http://www.theguardian.com/football",
            "apiUrl": "http://content.guardianapis.com/football",
            "code": "default"
          }
        ]
      }
    ]
  }
}
我对Python相当陌生,对Javascript知之甚少。我认为这段代码可以将结果从他们网站的football部分打印到pythonidle。它运行时不会出错,但不会产生任何输出

有人能告诉我我做错了什么和/或我完全误解了这段代码的意图吗


谢谢

您必须调用函数才能获得输出:

get_content() # you need to call the function


import requests
def get_content():
    api_url = 'http://content.guardianapis.com/#/search?q=football'
    payload = {
        'api-key':              'xxxxxxxxxxx',
        'page-size':            10,
        'show-editors-picks':   'true',
        'show-elements':        'image',
        'show-fields':          'all'

    }
    response = requests.get(api_url, params=payload)
    data = response.json() # convert json to python-readable format
    print  data  # put print first
    return data
get_content() # call function

在打印数据之前有
返回数据
意味着
打印数据
是不可访问的,因为当您
返回数据
时,您的函数将结束

我认为“返回数据”需要在“打印数据”之后执行@imcg hi感谢您的回复。我试过两种方法。不幸的是,两者都不起作用……你是如何在空闲状态下运行/调用它的?@PadraicCunningham F5-RunModule@user3045351,我的答案中的代码应该使用f5运行模块运行。我使用了确切的语法,并得到了一个关于api密钥无效的错误!我不知道为什么昨天我在google groups上给卫报发了信息,他们对我说他们已经确认了密钥是有效的(请你修改你的答案并帮我删除它好吗?我把它包含在错误中了-谢谢)…我从我的web浏览器复制并粘贴了API密钥…你认为我需要手动复制吗?我实际上认为是你伪造了密钥,因为有一个错误,我想复制应该可以,但值得一试。另外,我建议使用
ipython
,您可以复制代码,然后在ipython中键入
paste
,然后使用
my_func()
运行。ipythonok中有很多非常酷的特性,我们来看看。至于api密钥,我在google groups上再次向他们发送消息,并将在一分钟内向他们发送另一条推特。在我最初的问题中,在print和return语句下面,这些代码打算做什么?如果您是初学者,那么内容代码生成器不容易理解。谢谢你是指问题底部的json吗?是的,那一点。他们提供了这个内容代码生成器:“当您在中添加过滤器元素时,显然可以看到代码更改,但我不确定使用此代码的上下文……就像它实际在做什么一样?”?