email-normalize
email-normalize copied to clipboard
loop = asyncio.get_event_loop() call fails
Hi there; When I try to call blocking normalize function. Call fails with
RuntimeError: There is no current event loop in thread 'Thread-7'.
@orhanbalci Did you find a solution?
EDIT: #4 contains the solution!
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`
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)