python - 与外部 API 交互的基本电影数据库

标签 python django rest

在工作机会中我经常看到“REST-API”这个词。所以,我想了解 REST-API 到底是什么。我对 Django 有一些经验。嗯,其实我是一个初学者。

我在 GitHub 上发现了一个简单的任务:https://github.com/netguru/python-recruitment-task我唯一不明白的是如何做到这一点:

POST /movies:
    Request body should contain only movie title, and its presence should be validated.
    Based on passed title, other movie details should be fetched from http://www.omdbapi.com/ (or other similar, public movie database) - and saved to application database.
    Request response should include full movie object, along with all data fetched from external API.

它应该是什么样子?

如何验证“存在”?

如何从公共(public)数据库下载数据?

最佳答案

How should it looks like?

也许您将使用 Django 来完成此任务,但您应该通过以下内容了解这个概念,并且可能会适应:

import sys

import requests


API_KEY = '<API_KEY>'


def insert_to_db():
    raise NotImplementedError("Implement this function by yourself.")


if __name__ == "__main__":
    title = '+'.join([arg for arg in sys.argv[1:]])

    # Check if title is found in argument list. It's a validation.
    if not title:
        raise IndexError("No title entered!")

    # The request itself.
    response = requests.get(f"http://www.omdbapi.com/?t={title}&apikey={API_KEY}").json()
    if response:
        print(response)

这是一个简单的程序,它通过您使用的任何终端读取您的输入(电影标题),向您的 API 发出简单的请求(使用请求模块)并获取 JSON 格式的响应。这是它的输出:

$ python api.py city of god   
{'Title': 'City of God', 'Year': '2002', 'Rated': 'R', 'Released': '13 Feb 2004', 'Runtime': '130 min', 'Genre': 'Crime, Drama', 'Director': 'Fernando Meirelles, Kátia Lund(co-director)', 'Writer': 'Paulo Lins (novel), Bráulio Mantovani (screenplay)', 'Actors': 'Alexandre Rodrigues, Leandro Firmino, Phellipe Haagensen, Douglas Silva', 'Plot': "In the slums of Rio, two kids' paths diverge as one struggles to become a photographer and the other a kingpin.", 'Language': 'Portuguese', 'Country': 'Brazil, France, Germany', 'Awards': 'Nominated for 4 Oscars. Another 66 wins & 38 nominations.', 'Poster': 'https://m.media-amazon.com/images/M/MV5BMGU5OWEwZDItNmNkMC00NzZmLTk1YTctNzVhZTJjM2NlZTVmXkEyXkFqcGdeQXVyMTMxODk2OTU@._V1_SX300.jpg', 'Ratings': [{'Source': 'Internet Movie Database', 'Value': '8.6/10'}, {'Source': 'Rotten Tomatoes', 'Value': '91%'}, {'Source': 'Metacritic', 'Value': '79/100'}], 'Metascore': '79', 'imdbRating': '8.6', 'imdbVotes': '639,695', 'imdbID': 'tt0317248', 'Type': 'movie', 'DVD': '08 Jun 2004', 'BoxOffice': 'N/A', 'Production': 'Miramax Films', 'Website': 'http://www.miramax.com/movie/city-of-god', 'Response': 'True'}

How to validate the "presence"?

分析该程序应该可以消除您的疑虑。

    title = '+'.join([arg for arg in sys.argv[1:]])

    # Check if title is found in argument list. It's a validation.
    if not title:
        raise IndexError("No title entered!")

这部分代码检查标题是否已传递到您的请求。这称为验证,当您处理 API 时,在与其交互之前清理用户输入数据非常重要,否则,它可能会因意外行为而扰乱您的 API。

How to download data from public databases?

这是一个一般性问题,您可能需要进一步解释您要下载的内容。数据库各不相同,API 通过代表您执行查询来连接与数据库的通信。您可能需要详细说明这一点。

但是使用相关 API 下载 JSON 文件非常简单。如果您使用的是 Linux 并且对curl 有点熟悉,只需使用它发出请求并将其输出重定向到文件即可:

curl "http://www.omdbapi.com/?t=the+professional&apikey=<API_KEY>" >> out.json

通过这个示例,您可能会关联一个如何处理外部 API 的示例,然后就由您决定了。

关于python - 与外部 API 交互的基本电影数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56378013/

相关文章:

python - 将字典中的列表作为新列添加到 DataFrame

需要带有 Nodejs 示例的 RESTful MongoDB

C#如何处理从android上传到C#的多部分文件

django - 如何在models.py中的save方法中获取内联对象

rest - 如何使用 PUT 和 DELETE 进行 REST

python - 限制子类的外键选择

php - WhatsApp:如何解码 *.db.crypt 文件?

c++ - QTreeWidget : Windows Explorer-like editing

database - Django - 这些查询集会被缓存吗?

python - Django - 数据库数据未显示在应用程序中?