Using template tags in django to display a small bit of data for every view
I have an app I created that gets my latest github commits. Other than the model that was created to cache the info, I'm doing a lot of work inside of a simple_tag but I am unsure of the best way to avoid doing this. The reason I made this into a tag is that I want to display this data as part of the main layout of my overall project and so this code should be run for every view th开发者_如何学Pythonat is called that extends my main layout.
Basically, my simple_tag is supposed to provide the last commit information. It calls a function that checks the last timestamp in a db and if it's over 1 hour old, it uses urllib2 to hit the github commit API to get the last commit and in turn store that data in the db and then print the fresh commit info. So, it basically looks a little something like this, minus some boilerplate code to actually get the json from github and such:
@register.simple_tag
def latest_commit(project_name):
commit = get_latest_commit(project_name)
return 'Latest commit message: %s' % commit.message
def get_latest_commit(project_name):
commit = models.Commit.objects.get(pk=project_name)
# ...
if not commit or now - commit.updated_at >= one_hour
# use urllib2 to get github json string
# ...
# use simple json to parse string
# ...
commit = Commit.objects.create(message=json['mesage'])
commit.save()
return commit
I feel like this logic should go into another place... it feels a little dirty to me and there is a potential for XSS, but I'm new to Django and I'm unsure of the best way to do this...
I'm doing a lot of work inside of a simple_tag but I am unsure of the best way to avoid doing this.
Two Words: View Functions.
A view function should provide the last commit information. The view function should call a function that checks the last timestamp in a db and if it's over 1 hour old, it uses urllib2 to hit the github commit API to get the last commit and in turn store that data in the db and then ...
provide all the data, including the fresh commit info, to the page template for rending.
That's what a view function should do. The template renders the information provided by the view function.
精彩评论