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

loop = asyncio.get_event_loop() call fails #6

Open
orhanbalci opened this issue Apr 26, 2021 · 3 comments
Open

loop = asyncio.get_event_loop() call fails #6

orhanbalci opened this issue Apr 26, 2021 · 3 comments

Comments

@orhanbalci
Copy link

Hi there;
When I try to call blocking normalize function. Call fails with

RuntimeError: There is no current event loop in thread 'Thread-7'.
@Myzel394
Copy link

Myzel394 commented Aug 5, 2021

@orhanbalci Did you find a solution?

EDIT:
#4 contains the solution!

@orhanbalci
Copy link
Author

I was using this library from a django project. Django has a utility function which converts an async function into a sync one. By using async_to_sync function I managed to call async normalize function.

def normalize_email(email: str) -> str:

    async def normalize_inner(email: str):
        normalizer = Normalizer()
        return await normalizer.normalize(email)

    normalized_email = email
    try:
        sync_normalize = async_to_sync(normalize_inner)
        normalisation_result = sync_normalize(email)
        if normalisation_result is not None:
            normalized_email = normalisation_result.normalized_address
    except BaseException:
        logger.exception("Error occured when normalizing %s ", email)

    return normalized_email`

@dvf
Copy link

dvf commented Oct 16, 2021

Using it as a decorator is a lot cleaner:

from asgiref.sync import async_to_sync
from email_normalize import Normalizer, Result


@async_to_sync
async def normalize(email: str) -> Result:
    normalizer = Normalizer()
    return await normalizer.normalize(email)

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