在Django中使用来自RESTFUL API的数据的正确方法 [英] Proper way to consume data from RESTFUL API in django
问题描述
我正在尝试学习django,因此当我有最新的解决方案时,我不确定它是否遵循django中的最佳做法。我想在我的网站上显示来自Web api的信息。假设api网址如下:
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
Thsis将返回Edwards在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专门编写了上面的示例,因此任何错误都完全是在此处编写的结果。
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
请注意参数通过(使用请求
程序包的功能)。
Note how the parameters get passed (using a capability of the requests
package).
然后在视图中。 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)
另请参见:
- Separation of business logic and data access in django
这篇关于在Django中使用来自RESTFUL API的数据的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!