Creating short tinyurls for Django model objects while maintaining clean code
I'm using this code https://github.com/kylebragger/tiny/blob/master/tiny.py to transform integer primary keys into shortened URLs.
For example, instead of using the url /articles/1000/title-of-article for article id 1000, the url might be transformed to /articles/a1b2c3/title-of-article.
The problem with doing this is that my models and views is littered with calls to the functions that shorten and unshorten these primary keys. They occurs in each view that uses the primary key, as well as methods in the model that return permalinks such as get_absolute_url().
This seems like unnecessary repetition. I was wondering if there's a more elegant way to do this without having these function calls all over the place -- perhaps by modifying the URL dispatcher and its reverse function, to automatically call a specified callback function when it encounters spe开发者_运维问答cified URL parameters when generating or parsing URLs, and having that callback perform the transformation.
If you store the shortened url in the database as a slug field of sorts then you can use it like any other slug field and filter on it directly, without having to convert it.
Alternatively: You may consider writing a custom manager for any model that uses this technique, that allows you to search the table for records by giving it a shortened url. Soemthing like:
MyModel.objects.get_by_short_url('myshorturl')
which could be implemented as:
class MyManager(models.Manager):
...
def get_by_short_url(self, s):
return self.get(from_tiny(s))
This combined with your existing idea to use the model's get_absolute_url method means the shortening algorithm should be completely abstracted away. This leaves it no different from using any real field to identify model instances like the primary key itself or (preferably) a dedicated slug field.
精彩评论