努力通过Python了解Guardian API

时间:2014-07-09 22:32:54

标签: python json api

我在Windows Vista 64位上使用Python.org版本2.7 64位。我已经汇总了一些代码,这些代码是使用Guardian支持团队提供的API密钥的身份验证方法和由其网站的Content 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。我认为这段代码会将结果从他们网站的足球部分打印到Python IDLE。它运行没有错误,但它不产生输出。

有人可以告诉我我做错了什么和/或我是否完全误解了这段代码的意图?

由于

1 个答案:

答案 0 :(得分:2)

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

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

同时拥有return data before print data表示print data无法访问,因为当您return data时,您的功能结束。