Created
October 23, 2017 17:51
-
-
Save josefdlange/dff288bb12f3d5a03152e435fc5e22a2 to your computer and use it in GitHub Desktop.
Hashid-enabled PrimaryKeyField for Peewee ORM
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from peewee import PrimaryKeyField | |
| from hashids import Hashids | |
| class HashidPrimaryKeyField(PrimaryKeyField): | |
| hashid = Hashids(min_length=16) | |
| @property | |
| def prefix(self): | |
| return self.model_class.__name__.lower() + '_' | |
| def db_value(self, value): | |
| try: | |
| return self.hashid.decode(value.replace(self.prefix, '')) | |
| except Exception as e: | |
| print(e) | |
| return super().db_value(value) | |
| def python_value(self, value): | |
| hashed = self.hashid.encode(value) | |
| return self.prefix + hashed | |
| class User(BaseModel): | |
| id = HashidPrimaryKeyField() | |
| first_name = TextField(null=False) | |
| last_name = TextField(null=False) | |
| email = TextField(null=False, index=True) | |
| password = TextField(null=False) | |
| class Meta: | |
| database = SOME_DATABASE | |
| u = User.create(first_name="Foo", last_name="Bar", email="foo@bar.com", password="some salt/hashed password") | |
| print(u.id) # Prints: '1' | |
| u2 = User.get(User.id == u.id) | |
| print(u.id) # Prints the nicely-formatted hashid: "user_4q2VolejRejNmGQB" | |
| assert(u == u2) # Fails. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment