纽约时报头条故事api的python包装器
nytimes-top-stories的Python项目详细描述
nytimes-top-stories是纽约时报顶部的一个简单的python包装器 故事API。
与Python2.7和3+兼容。
依赖关系
nytimes-top-stories需要requests包。
安装
PIP
pip install nytimes-top-stories
克隆库
- git clone git@github.com:kashiish/nytimes-top-stories.git
- cd进入nytimes-top-stories目录
- python setup.py install
用法
在注册TopStories API密钥 https://developer.nytimes.com/signup。
fromtopstoriesimportTopStoriesAPIapi=TopStoriesAPI(<SECRET_API_KEY>)
get_stories方法接受一个必需参数和两个可选参数 论据。签出API documentation以查看 从API返回。
defget_stories(self,section,format_type="json",return_json_string=False):""" Gets a list of current top articles and associated images in the specified section and in the specified format. params: section: (string) the section the articles appears in format: (string) json or jsonp, default is json return_json_string: (boolean) if True, return value will be JSON string instead of a python list, default is False return: format_type=json: A list of articles (articles are python dicts) is returned. If return_json_string, string is returned. format_type=jsonp: API returns a callback function (string) in the format "{section}TopStoriesCallback({data})". {data} is an object, not an array, and it is not parsed/decoded. """
stories=api.get_stories("politics")# list of story dictsstories_string=api.get_stories("home",return_json_string=True)# json stringstories_jsonp=api.get_stories("work",format_type="jsonp")# (string) callback function with data input
此外,还有两种公共方法:
#returns a list of valid sections>>>api.get_sections_list()>>>["home","opinion","world","national","politics","upshot","nyregion","business","technology","science","health","sports","arts","books","theater","sundayreview","fashion","tmagazine","food","travel","magazine","realestate","automobiles","obituaries","insider"]
# writes a list of stories to a json file# input a path to file and list of storiesapi.write_to_json_file("example.json",stories)
测试
pytest和mock用于测试此包。
python setup.py pytest