|
| 1 | +from flask import current_app, Flask |
| 2 | +from hashids import Hashids as _Hashids |
| 3 | +from typing import Any, Dict |
| 4 | +from werkzeug.routing import BaseConverter |
| 5 | + |
| 6 | + |
| 7 | +class HashidMixin: |
| 8 | + ''' |
| 9 | + Hashid mixin meant for use with SQLAlchemy models. |
| 10 | + Adds a property to the model which returns a hashid based on the model id. |
| 11 | +
|
| 12 | + This won't add a column to the model, the hashid is computed on runtime. |
| 13 | +
|
| 14 | + Note: The extended class must have an attribute 'id' of type int! |
| 15 | + ''' |
| 16 | + @property |
| 17 | + def hashid(self): |
| 18 | + return current_app.extensions['hashids'].encode(self.id) |
| 19 | + |
| 20 | + |
| 21 | +class HashidConverter(BaseConverter): |
| 22 | + ''' |
| 23 | + Hashid Converter. |
| 24 | +
|
| 25 | + Converts given hashids from routes to integers. |
| 26 | + Example: @bq.route('/users/<hashid:user_id') |
| 27 | +
|
| 28 | + Converts integers to hashids when generating urls. |
| 29 | + Example: url_for('users.user', user_id=user.id) |
| 30 | + ''' |
| 31 | + |
| 32 | + def to_python(self, value: str) -> int: |
| 33 | + return current_app.extensions['hashids'].decode(value) |
| 34 | + |
| 35 | + def to_url(self, value: int) -> str: |
| 36 | + return current_app.extensions['hashids'].encode(value) |
| 37 | + |
| 38 | + |
| 39 | +class Hashids: |
| 40 | + ''' Wrapper class to easily integrate hashids in Flask ''' |
| 41 | + |
| 42 | + def __init__(self, app: Flask = None): |
| 43 | + self.app = app |
| 44 | + if app is not None: |
| 45 | + self.init_app(app) |
| 46 | + |
| 47 | + def init_app(self, app: Flask): |
| 48 | + ''' Setup Hashids, includes the integration of the HashidConverter. ''' |
| 49 | + hashids_config: Dict[str, Any] = {} |
| 50 | + if 'HASHIDS_ALPHABET' in app.config: |
| 51 | + hashids_config['alphabet'] = app.config['HASHIDS_ALPHABET'] |
| 52 | + if 'HASHIDS_MIN_LENGTH' in app.config: |
| 53 | + hashids_config['min_length'] = \ |
| 54 | + int(app.config['HASHIDS_MIN_LENGTH']) |
| 55 | + if 'SECRET_KEY' in app.config: |
| 56 | + hashids_config['salt'] = app.config['SECRET_KEY'] |
| 57 | + self._hashids = _Hashids(**hashids_config) |
| 58 | + if not hasattr(app, 'extensions'): |
| 59 | + app.extensions = {} |
| 60 | + app.extensions['hashids'] = self |
| 61 | + app.url_map.converters['hashid'] = HashidConverter |
| 62 | + |
| 63 | + def decode(self, value: str) -> int: |
| 64 | + ''' Decode a hashid to an integer. ''' |
| 65 | + return self._hashids.decode(value)[0] |
| 66 | + |
| 67 | + def encode(self, value: int) -> str: |
| 68 | + ''' Encode an integer to a hashid. ''' |
| 69 | + return self._hashids.encode(value) |
0 commit comments