Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hooks Outside PiccoloCrud #293

Open
Fidel-C opened this issue Aug 22, 2024 · 7 comments
Open

Hooks Outside PiccoloCrud #293

Fidel-C opened this issue Aug 22, 2024 · 7 comments

Comments

@Fidel-C
Copy link

Fidel-C commented Aug 22, 2024

Just wondering whether Hooks can be emplemented externally in any part of the app. Something like Django signals. So that wherever a record changes or is added in the database, even if the action was called from the admin panel, the Hook would still be triggered . I think this restriction to PiccoloCrud alone is very limiting. I wish there could be a Django-like approach to this.

@dantownsend
Copy link
Member

There isn't an official way of doing it at the moment - it's possible to override the save method on a table, but a bit tricky.

Having a proper API for it would be nice, as it's a much more common requirement than I expected.

@Fidel-C
Copy link
Author

Fidel-C commented Aug 22, 2024

Looking forward to that then.

@Fidel-C
Copy link
Author

Fidel-C commented Sep 26, 2024

A code example showing how to override the save method on a table will be good. I can't see how to that.

@dantownsend
Copy link
Member

It's something like this:

from piccolo.utils.sync import run_sync

def save(self, columns=None):
    save_ = super().save

    class Save:
        async def run(self, *args, **kwargs):
            # Add custom logic here

            await save_(columns=columns).run(*args, **kwargs)

        def run_sync(self, *args, **kwargs):
            return run_sync(self.run(*args, **kwargs))

        def __await__(self):
            return self.run().__await__()

    return Save()

The reason it looks a bit complicated is because Piccolo lets you run a query as sync or async.

@Fidel-C
Copy link
Author

Fidel-C commented Sep 27, 2024

Thanks a lot. I observed that the run method is called when adding records. But doesn't seem to be called when updating existing records.
Quite complicated, just like you said.

@sinisaos
Copy link
Member

@Fidel-C You can also try something like this. It is based on the @dantownsend code with minor modifications to use (override) also save (both save and update) and remove methods.

@Fidel-C
Copy link
Author

Fidel-C commented Sep 28, 2024

@sinisaos Thanks a lot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants