Proper way to consume data from RESTFUL API in django

前端 未结 4 773
迷失自我
迷失自我 2020-11-30 17:55

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

4条回答
  •  悲哀的现实
    2020-11-30 18:46

    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.

    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).

    Then in 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)
    

    See also:

    • Separation of business logic and data access in django

提交回复
热议问题