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

Class-based directives #603

Merged
merged 1 commit into from
Jan 4, 2018
Merged

Conversation

gtxm
Copy link

@gtxm gtxm commented Dec 25, 2017

Hey, it's my first contribution here, so let me say: awesome project, I love it, thank all of you for it!

I used hug for my project and I found a problem how to include a database connection (in my case sqlalchemy session) to the project. While searching for the solution I found some issues that also mention this problem: #376 and #458.

In the PR I included my solution to the problem - a class-based directive with a method for a cleanup when something goes wrong. In examples I included two use cases: sqlalchemy and mail sending. I will be happy to include more.

@hug.directive()
class SMTP(object):

    def __init__(self, *args, **kwargs):
        self.smtp = envelopes.SMTP(host='127.0.0.1')
        self.envelopes_to_send = list()

    def send_envelope(self, envelope):
        self.envelopes_to_send.append(envelope)

    def cleanup(self, exception=None):
        if exception:
            return
        for envelope in self.envelopes_to_send:
            self.smtp.send(envelope)


@hug.get('/hello')
def send_hello_email(smtp: SMTP):
    pass

One nice thing about solution is that annotation still preserves its basic functionality - a smtp variable is an object of SMTP class.

Any comments are welcome, thanks!

@coveralls
Copy link

coveralls commented Dec 25, 2017

Coverage Status

Coverage increased (+0.001%) to 99.845% when pulling 7ebcb60 on gtxm:class_directives into bf311e7 on timothycrosley:develop.

@timothycrosley
Copy link
Collaborator

This looks fantastic, thank you!

@timothycrosley timothycrosley merged commit 528a0de into hugapi:develop Jan 4, 2018
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

Successfully merging this pull request may close these issues.

None yet

3 participants