python - Proper way to consume data from RESTFUL API in django -


i'm trying learn django while have current solution i'm not sure if follows best practices in django. display information web api on website. let's api url follows:

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

thsis return list of books edwards written in year 2009. returned in following format:

{'results':              [                 {                    'title':'book 1',                    'author':'edwards man',                    'year':2009                 },                 {                    'title':'book 2',                    'author':'edwards man',                    'year':2009}            ] } 

currently consuming api in views file 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) 

normally, grab data database in models.py file, unsure if should grabbing api data in models.py or views.py. if should in models.py, can provide example of how this? wrote above example sepecifically stackoverflow, bugs purely result of writing here.

i approach of putting kind of logic in separate service layer (services.py); data rendering quite not "model" in django orm sense, , it's more simple "view" logic. clean encapsulation ensures can things control interface backing service (i.e., make python api vs. url parameters), add enhancements such caching, @sobolevn mentioned, test api in isolation, etc.

so i'd suggest simple services.py, looks this:

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

note how parameters passed (using capability of 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:


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -