Giter VIP home page Giter VIP logo

flask-hashids's Introduction

Flask-Hashids

Hashids integration for Flask applications, it is based on the Hashid package available on PyPi. 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.

Installation

The latest stable version is available on PyPI. Either add Flask-Hashids to your requirements.txt file or install with pip:

pip install Flask-Hashids

Configuration

Flask-Hashids is configured through the standard Flask config API. These are the available options:

Examples

You can find more detailed examples on how to use Flask-Hashids in the examples directory.

from flask import Flask, jsonify, url_for
from flask_hashids import HashidMixin, Hashids
from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)
app.config['SECRET_KEY'] = 'top_secret_key'
app.config['HASHIDS_SALT'] = 'secret!'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
db = SQLAlchemy(app)
hashids = Hashids(app)


# The HashidMixin class adds the hashid property which will compute a hashid
# based on the existing id attribute of the instance.
# NOTE: The id attribute must be an int
class User(HashidMixin, db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), nullable=False)

    @property
    def url(self):
        # The HashidConverter encodes the given id to a hashid in the URL
        return url_for('user', user_id=self.id)

    def to_json_serializeable(self):
        return {'id': self.hashid, 'name': self.name, 'url': self.url}


@app.before_first_request
def database_setup():
    db.create_all()
    john = User(name='John')
    db.session.add(john)
    jane = User(name='Jane')
    db.session.add(jane)
    db.session.commit()


@app.route('/users')
def users():
    return [user.to_json_serializeable() for user in User.query.all()], 200


@app.route('/users/<hashid:user_id>')
def user(user_id: int):
    # The HashidConverter decodes the given hashid to an int
    user = User.query.get(user_id)
    if user is None:
        return jsonify('User not found'), 404
    return user.to_json_serializeable(), 200


def main():
    # You can encode and decode hashids manually
    id = 123
    encoded_id = hashids.encode(id)
    decoded_id = hashids.decode(encoded_id)
    app.run()


if __name__ == '__main__':
    main()

Resources

flask-hashids's People

Contributors

pevtrick avatar ollemento avatar norepercussions avatar

Stargazers

Filip Mularczyk avatar  avatar  avatar

Watchers

James Cloos avatar  avatar  avatar

flask-hashids's Issues

Primary key naming in DB models

Hi @Pevtrick,

First, I want to thank you for this extension and awesomeness. This extension is a huge life saver.

I have a request from you though. Can you please let the attribute name of the ID be either id or pk?

According to the following note

NOTE: The extended class must have an attribute named after the value of
__id_attribute__ (str) and must be of type int!
'''

And the statically assigned __id_attibute__

__id_attribute__: str = 'id'

If the primary key column is any other name than id, you get an error:

class MyModel(HashidMixin, db.Model):
    __tablename__ = "my_model"
    pk = db.Column(db.Integer, primary_key=True)
    ...
AttributeError: 'MyModel' object has no attribute 'id'

You might be wondering why am I asking you for this change? Basically, because there is a VSCode extension called Sourcery (which I think is awesome too) recommends avoiding-builtin-shadow when using id as variable name.

I also think this gives more flexibility to the awesome extension.

Thank you

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.