Skip to content

Commit 78f2949

Browse files
author
Patrick Jentsch
committed
Initial commit
0 parents  commit 78f2949

File tree

5 files changed

+187
-0
lines changed

5 files changed

+187
-0
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
build
2+
dist
3+
*.egg-info

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2021 Patrick Jentsch
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
# Flask-Hashids
2+
3+
Hashids integration for Flask applications, it is based on the [Hashid](https://github.com/davidaurelio/hashids-python) package available on [PyPi](https://pypi.org/project/hashids/). With this extension you can conveniently use integer ids for your application logic or database tables and hash them before exposing it in URLs or JSON data.
4+
5+
## Installation
6+
7+
The latest stable version [is available on PyPI](https://pypi.org/project/Flask-Hashids/). Either add `Flask-Hashids` to your `requirements.txt` file or install with pip:
8+
9+
```
10+
pip install Flask-Hashids
11+
```
12+
13+
## Configuration
14+
15+
Flask-Hashids is configured through the standard Flask config API. These are the available options:
16+
17+
- **HASHIDS_ALPHABET**: Read more about that in [Hashids documentation](https://github.com/davidaurelio/hashids-python#using-a-custom-alphabet)
18+
- **HASHIDS_MIN_LENGTH**: Read more about that in [Hashids documentation](https://github.com/davidaurelio/hashids-python#controlling-hash-length)
19+
- **SECRET_KEY**: Used as the salt, read more in [Hashids documentation](https://github.com/davidaurelio/hashids-python#using-a-custom-salt)
20+
21+
## Examples
22+
23+
```python
24+
from flask import abort, Flask, render_template, url_for
25+
from flask_hashids import HashidMixin, Hashids
26+
from flask_sqlalchemy import SQLAlchemy
27+
28+
29+
app = Flask(__name__)
30+
# The SECRET_KEY is used as a salt, so don't forget to set this in production
31+
app.config['SECRET_KEY'] = 'secret!'
32+
db = SQLAlchemy(app)
33+
hashids = Hashids(app)
34+
35+
36+
class User(HashidMixin, db.Model):
37+
__tablename__ = 'users'
38+
39+
id = db.Column(db.Integer, primary_key=True)
40+
name = db.Column(db.String(64), nullable=False)
41+
42+
43+
@app.route('/users')
44+
def users():
45+
hashid_users = [
46+
{
47+
'id': user.hashid, # hashid property from HashidMixin
48+
'name': user.name,
49+
'url': url_for('user', user_id=user.id) # Int id for url generation
50+
} for user in User.query.all()
51+
]
52+
return render_template('users.html', users=hashid_users)
53+
54+
55+
@app.route('/users/<hashid:user_id>')
56+
def user(user_id):
57+
# The HashidConverter decodes the given hashid to an int
58+
user = User.query.get_or_404(user_id):
59+
return render_template('user.html', user=user)
60+
61+
62+
if __name__ == '__main__':
63+
app.run()
64+
```
65+
66+
67+
## Ressources
68+
69+
- https://hashids.org/python/

flask_hashids.py

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
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)

setup.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
from setuptools import setup
2+
3+
4+
with open('README.md', 'r') as fh:
5+
long_description = fh.read()
6+
7+
8+
setup(
9+
name='Flask-Hashids',
10+
version='0.2.0',
11+
url='https://github.com/Pevtrick/Flask-Hashids',
12+
author='Patrick Jentsch',
13+
author_email='[email protected]',
14+
description='Hashids integration for Flask applications.',
15+
long_description=long_description,
16+
long_description_content_type='text/markdown',
17+
py_modules=['flask_hashids'],
18+
install_requires=['Flask', 'Hashids >= 1.0.2'],
19+
classifiers=[
20+
'Programming Language :: Python :: 3',
21+
'License :: OSI Approved :: MIT License',
22+
'Operating System :: OS Independent',
23+
],
24+
python_requires='>=3.5',
25+
)

0 commit comments

Comments
 (0)