Skip to content

Instantly share code, notes, and snippets.

@kezabelle
Created July 31, 2014 07:56
Show Gist options
  • Save kezabelle/f260577237d4e8e0ce55 to your computer and use it in GitHub Desktop.
Save kezabelle/f260577237d4e8e0ce55 to your computer and use it in GitHub Desktop.
for basichash (heh) on #django IRC
from hashids import Hashids
class Property(...):
""" to get the hash in a template {{ myobj.urlsafe_id }} """
""" to get the URL in a template, {{ myobj.get_absolute_url }} """
# I've shoved this here because why not, but you could put it in module
# scope for the whole set of models, or in utils for whole package access.
hashid_generator = Hashids(...)
def urlsafe_id(self):
return self.hashid_generator.encrypt(self.pk)
# Aliased, just like `id` = `pk`
urlsafe_pk = urlsafe_id
def get_absolute_url(self):
return reverse('myapp:myview', kwargs={'hash': self.urlsafe_id()})
urlpatterns = (
url('path/(?P<hash>[a-zA-Z0-9]+)/...', View.as_view(), 'myview')
)
class MyView(...):
def get_object(self, *args, **kwargs):
"""
for simplicity's sake, I haven't made reference to the parent
get_object at all, but the key here is to decrypt the kwarg and if it
returns something that isn't (), try it against a get_object implementation
"""
decrypted = Property.hashid_generator.decrypt(self.kwargs.get('hash'))
if decrypted:
try:
Property.objects.get(pk=decrypted)
except Property.DoesNotExist:
raise Http404('Invalid Property after hash was decrypted')
raise Http404('Invalid hash')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment