Where to place the call to a external API that has a dependency on a Model?
Suppose I have a Django app named "blog".
There's a model called Post
and I have an external API call that returns the list of the most popular posts in a given time, e.g., the Google Analytics API.
My question is: Where is the expected place that I should place the code that makes the call to the external API, parses the id from each post, query the database and sort the list of models accordingly?
I don't think that it should live in the Manager
or in a t开发者_运维百科emplatetag
. Any tips or suggestions?
Thanks in advance!
EDIT: The desired result might be need in several places across the project, so if I place the code in view, I'll have duplication.
It should be done in a view, or better, if your view code is getting cluttered, put it in a helper module.
import util
def view(request):
util.process_post_rankings(request.user.id)
# ... write additional logic and render to template
However, be cautious with relying on external apis to render a page to your user. Things might go wrong, take an awful lot of time, API might not respond etc... Better to do that asynchronously with Javascript, and update the page when data is ready.
This sounds like it should be done in a View, because then you will be returning to a template with all the required context.
精彩评论