Usage of the asynchronous client

Requires aiohttp package to be installed.

  1"""
  2`aiohttp` package is required.
  3Since asynchronous client is powered by `aiohttp.ClientSession`.
  4"""
  5
  6import asyncio
  7import logging
  8
  9# module is requiring external dependency:
 10# so it can not be set in __init__ files
 11# for easier importing
 12from freedictionaryapi.clients.async_client import AsyncDictionaryApiClient
 13# or `from freedictionaryapi import DictionaryApiError`
 14from freedictionaryapi.errors import DictionaryApiError
 15from freedictionaryapi.languages import LanguageCodes
 16# or `from freedictionaryapi import LanguageCodes`
 17
 18
 19async def main():
 20    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
 21    logger = logging.getLogger(__name__)
 22
 23    # on initializing might be passed
 24    # # - one of supported languages (listed in LanguageCodes enum that imported above)
 25    # # - manually created aiohttp.ClientSession
 26    client = AsyncDictionaryApiClient()
 27
 28    # client have to be closed after all work
 29    # like in the same way we close our
 30    # web libraries` clients/sessions
 31
 32    # # it might be done with try-finally block
 33    try:
 34        # before watching of client methods
 35        # important note:
 36        # # each method that under hood
 37        # # uses HTTP request to API
 38        # # might raise correspond API error
 39        # # if one has been occurred
 40        # # so, you have to handle exceptions
 41        # # that might be raised during processing.
 42        # # for this we`ve imported errors above
 43        # # for now, we`ll catch API errors with one
 44        # # the big-scaled (common for all errors) exception
 45        # # DictionaryApiError
 46
 47        # so, go next...
 48
 49        # # in client`s methods we have to pass word
 50        # that we actually are searching info about
 51        # and also
 52        # if word`s language not the client default one
 53        # we can pass it manually
 54
 55        # 1. default language
 56        word = 'hello'
 57
 58        # # do not forger about errors handling
 59        try:
 60            parser = await client.fetch_parser(word)
 61        except DictionaryApiError:
 62            logger.error('Oops! Here I might do some stuff for errors handling!')
 63        else:
 64            # parser has a lot of different data
 65            # to explore see parser example and docs
 66            word_transcription = parser.get_transcription()
 67            print(f'Transcription of the word <{word}> is: {word_transcription}.')
 68
 69        # 2. set language for the particular word
 70        word = 'привет'
 71        language = LanguageCodes.RUSSIAN
 72
 73        try:
 74            parser = await client.fetch_parser(word, language)
 75        except DictionaryApiError:
 76            logger.error('Oops! Here I might do some stuff for errors handling!')
 77        else:
 78            word_definitions = parser.get_all_definitions()
 79            word_definitions_formatted_string = '; '.join(word_definitions)
 80            print(f'Definition[s] of the word <{word}> is/are: {word_definitions_formatted_string}')
 81
 82    finally:
 83        await client.close()
 84
 85    # # or with implemented context manager
 86    # # Note:
 87    # # on each usage of this context manager
 88    # # you init new instance -> init new web client instance
 89    # # so, client supposed to be created once for all program
 90    async with AsyncDictionaryApiClient() as client:
 91        word = 'queue'
 92        try:
 93            # here instead of the parser
 94            # we fetch word object
 95            # that implements clear API JSON response
 96            word = await client.fetch_word(word)
 97        except DictionaryApiError:
 98            logger.error('Oops! Here I might do some stuff for errors handling!')
 99        else:
100            print(f'Audio links of the word <{word}>:')
101            for phonetic in word.phonetics:
102                print(phonetic.audio)
103
104    # # # ---------------------------
105    # so, the most important methods are:
106    # - .fetch_parser() - that returns parser object
107    # - .fetch_word() - that returns word object
108    # also, it is some more methods
109    # but there are the most often needed
110    # since they implement high-level API
111    # that you want to use to
112
113
114if __name__ == '__main__':
115    loop = asyncio.get_event_loop()
116    loop.run_until_complete(main())