的数据的正确方法

的数据的正确方法

本文介绍了在 Django 中使用来自 RESTFUL API 的数据的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习 django,所以虽然我有一个当前的解决方案,但我不确定它是否遵循 django 中的最佳实践.我想在我的网站上显示来自 web api 的信息.假设api url如下:

I'm trying to learn django so while I have a current solution I'm not sure if it follows best practices in django. I would like to display information from a web api on my website. Let's say the api url is as follows:

http://api.example.com/books?author=edwards&year=2009

这将返回爱德华兹在 2009 年写的书籍列表.返回格式如下:

Thsis would return a list of books by Edwards written in the year 2009. Returned in the following format:

{'results':
             [
                {
                   'title':'Book 1',
                   'Author':'Edwards Man',
                   'Year':2009
                },
                {
                   'title':'Book 2',
                   'Author':'Edwards Man',
                   'Year':2009}
           ]
}

目前我在我的视图文件中使用 API 如下:

Currently I am consuming the API in my views file as follows:

class BooksPage(generic.TemplateView):
    def get(self,request):
        r = requests.get('http://api.example.com/books?author=edwards&year=2009')
        books = r.json()
        books_list = {'books':books['results']}
        return render(request,'books.html',books_list)

通常,我们从models.py 文件中的数据库中获取数据,但我不确定是否应该在models.py 或views.py 中获取此API 数据.如果它应该在models.py中,有人可以提供一个如何做到这一点的例子吗?上面的例子是我专门为stackoverflow写的,所以任何bug都纯粹是写在这里的结果.

Normally, we grab data from the database in the models.py file, but I am unsure if I should be grabbing this API data in models.py or views.py. If it should be in models.py, can someone provide an example of how to do this? I wrote the above example sepecifically for stackoverflow, so any bugs are purely a result of writing it here.

推荐答案

我喜欢将这种逻辑放在单独的服务层 (services.py) 中的方法;您渲染的数据在 Django ORM 意义上并不是模型",它不仅仅是简单的视图"逻辑.干净的封装确保您可以执行诸如控制后备服务的接口(即,使其看起来像 Python API 与带有参数的 URL)、添加增强功能(如@sobolevn 提到的缓存)、单独测试 API、等

I like the approach of putting that kind of logic in a separate service layer (services.py); the data you are rendering is quite not a "model" in the Django ORM sense, and it's more than simple "view" logic. A clean encapsulation ensures you can do things like control the interface to the backing service (i.e., make it look like a Python API vs. URL with parameters), add enhancements such as caching, as @sobolevn mentioned, test the API in isolation, etc.

所以我建议使用一个简单的 services.py,它看起来像这样:

So I'd suggest a simple services.py, that looks something like this:

def get_books(year, author):
    url = 'http://api.example.com/books'
    params = {'year': year, 'author': author}
    r = requests.get(url, params=params)
    books = r.json()
    books_list = {'books':books['results']}
    return books_list

注意参数是如何传递的(使用 requests 包的功能).

Note how the parameters get passed (using a capability of the requests package).

然后在 views.py 中:

import services
class BooksPage(generic.TemplateView):
    def get(self,request):
        books_list = services.get_books('2009', 'edwards')
        return render(request,'books.html',books_list)

另见:

这篇关于在 Django 中使用来自 RESTFUL API 的数据的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!