Follow a news topic all over the world in your native language.

We'll take some keywords, translate them into different language, fetch the news on these keywords and translate the new back. First we make it work, then make it fast using three layers of async programming

  • author :Hugo Evers
name url description provider market
datePublished
2021-05-27 13:00:00+00:00 Superrijken maken dankzij privéjet al weer mee... https://www.volkskrant.nl/nieuws-achtergrond/s... De markt voor privévluchten in Europa heeft zi... Volkskrant nl-NL
2021-05-27 09:05:14+00:00 Consumentenbond: Transavia 'minst flexibele' v... https://www.msn.com/nl-nl/news/Binnenland/cons... Wie voor de zomervakantie een flexibel vliegti... RTL Nieuws on MSN.com nl-NL
2021-05-24 14:10:00+00:00 KLM stopt met vliegen over Belarus na oproep p... https://www.volkskrant.nl/nieuws-achtergrond/k... KLM vliegt voorlopig niet over het luchtruim v... Volkskrant nl-NL
2021-05-29 05:02:00+00:00 Groningen Airport Eelde kijkt ook naar Brussel... https://www.dvhn.nl/drenthe/Groningen-Airport-... Fondsen van de Europese Unie kunnen indirect h... DVHN nl-NL
2021-05-27 05:45:00+00:00 Ryanair betaalt mensen om in het vliegtuig te ... https://www.telegraaf.nl/watuzegt/1752348247/r... Er is veel onbegrip bij het grote publiek over... De Telegraaf nl-NL
2021-05-25 06:57:00+00:00 KLM blijft over Wit-Rusland vliegen, andere ma... https://www.rd.nl/artikel/928503-klm-blijft-ov... Luchtvaartmaatschappij KLM blijft door het Wit... RD nl-NL
2021-05-24 19:30:00+00:00 KLM stopt toch met vluchten boven Wit-Rusland https://www.nhnieuws.nl/nieuws/286261/klm-stop... KLM gaat toch om Wit-Rusland vliegen op routes... Nieuws nl-NL
2021-05-24 11:07:00+00:00 KLM blijft over Belarus vliegen, andere maatsc... https://www.parool.nl/wereld/klm-blijft-over-b... Luchtvaartmaatschappij KLM blijft door het luc... PAROOL nl-NL
import pandas as pd
import plotly.graph_objects as go
import datetime as dt

def news_table(dates:np.array,
               titles:np.array,
               summaries:np.array,
               urls:np.array,
               autosize=True,
               width=500,
               height=550):
  df = pd.DataFrame([])

  df['Date'] = list(map(lambda date:dt.datetime.fromtimestamp(date.item() / 10**9).strftime('%d-%b'),dates))
  df['URL'] = list(map(lambda url: f'<a href="{url}">Link</a>', urls))
  df['Title'] = list(map(lambda url: f'<b>"{url}"</b> ', titles))
  df['Text'] = '<b>' + df['Title'] + '</b> ' + summaries + '...  ' + df['URL']

  values = [df['Date'], df['Text']]
  text_colors = ['#72bf44', '#414141', '#313c59']

  fig = go.Figure(data=[go.Table(
      columnwidth=[1.4, 8],
      header=dict(values=[[''],
                          ['']],
                  fill_color='rgba(0,0,0,0)',
                  # align='left',
                  font=dict(color='#414141', size=12, family='Verdana'),
                  height=0
                  ),
      cells=dict(values=values,
                  fill_color='rgba(0,0,0,0)',
                  align='left',
                  font=dict(color=text_colors, size=[10, 12], family='Verdana'),
                  height=40
                  ))
  ])

  fig.update_layout(
      title=dict(text='<b>Latest Aviation news</b>',
                  font=dict(color='#414141', size=18, family='Verdana')),
      title_x=0.5,
      autosize=autosize,
      width=width,
      height=height,
  )
  return fig.show(config={
    'displayModeBar': False})

bing news

get the news data as a dataframe

market_keywords_df = pd.DataFrame().from_dict(markets_dict,orient='index')
market_keywords_df
Country/Region Language iso_alpha keywords
da-DK Denmark Danish DNK Luftfart Flyselskab Fly Lufthavn Plane
de-AT Austria German AUT Luftfahrt Fluggesellschaft Flüge Flughafen Flu...
de-CH Switzerland German CHE Luftfahrt Fluggesellschaft Flüge Flughafen Flu...
de-DE Germany German DEU Luftfahrt Fluggesellschaft Flüge Flughafen Flu...
en-AU Australia English AUS Aviation Airline Flights Airport Plane
en-CA Canada English CAN Aviation Airline Flights Airport Plane
en-GB United Kingdom English GBR Aviation Airline Flights Airport Plane
en-ID Indonesia English IDN Aviation Airline Flights Airport Plane
en-IE Ireland English IRL Aviation Airline Flights Airport Plane
en-IN India English IND Aviation Airline Flights Airport Plane
en-MY Malaysia English MYS Aviation Airline Flights Airport Plane
en-NZ New Zealand English NZL Aviation Airline Flights Airport Plane
en-PH Republic of the Philippines English PHL Aviation Airline Flights Airport Plane
en-SG Singapore English SGP Aviation Airline Flights Airport Plane
en-US United States English USA Aviation Airline Flights Airport Plane
en-ZA South Africa English ZAF Aviation Airline Flights Airport Plane
es-AR Argentina Spanish ARG Aviación Aerolínea Vuelos Aeropuerto Avión
es-CL Chile Spanish CHL Aviación Aerolínea Vuelos Aeropuerto Avión
es-ES Spain Spanish ESP Aviación Aerolínea Vuelos Aeropuerto Avión
es-MX Mexico Spanish MEX Aviación Aerolínea Vuelos Aeropuerto Avión
fi-FI Finland Finnish FIN ilmailu lentoyhtiö lennot Lentokenttä kone
fr-FR France French FRA Aviation Compagnie aérienne Vols Aéroport Avion
it-IT Italy Italian ITA aviazione linea aerea voli Aeroporto Aereo
ja-JP Japan Japanese JPN 航空 エアライン フライト 空港 飛行機
ko-KR Korea Korean KOR 비행 공기 호스 항공편 공항 비행기
nl-BE Belgium Dutch BEL Luchtvaart vliegmaatschappij Vluchten Luchthav...
nl-NL Netherlands Dutch NLD Luchtvaart vliegmaatschappij Vluchten Luchthav...
pl-PL Poland Polish POL Lotnictwo Linia lotnicza Loty Lotnisko Samolot
pt-BR Brazil Portuguese BRA Aviação CIA aérea Voos Aeroporto Avião
ru-RU Russia Russian RUS авиации авиакомпания рейсы аэропорт Плане
sv-SE Sweden Swedish SWE Flyg Flygbolag Flyg Flygplats Plan
tr-TR Turkey Turkish TUR Havacılık Havayolu Uçak Havalimanı uçak
zh-CN People's republic of China Chinese (simplified) CHN 航空 航空公司 机票 飞机场 平面
zh-HK Hong Kong SAR Chinese (traditional) HKG 航空 航空公司 機票 飛機場 平面
zh-TW Taiwan Chinese (traditional) TWN 航空 航空公司 機票 飛機場 平面

How to create the queries for the news api?

First follow the documentation over at bing, create an account, activate billing and setup an API key. Then you need to create the query for the API request. Which consist of:

  • Market codes
  • Keywords (one string, keywords separated by spaces)
  • freshness
  • count
mkt = 'nl-NL'
keywords = 'Luchtvaart vliegmaatschappij Vluchten Luchthaven Vliegtuig'
search_url = "https://api.cognitive.microsoft.com/bing/v7.0/news/search"
freshness = 'Week'
headers = {"Ocp-Apim-Subscription-Key":os.environ['BINGS_NEWS_API_KEY']}
params = {
    "q": keywords,
    'freshness': freshness,
    'count': 10,
    'mkt': mkt,
    # "textDecorations": True, "textFormat": "RAW"
}

import requests

response = requests.get(search_url, headers=headers, params=params)
response.json()
{'_type': 'News',
 'queryContext': {'adultIntent': False,
  'originalQuery': 'Luchtvaart vliegmaatschappij Vluchten Luchthaven Vliegtuig'},
 'readLink': 'https://api.cognitive.microsoft.com/api/v7/news/search?q=Luchtvaart+vliegmaatschappij+Vluchten+Luchthaven+Vliegtuig',
 'sort': [{'id': 'relevance',
   'isSelected': True,
   'name': 'Beste overeenkomst',
   'url': 'https://api.cognitive.microsoft.com/api/v7/news/search?q=Luchtvaart+vliegmaatschappij+Vluchten+Luchthaven+Vliegtuig'},
  {'id': 'date',
   'isSelected': False,
   'name': 'Meest recent',
   'url': 'https://api.cognitive.microsoft.com/api/v7/news/search?q=Luchtvaart+vliegmaatschappij+Vluchten+Luchthaven+Vliegtuig&sortby=date'}],
 'totalEstimatedMatches': 8,
 'value': [{'about': [{'name': 'de Volkskrant',
     'readLink': 'https://api.cognitive.microsoft.com/api/v7/entities/a3b315b7-0c7d-d2d2-d2e6-c4d0e7964834'}],
   'category': 'Business',
   'datePublished': '2021-05-27T13:00:00.0000000Z',
   'description': 'De markt voor privévluchten in Europa heeft zich sneller hersteld van de coronacrisis dan de ‘gewone’ luchtvaart. Terwijl Jan Modaal zijn',
   'image': {'thumbnail': {'contentUrl': 'https://www.bing.com/th?id=OVFT.oJy735r2Aafw8ieaksZMGi&pid=News',
     'height': 466,
     'width': 700}},
   'name': 'Superrijken maken dankzij privéjet al weer meer vluchten dan de sterveling',
   'provider': [{'_type': 'Organization', 'name': 'Volkskrant'}],
   'url': 'https://www.volkskrant.nl/nieuws-achtergrond/superrijken-maken-dankzij-privejet-al-weer-meer-vluchten-dan-de-sterveling~b40828a1/'},
  {'about': [{'name': 'Consumentenbond',
     'readLink': 'https://api.cognitive.microsoft.com/api/v7/entities/fea22130-578e-4ad9-9174-6a90720745fd'}],
   'category': 'Business',
   'datePublished': '2021-05-27T09:05:14.0000000Z',
   'description': 'Wie voor de zomervakantie een flexibel vliegticket wil boeken, kan beter niet bij Transavia aankloppen. In vergelijking met andere Europese luchtvaartmaatschappijen is die een stuk minder soepel als h',
   'image': {'thumbnail': {'contentUrl': 'https://www.bing.com/th?id=OVFT.OTQ5ataMdKakSebtaH5UXy&pid=News',
     'height': 393,
     'width': 700}},
   'mentions': [{'name': 'Consumentenbond'},
    {'name': 'Transavia.com'},
    {'name': 'RTL Nieuws'}],
   'name': "Consumentenbond: Transavia 'minst flexibele' vliegmaatschappij",
   'provider': [{'_type': 'Organization', 'name': 'RTL Nieuws on MSN.com'}],
   'url': 'https://www.msn.com/nl-nl/news/Binnenland/consumentenbond-transavia-minst-flexibele-vliegmaatschappij/ar-AAKqSMa'},
  {'about': [{'name': 'de Volkskrant',
     'readLink': 'https://api.cognitive.microsoft.com/api/v7/entities/a3b315b7-0c7d-d2d2-d2e6-c4d0e7964834'},
    {'name': 'KLM',
     'readLink': 'https://api.cognitive.microsoft.com/api/v7/entities/500f9f4f-16e3-a317-4cec-21fc8c627782'},
    {'name': 'Belarus',
     'readLink': 'https://api.cognitive.microsoft.com/api/v7/entities/70f0e4f4-4cfb-8ee3-cfe6-041ba6b221bc'}],
   'datePublished': '2021-05-24T14:10:00.0000000Z',
   'description': 'KLM vliegt voorlopig niet over het luchtruim van Belarus. Eerder op maandag riep premier Rutte de luchtvaartmaatschappij op het luchtruim te',
   'image': {'thumbnail': {'contentUrl': 'https://www.bing.com/th?id=OVFT.LwWrklLNGJl5oDHV9C4CmC&pid=News',
     'height': 469,
     'width': 700}},
   'name': 'KLM stopt met vliegen over Belarus na oproep premier Rutte',
   'provider': [{'_type': 'Organization', 'name': 'Volkskrant'}],
   'url': 'https://www.volkskrant.nl/nieuws-achtergrond/klm-stopt-met-vliegen-over-belarus-na-oproep-premier-rutte~b66d8a01/'},
  {'datePublished': '2021-05-29T05:02:00.0000000Z',
   'description': 'Fondsen van de Europese Unie kunnen indirect helpen bij het overleven van Groningen Airport Eelde (GAE). De luchthaven heeft dan ook de blik op Brussel gericht.',
   'image': {'thumbnail': {'contentUrl': 'https://www.bing.com/th?id=OVFT.ilHo9N2ArAu9IBZzxo4fiy&pid=News',
     'height': 436,
     'width': 700}},
   'name': 'Groningen Airport Eelde kijkt ook naar Brussel voor overlevingskansen. Fondsen van Europese Unie kunnen indirect helpen',
   'provider': [{'_type': 'Organization', 'name': 'DVHN'}],
   'url': 'https://www.dvhn.nl/drenthe/Groningen-Airport-Eelde-kijkt-ook-naar-Brussel-voor-overlevingskansen-26854246.html'},
  {'about': [{'name': 'De Telegraaf',
     'readLink': 'https://api.cognitive.microsoft.com/api/v7/entities/9d35a5f9-d594-d398-1e17-b30ade9d7385'},
    {'name': 'Ryanair',
     'readLink': 'https://api.cognitive.microsoft.com/api/v7/entities/416c0ed4-d041-d9d6-4ddb-0d5c65f5be34'}],
   'datePublished': '2021-05-27T05:45:00.0000000Z',
   'description': 'Er is veel onbegrip bij het grote publiek over de luchtvaart, zo blijkt deze dagen weer. Lezers meldden mij verontwaardigd dat de KLM na de kaping van een toestel van Ryanair boven Wit-Rusland bleef v',
   'image': {'thumbnail': {'contentUrl': 'https://www.bing.com/th?id=OVFT.b9W7s5HCwbJxAQWXNLl3bi&pid=News',
     'height': 367,
     'width': 700}},
   'name': 'Ryanair betaalt mensen om in het vliegtuig te stappen is pure marketingstunt',
   'provider': [{'_type': 'Organization', 'name': 'De Telegraaf'}],
   'url': 'https://www.telegraaf.nl/watuzegt/1752348247/ryanair-betaalt-mensen-om-in-het-vliegtuig-te-stappen-is-pure-marketingstunt'},
  {'about': [{'name': 'KLM',
     'readLink': 'https://api.cognitive.microsoft.com/api/v7/entities/500f9f4f-16e3-a317-4cec-21fc8c627782'},
    {'name': 'Rusland, Cumbria',
     'readLink': 'https://api.cognitive.microsoft.com/api/v7/entities/54cf54dd-77eb-3e02-afb1-7edb875e5941'}],
   'datePublished': '2021-05-25T06:57:00.0000000Z',
   'description': 'Luchtvaartmaatschappij KLM blijft door het Wit-Russische luchtruim vliegen. De maatschappij zegt geen veiligheidsrisico te zien en stelt dat het vluchtschema „normaal zal worden voortgezet”. KLM heeft',
   'image': {'thumbnail': {'contentUrl': 'https://www.bing.com/th?id=OVFT.lpwGdQd6RSUjqsK_Q3ebPi&pid=News',
     'height': 437,
     'width': 700}},
   'name': 'KLM blijft over Wit-Rusland vliegen, andere maatschappijen niet',
   'provider': [{'_type': 'Organization', 'name': 'RD'}],
   'url': 'https://www.rd.nl/artikel/928503-klm-blijft-over-wit-rusland-vliegen'},
  {'about': [{'name': 'Rusland, Cumbria',
     'readLink': 'https://api.cognitive.microsoft.com/api/v7/entities/54cf54dd-77eb-3e02-afb1-7edb875e5941'},
    {'name': 'New Hampshire',
     'readLink': 'https://api.cognitive.microsoft.com/api/v7/entities/9ca71997-cc97-46eb-8911-fac32f80b0b1'},
    {'name': 'KLM',
     'readLink': 'https://api.cognitive.microsoft.com/api/v7/entities/500f9f4f-16e3-a317-4cec-21fc8c627782'}],
   'datePublished': '2021-05-24T19:30:00.0000000Z',
   'description': 'KLM gaat toch om Wit-Rusland vliegen op routes van en naar Azië. Dat laat de maatschappij weten nadat demissionair premier Rutte KLM opriep om het Wit-Russische luchtruim te vermijden. Aanleiding is d',
   'image': {'thumbnail': {'contentUrl': 'https://www.bing.com/th?id=OVFT.3o1T08dkW4JbTPzPE7GjnC&pid=News',
     'height': 394,
     'width': 700}},
   'name': 'KLM stopt toch met vluchten boven Wit-Rusland',
   'provider': [{'_type': 'Organization', 'name': 'Nieuws'}],
   'url': 'https://www.nhnieuws.nl/nieuws/286261/klm-stopt-toch-met-vluchten-boven-wit-rusland'},
  {'about': [{'name': 'Belarus',
     'readLink': 'https://api.cognitive.microsoft.com/api/v7/entities/70f0e4f4-4cfb-8ee3-cfe6-041ba6b221bc'},
    {'name': 'KLM',
     'readLink': 'https://api.cognitive.microsoft.com/api/v7/entities/500f9f4f-16e3-a317-4cec-21fc8c627782'},
    {'name': 'Het Parool',
     'readLink': 'https://api.cognitive.microsoft.com/api/v7/entities/914c006b-8523-333d-5ffc-2a81413ff871'}],
   'datePublished': '2021-05-24T11:07:00.0000000Z',
   'description': 'Luchtvaartmaatschappij KLM blijft door het luchtruim boven Belarus vliegen. Verschillende andere maatschappijen mijden het land voorlopig vanwege',
   'image': {'thumbnail': {'contentUrl': 'https://www.bing.com/th?id=OVFT.rgCSEJM00FvWDGpT3PUFBS&pid=News',
     'height': 466,
     'width': 700}},
   'name': 'KLM blijft over Belarus vliegen, andere maatschappijen niet',
   'provider': [{'_type': 'Organization', 'name': 'PAROOL'}],
   'url': 'https://www.parool.nl/wereld/klm-blijft-over-belarus-vliegen-andere-maatschappijen-niet~b9bc387b/'}]}
Our list of keywords to search for:
keywords =  ['Aviation', 
             'Airline', 
             'Flights', 
             'Airport', 
             'Planes']

You will also need to determine in which markets you want to fetch the news, since we want a very international perspective and get the aviation news from every country we ask for every news country. So we need a list of markets to search in.

market_codes = ['da-DK',
                'de-AT',
                'de-CH',
                'de-DE',
                'en-AU',
                'en-CA',
                'en-GB',
                'en-ID',
                'en-IE',
                'en-IN',
                'en-MY',
                'en-NZ',
                'en-PH',
                'en-SG',
                'en-US',
                'en-ZA',
                'es-AR',
                'es-CL',
                'es-ES',
                'es-MX',
                'fi-FI',
                'fr-FR',
                'it-IT',
                'ja-JP',
                'ko-KR',
                'nl-BE',
                'nl-NL',
                'pl-PL',
                'pt-BR',
                'ru-RU',
                'sv-SE',
                'tr-TR',
                'zh-CN',
                'zh-HK',
                'zh-TW']

You can copy and paste the table with all the markets, but you can also remember that pandas has a very neat table scraping function, so with a little pd.read_html and filters these afterwards.

import pandas as pd
markets_df = pd.read_html('https://docs.microsoft.com/en-us/rest/api/cognitiveservices-bingsearch/bing-news-api-v7-reference#market-codes')[23]
markets_df
Country/Region Language Market Code
0 Denmark Danish da-DK
1 Austria German de-AT
2 Belgium Dutch nl-BE
3 Switzerland German de-CH
4 Germany German de-DE
5 Australia English en-AU
6 Canada English en-CA
7 United Kingdom English en-GB
8 Indonesia English en-ID
9 Ireland English en-IE
10 India English en-IN
11 Malaysia English en-MY
12 New Zealand English en-NZ
13 Republic of the Philippines English en-PH
14 Singapore English en-SG
15 United States English en-US
16 English general en-WW
17 English general en-XA
18 South Africa English en-ZA
19 Argentina Spanish es-AR
20 Chile Spanish es-CL
21 Spain Spanish es-ES
22 Mexico Spanish es-MX
23 United States Spanish es-US
24 Spanish general es-XL
25 Finland Finnish fi-FI
26 France French fr-BE
27 Canada French fr-CA
28 Switzerland French fr-CH
29 France French fr-FR
30 Italy Italian it-IT
31 Hong Kong SAR Traditional Chinese zh-HK
32 Taiwan Traditional Chinese zh-TW
33 Japan Japanese ja-JP
34 Korea Korean ko-KR
35 Netherlands Dutch nl-NL
36 People's republic of China Chinese zh-CN
37 Poland Polish pl-PL
38 Brazil Portuguese pt-BR
39 Russia Russian ru-RU
40 Sweden Swedish sv-SE
41 Turkey Turkish tr-TR
market_keywords_df.index.to_list()
['da-DK',
 'de-AT',
 'de-CH',
 'de-DE',
 'en-AU',
 'en-CA',
 'en-GB',
 'en-ID',
 'en-IE',
 'en-IN',
 'en-MY',
 'en-NZ',
 'en-PH',
 'en-SG',
 'en-US',
 'en-ZA',
 'es-AR',
 'es-CL',
 'es-ES',
 'es-MX',
 'fi-FI',
 'fr-FR',
 'it-IT',
 'ja-JP',
 'ko-KR',
 'nl-BE',
 'nl-NL',
 'pl-PL',
 'pt-BR',
 'ru-RU',
 'sv-SE',
 'tr-TR',
 'zh-CN',
 'zh-HK',
 'zh-TW']
import pycountry
from google_trans_new import google_translator




def generate_market_keywords(keywords:list,market_codes:list)->dict:
  """
  Parameters
  ----------
  keywords : list
    list of keywords to be translated in the target language (as provided in the market-codes)
  market_codes : list
    list of market_codes, formatted as language_iso_alpha_2-COUNTRY_ISO_ALPHA_2 , e.g 'da-DK'

  Returns
  -------
  market_codes_country_language_alpha3_keywords : dict
  {
    'da-DK': {
      'Country/Region': 'Denmark',
      'Language': 'Danish',
      'iso_alpha': 'DNK',
      'keywords': 'Luftfart Flyselskab Fly Lufthavn Planer',
      'language_iso_alpha_2': 'da'
      },
 'de-AT': {
   'Country/Region': 'Austria',
   'Language': 'German',
   'iso_alpha': 'AUT',
   'keywords': 'Luftfahrt Fluggesellschaft Flüge Flughafen Flugzeug',
   'language_iso_alpha_2': 'de'
   }
  }
  """
  translate_keywords = lambda keywords, language_iso_alpha_2: [
                                                google_translator().translate(
                                                    keyword, 
                                                    lang_tgt=language_iso_alpha_2,
                                                    lang_src = 'en'
                                                    ) 
                                                for keyword in keywords
                                                ]
  # generate the set of languages in the target markets
  target_languages = set([get_country_language_iso_alpha(market_code)['language_iso_alpha_2'] for market_code in market_codes])
  # generate the dictionary with language as the key and translates keywords as values
  keywords_translated = {language : " ".join(translate_keywords(keywords,language)) for language in target_languages}

  return {market_code:{**get_country_language_iso_alpha(market_code),
                **{"keywords":keywords_translated[get_country_language_iso_alpha(market_code)['language_iso_alpha_2']]}
  } for market_code in market_codes}

generate_market_keywords(keywords,market_codes)
/usr/local/lib/python3.7/dist-packages/pkg_resources/_vendor/pyparsing.py:3552: RuntimeWarning: coroutine 'async_series_translator' was never awaited
  ret = e._parse( instring, loc, doActions )
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-53-f5dab7e639fe> in <module>()
     90   } for market_code in market_codes}
     91 
---> 92 generate_market_keywords(keywords,market_codes)

<ipython-input-53-f5dab7e639fe> in generate_market_keywords(keywords, market_codes)
     82                                                 ]
     83   # generate the set of languages in the target markets
---> 84   target_languages = set([get_country_language_iso_alpha(market_code)['language_iso_alpha_2'] for market_code in market_codes])
     85   # generate the dictionary with language as the key and translates keywords as values
     86   keywords_translated = {language : " ".join(translate_keywords(keywords,language)) for language in target_languages}

<ipython-input-53-f5dab7e639fe> in <listcomp>(.0)
     82                                                 ]
     83   # generate the set of languages in the target markets
---> 84   target_languages = set([get_country_language_iso_alpha(market_code)['language_iso_alpha_2'] for market_code in market_codes])
     85   # generate the dictionary with language as the key and translates keywords as values
     86   keywords_translated = {language : " ".join(translate_keywords(keywords,language)) for language in target_languages}

NameError: name 'get_country_language_iso_alpha' is not defined
markets_dict = {'da-DK': {'Country/Region': 'Denmark',
  'Language': 'Danish',
  'iso_alpha': 'DNK',
  'keywords': 'Luftfart Flyselskab Fly Lufthavn Plane'},
 'de-AT': {'Country/Region': 'Austria',
  'Language': 'German',
  'iso_alpha': 'AUT',
  'keywords': 'Luftfahrt Fluggesellschaft Flüge Flughafen Flugzeug'},
 'de-CH': {'Country/Region': 'Switzerland',
  'Language': 'German',
  'iso_alpha': 'CHE',
  'keywords': 'Luftfahrt Fluggesellschaft Flüge Flughafen Flugzeug'},
 'de-DE': {'Country/Region': 'Germany',
  'Language': 'German',
  'iso_alpha': 'DEU',
  'keywords': 'Luftfahrt Fluggesellschaft Flüge Flughafen Flugzeug'},
 'en-AU': {'Country/Region': 'Australia',
  'Language': 'English',
  'iso_alpha': 'AUS',
  'keywords': 'Aviation Airline Flights Airport Plane'},
 'en-CA': {'Country/Region': 'Canada',
  'Language': 'English',
  'iso_alpha': 'CAN',
  'keywords': 'Aviation Airline Flights Airport Plane'},
 'en-GB': {'Country/Region': 'United Kingdom',
  'Language': 'English',
  'iso_alpha': 'GBR',
  'keywords': 'Aviation Airline Flights Airport Plane'},
 'en-ID': {'Country/Region': 'Indonesia',
  'Language': 'English',
  'iso_alpha': 'IDN',
  'keywords': 'Aviation Airline Flights Airport Plane'},
 'en-IE': {'Country/Region': 'Ireland',
  'Language': 'English',
  'iso_alpha': 'IRL',
  'keywords': 'Aviation Airline Flights Airport Plane'},
 'en-IN': {'Country/Region': 'India',
  'Language': 'English',
  'iso_alpha': 'IND',
  'keywords': 'Aviation Airline Flights Airport Plane'},
 'en-MY': {'Country/Region': 'Malaysia',
  'Language': 'English',
  'iso_alpha': 'MYS',
  'keywords': 'Aviation Airline Flights Airport Plane'},
 'en-NZ': {'Country/Region': 'New Zealand',
  'Language': 'English',
  'iso_alpha': 'NZL',
  'keywords': 'Aviation Airline Flights Airport Plane'},
 'en-PH': {'Country/Region': 'Republic of the Philippines',
  'Language': 'English',
  'iso_alpha': 'PHL',
  'keywords': 'Aviation Airline Flights Airport Plane'},
 'en-SG': {'Country/Region': 'Singapore',
  'Language': 'English',
  'iso_alpha': 'SGP',
  'keywords': 'Aviation Airline Flights Airport Plane'},
 'en-US': {'Country/Region': 'United States',
  'Language': 'English',
  'iso_alpha': 'USA',
  'keywords': 'Aviation Airline Flights Airport Plane'},
 'en-ZA': {'Country/Region': 'South Africa',
  'Language': 'English',
  'iso_alpha': 'ZAF',
  'keywords': 'Aviation Airline Flights Airport Plane'},
 'es-AR': {'Country/Region': 'Argentina',
  'Language': 'Spanish',
  'iso_alpha': 'ARG',
  'keywords': 'Aviación Aerolínea Vuelos Aeropuerto Avión'},
 'es-CL': {'Country/Region': 'Chile',
  'Language': 'Spanish',
  'iso_alpha': 'CHL',
  'keywords': 'Aviación Aerolínea Vuelos Aeropuerto Avión'},
 'es-ES': {'Country/Region': 'Spain',
  'Language': 'Spanish',
  'iso_alpha': 'ESP',
  'keywords': 'Aviación Aerolínea Vuelos Aeropuerto Avión'},
 'es-MX': {'Country/Region': 'Mexico',
  'Language': 'Spanish',
  'iso_alpha': 'MEX',
  'keywords': 'Aviación Aerolínea Vuelos Aeropuerto Avión'},
 'fi-FI': {'Country/Region': 'Finland',
  'Language': 'Finnish',
  'iso_alpha': 'FIN',
  'keywords': 'ilmailu lentoyhtiö lennot Lentokenttä kone'},
 'fr-FR': {'Country/Region': 'France',
  'Language': 'French',
  'iso_alpha': 'FRA',
  'keywords': 'Aviation Compagnie aérienne Vols Aéroport Avion'},
 'it-IT': {'Country/Region': 'Italy',
  'Language': 'Italian',
  'iso_alpha': 'ITA',
  'keywords': 'aviazione linea aerea voli Aeroporto Aereo'},
 'ja-JP': {'Country/Region': 'Japan',
  'Language': 'Japanese',
  'iso_alpha': 'JPN',
  'keywords': '航空 エアライン フライト 空港 飛行機'},
 'ko-KR': {'Country/Region': 'Korea',
  'Language': 'Korean',
  'iso_alpha': 'KOR',
  'keywords': '비행 공기 호스 항공편 공항 비행기'},
 'nl-BE': {'Country/Region': 'Belgium',
  'Language': 'Dutch',
  'iso_alpha': 'BEL',
  'keywords': 'Luchtvaart vliegmaatschappij Vluchten Luchthaven Vliegtuig'},
 'nl-NL': {'Country/Region': 'Netherlands',
  'Language': 'Dutch',
  'iso_alpha': 'NLD',
  'keywords': 'Luchtvaart vliegmaatschappij Vluchten Luchthaven Vliegtuig'},
 'pl-PL': {'Country/Region': 'Poland',
  'Language': 'Polish',
  'iso_alpha': 'POL',
  'keywords': 'Lotnictwo Linia lotnicza Loty Lotnisko Samolot'},
 'pt-BR': {'Country/Region': 'Brazil',
  'Language': 'Portuguese',
  'iso_alpha': 'BRA',
  'keywords': 'Aviação CIA aérea Voos Aeroporto Avião'},
 'ru-RU': {'Country/Region': 'Russia',
  'Language': 'Russian',
  'iso_alpha': 'RUS',
  'keywords': 'авиации авиакомпания рейсы аэропорт Плане'},
 'sv-SE': {'Country/Region': 'Sweden',
  'Language': 'Swedish',
  'iso_alpha': 'SWE',
  'keywords': 'Flyg Flygbolag Flyg Flygplats Plan'},
 'tr-TR': {'Country/Region': 'Turkey',
  'Language': 'Turkish',
  'iso_alpha': 'TUR',
  'keywords': 'Havacılık Havayolu Uçak Havalimanı uçak'},
 'zh-CN': {'Country/Region': "People's republic of China",
  'Language': 'Chinese (simplified)',
  'iso_alpha': 'CHN',
  'keywords': '航空 航空公司 机票 飞机场 平面'},
 'zh-HK': {'Country/Region': 'Hong Kong SAR',
  'Language': 'Chinese (traditional)',
  'iso_alpha': 'HKG',
  'keywords': '航空 航空公司 機票 飛機場 平面'},
 'zh-TW': {'Country/Region': 'Taiwan',
  'Language': 'Chinese (traditional)',
  'iso_alpha': 'TWN',
  'keywords': '航空 航空公司 機票 飛機場 平面'}}
import pycountry
def get_country_language_iso_alpha(market_code:str)->dict:
  """
  
  """

  language_iso_alpha_2,country_alpha_2 = market_code.split('-')

  return {
      'country': pycountry.countries.get(alpha_2=country_alpha_2).name,
      'language': pycountry.languages.get(alpha_2=language_iso_alpha_2).name,
      'language_iso_alpha_2':language_iso_alpha_2,
      'iso_alpha': pycountry.countries.get(alpha_2=country_alpha_2).alpha_3
      
  }
!pip install pycountry google_trans_new
Collecting pycountry
  Downloading https://files.pythonhosted.org/packages/76/73/6f1a412f14f68c273feea29a6ea9b9f1e268177d32e0e69ad6790d306312/pycountry-20.7.3.tar.gz (10.1MB)
     |████████████████████████████████| 10.1MB 2.1MB/s 
Collecting google_trans_new
  Downloading https://files.pythonhosted.org/packages/f9/7b/9f136106dc5824dc98185c97991d3cd9b53e70a197154dd49f7b899128f6/google_trans_new-1.1.9-py3-none-any.whl
Building wheels for collected packages: pycountry
  Building wheel for pycountry (setup.py) ... done
  Created wheel for pycountry: filename=pycountry-20.7.3-py2.py3-none-any.whl size=10746863 sha256=bfce3fcbaaee04549c259d91a5ff4713f638ef0e3c52b322f2a4b49c249d7cf1
  Stored in directory: /root/.cache/pip/wheels/33/4e/a6/be297e6b83567e537bed9df4a93f8590ec01c1acfbcd405348
Successfully built pycountry
Installing collected packages: pycountry, google-trans-new
Successfully installed google-trans-new-1.1.9 pycountry-20.7.3
market_keywords_df
Country/Region Language iso_alpha keywords
da-DK Denmark Danish DNK Luftfart Flyselskab Fly Lufthavn Plane
de-AT Austria German AUT Luftfahrt Fluggesellschaft Flüge Flughafen Flu...
de-CH Switzerland German CHE Luftfahrt Fluggesellschaft Flüge Flughafen Flu...
de-DE Germany German DEU Luftfahrt Fluggesellschaft Flüge Flughafen Flu...
en-AU Australia English AUS Aviation Airline Flights Airport Plane
en-CA Canada English CAN Aviation Airline Flights Airport Plane
en-GB United Kingdom English GBR Aviation Airline Flights Airport Plane
en-ID Indonesia English IDN Aviation Airline Flights Airport Plane
en-IE Ireland English IRL Aviation Airline Flights Airport Plane
en-IN India English IND Aviation Airline Flights Airport Plane
en-MY Malaysia English MYS Aviation Airline Flights Airport Plane
en-NZ New Zealand English NZL Aviation Airline Flights Airport Plane
en-PH Republic of the Philippines English PHL Aviation Airline Flights Airport Plane
en-SG Singapore English SGP Aviation Airline Flights Airport Plane
en-US United States English USA Aviation Airline Flights Airport Plane
en-ZA South Africa English ZAF Aviation Airline Flights Airport Plane
es-AR Argentina Spanish ARG Aviación Aerolínea Vuelos Aeropuerto Avión
es-CL Chile Spanish CHL Aviación Aerolínea Vuelos Aeropuerto Avión
es-ES Spain Spanish ESP Aviación Aerolínea Vuelos Aeropuerto Avión
es-MX Mexico Spanish MEX Aviación Aerolínea Vuelos Aeropuerto Avión
fi-FI Finland Finnish FIN ilmailu lentoyhtiö lennot Lentokenttä kone
fr-FR France French FRA Aviation Compagnie aérienne Vols Aéroport Avion
it-IT Italy Italian ITA aviazione linea aerea voli Aeroporto Aereo
ja-JP Japan Japanese JPN 航空 エアライン フライト 空港 飛行機
ko-KR Korea Korean KOR 비행 공기 호스 항공편 공항 비행기
nl-BE Belgium Dutch BEL Luchtvaart vliegmaatschappij Vluchten Luchthav...
nl-NL Netherlands Dutch NLD Luchtvaart vliegmaatschappij Vluchten Luchthav...
pl-PL Poland Polish POL Lotnictwo Linia lotnicza Loty Lotnisko Samolot
pt-BR Brazil Portuguese BRA Aviação CIA aérea Voos Aeroporto Avião
ru-RU Russia Russian RUS авиации авиакомпания рейсы аэропорт Плане
sv-SE Sweden Swedish SWE Flyg Flygbolag Flyg Flygplats Plan
tr-TR Turkey Turkish TUR Havacılık Havayolu Uçak Havalimanı uçak
zh-CN People's republic of China Chinese (simplified) CHN 航空 航空公司 机票 飞机场 平面
zh-HK Hong Kong SAR Chinese (traditional) HKG 航空 航空公司 機票 飛機場 平面
zh-TW Taiwan Chinese (traditional) TWN 航空 航空公司 機票 飛機場 平面
market_keywords_dict = market_keywords_df['keywords'].to_dict()
market_keywords_dict
{'da-DK': 'Luftfart Flyselskab Fly Lufthavn Plane',
 'de-AT': 'Luftfahrt Fluggesellschaft Flüge Flughafen Flugzeug',
 'de-CH': 'Luftfahrt Fluggesellschaft Flüge Flughafen Flugzeug',
 'de-DE': 'Luftfahrt Fluggesellschaft Flüge Flughafen Flugzeug',
 'en-AU': 'Aviation Airline Flights Airport Plane',
 'en-CA': 'Aviation Airline Flights Airport Plane',
 'en-GB': 'Aviation Airline Flights Airport Plane',
 'en-ID': 'Aviation Airline Flights Airport Plane',
 'en-IE': 'Aviation Airline Flights Airport Plane',
 'en-IN': 'Aviation Airline Flights Airport Plane',
 'en-MY': 'Aviation Airline Flights Airport Plane',
 'en-NZ': 'Aviation Airline Flights Airport Plane',
 'en-PH': 'Aviation Airline Flights Airport Plane',
 'en-SG': 'Aviation Airline Flights Airport Plane',
 'en-US': 'Aviation Airline Flights Airport Plane',
 'en-ZA': 'Aviation Airline Flights Airport Plane',
 'es-AR': 'Aviación Aerolínea Vuelos Aeropuerto Avión',
 'es-CL': 'Aviación Aerolínea Vuelos Aeropuerto Avión',
 'es-ES': 'Aviación Aerolínea Vuelos Aeropuerto Avión',
 'es-MX': 'Aviación Aerolínea Vuelos Aeropuerto Avión',
 'fi-FI': 'ilmailu lentoyhtiö lennot Lentokenttä kone',
 'fr-FR': 'Aviation Compagnie aérienne Vols Aéroport Avion',
 'it-IT': 'aviazione linea aerea voli Aeroporto Aereo',
 'ja-JP': '航空 エアライン フライト 空港 飛行機',
 'ko-KR': '비행 공기 호스 항공편 공항 비행기',
 'nl-BE': 'Luchtvaart vliegmaatschappij Vluchten Luchthaven Vliegtuig',
 'nl-NL': 'Luchtvaart vliegmaatschappij Vluchten Luchthaven Vliegtuig',
 'pl-PL': 'Lotnictwo Linia lotnicza Loty Lotnisko Samolot',
 'pt-BR': 'Aviação CIA aérea Voos Aeroporto Avião',
 'ru-RU': 'авиации авиакомпания рейсы аэропорт Плане',
 'sv-SE': 'Flyg Flygbolag Flyg Flygplats Plan',
 'tr-TR': 'Havacılık Havayolu Uçak Havalimanı uçak',
 'zh-CN': '航空 航空公司 机票 飞机场 平面',
 'zh-HK': '航空 航空公司 機票 飛機場 平面',
 'zh-TW': '航空 航空公司 機票 飛機場 平面'}
pip install backoff aiohttp asyncio
Collecting backoff
  Downloading https://files.pythonhosted.org/packages/f0/32/c5dd4f4b0746e9ec05ace2a5045c1fc375ae67ee94355344ad6c7005fd87/backoff-1.10.0-py2.py3-none-any.whl
Collecting aiohttp
  Downloading https://files.pythonhosted.org/packages/88/c0/5890b4c8b04a79b7360e8fe4490feb0bb3ab179743f199f0e6220cebd568/aiohttp-3.7.4.post0-cp37-cp37m-manylinux2014_x86_64.whl (1.3MB)
     |████████████████████████████████| 1.3MB 13.7MB/s 
Collecting asyncio
  Downloading https://files.pythonhosted.org/packages/22/74/07679c5b9f98a7cb0fc147b1ef1cc1853bc07a4eb9cb5731e24732c5f773/asyncio-3.4.3-py3-none-any.whl (101kB)
     |████████████████████████████████| 102kB 11.9MB/s 
Requirement already satisfied: typing-extensions>=3.6.5 in /usr/local/lib/python3.7/dist-packages (from aiohttp) (3.7.4.3)
Requirement already satisfied: chardet<5.0,>=2.0 in /usr/local/lib/python3.7/dist-packages (from aiohttp) (3.0.4)
Collecting multidict<7.0,>=4.5
  Downloading https://files.pythonhosted.org/packages/7c/a6/4123b8165acbe773d1a8dc8e3f0d1edea16d29f7de018eda769abb56bd30/multidict-5.1.0-cp37-cp37m-manylinux2014_x86_64.whl (142kB)
     |████████████████████████████████| 143kB 36.3MB/s 
Collecting async-timeout<4.0,>=3.0
  Downloading https://files.pythonhosted.org/packages/e1/1e/5a4441be21b0726c4464f3f23c8b19628372f606755a9d2e46c187e65ec4/async_timeout-3.0.1-py3-none-any.whl
Requirement already satisfied: attrs>=17.3.0 in /usr/local/lib/python3.7/dist-packages (from aiohttp) (21.2.0)
Collecting yarl<2.0,>=1.0
  Downloading https://files.pythonhosted.org/packages/f1/62/046834c5fc998c88ab2ef722f5d42122230a632212c8afa76418324f53ff/yarl-1.6.3-cp37-cp37m-manylinux2014_x86_64.whl (294kB)
     |████████████████████████████████| 296kB 38.7MB/s 
Requirement already satisfied: idna>=2.0 in /usr/local/lib/python3.7/dist-packages (from yarl<2.0,>=1.0->aiohttp) (2.10)
Installing collected packages: backoff, multidict, async-timeout, yarl, aiohttp, asyncio
Successfully installed aiohttp-3.7.4.post0 async-timeout-3.0.1 asyncio-3.4.3 backoff-1.10.0 multidict-5.1.0 yarl-1.6.3
market_keywords_dict
{'da-DK': 'Luftfart Flyselskab Fly Lufthavn Plane',
 'de-AT': 'Luftfahrt Fluggesellschaft Flüge Flughafen Flugzeug',
 'de-CH': 'Luftfahrt Fluggesellschaft Flüge Flughafen Flugzeug',
 'de-DE': 'Luftfahrt Fluggesellschaft Flüge Flughafen Flugzeug',
 'en-AU': 'Aviation Airline Flights Airport Plane',
 'en-CA': 'Aviation Airline Flights Airport Plane',
 'en-GB': 'Aviation Airline Flights Airport Plane',
 'en-ID': 'Aviation Airline Flights Airport Plane',
 'en-IE': 'Aviation Airline Flights Airport Plane',
 'en-IN': 'Aviation Airline Flights Airport Plane',
 'en-MY': 'Aviation Airline Flights Airport Plane',
 'en-NZ': 'Aviation Airline Flights Airport Plane',
 'en-PH': 'Aviation Airline Flights Airport Plane',
 'en-SG': 'Aviation Airline Flights Airport Plane',
 'en-US': 'Aviation Airline Flights Airport Plane',
 'en-ZA': 'Aviation Airline Flights Airport Plane',
 'es-AR': 'Aviación Aerolínea Vuelos Aeropuerto Avión',
 'es-CL': 'Aviación Aerolínea Vuelos Aeropuerto Avión',
 'es-ES': 'Aviación Aerolínea Vuelos Aeropuerto Avión',
 'es-MX': 'Aviación Aerolínea Vuelos Aeropuerto Avión',
 'fi-FI': 'ilmailu lentoyhtiö lennot Lentokenttä kone',
 'fr-FR': 'Aviation Compagnie aérienne Vols Aéroport Avion',
 'it-IT': 'aviazione linea aerea voli Aeroporto Aereo',
 'ja-JP': '航空 エアライン フライト 空港 飛行機',
 'ko-KR': '비행 공기 호스 항공편 공항 비행기',
 'nl-BE': 'Luchtvaart vliegmaatschappij Vluchten Luchthaven Vliegtuig',
 'nl-NL': 'Luchtvaart vliegmaatschappij Vluchten Luchthaven Vliegtuig',
 'pl-PL': 'Lotnictwo Linia lotnicza Loty Lotnisko Samolot',
 'pt-BR': 'Aviação CIA aérea Voos Aeroporto Avião',
 'ru-RU': 'авиации авиакомпания рейсы аэропорт Плане',
 'sv-SE': 'Flyg Flygbolag Flyg Flygplats Plan',
 'tr-TR': 'Havacılık Havayolu Uçak Havalimanı uçak',
 'zh-CN': '航空 航空公司 机票 飞机场 平面',
 'zh-HK': '航空 航空公司 機票 飛機場 平面',
 'zh-TW': '航空 航空公司 機票 飛機場 平面'}
markets_df['Country/Region'].unique()
array(['Denmark', 'Austria', 'Belgium', 'Switzerland', 'Germany',
       'Australia', 'Canada', 'United Kingdom', 'Indonesia', 'Ireland',
       'India', 'Malaysia', 'New Zealand', 'Republic of the Philippines',
       'Singapore', 'United States', 'English', 'South Africa',
       'Argentina', 'Chile', 'Spain', 'Mexico', 'Spanish', 'Finland',
       'France', 'Italy', 'Hong Kong SAR', 'Taiwan', 'Japan', 'Korea',
       'Netherlands', "People's republic of China", 'Poland', 'Brazil',
       'Russia', 'Sweden', 'Turkey'], dtype=object)
markets_df['Market Code'].apply(lambda s:s.split('-')[1]).unique()
array(['DK', 'AT', 'BE', 'CH', 'DE', 'AU', 'CA', 'GB', 'ID', 'IE', 'IN',
       'MY', 'NZ', 'PH', 'SG', 'US', 'WW', 'XA', 'ZA', 'AR', 'CL', 'ES',
       'MX', 'XL', 'FI', 'FR', 'IT', 'HK', 'TW', 'JP', 'KR', 'NL', 'CN',
       'PL', 'BR', 'RU', 'SE', 'TR'], dtype=object)

!pip install unsync
Collecting unsync
  Downloading https://files.pythonhosted.org/packages/74/f8/80e4d6a6e9f36d7dc09e10522d98277c4576924f9f450100d57c8a80c269/unsync-1.3.2.tar.gz
Building wheels for collected packages: unsync
  Building wheel for unsync (setup.py) ... done
  Created wheel for unsync: filename=unsync-1.3.2-cp37-none-any.whl size=4967 sha256=37cd8ff7214893ecf5d40b7506f02ce149595f8513079064ced64888db744bf6
  Stored in directory: /root/.cache/pip/wheels/b2/31/43/4e734c578ffe46c8af109521ed8db656fcec4e6585bbdaf2a6
Successfully built unsync
Installing collected packages: unsync
Successfully installed unsync-1.3.2
from unsync import unsync
from google_trans_new import google_translator

@unsync
async def async_series_translator(sentence, input_language_iso_alpha_2): 
  return google_translator().translate(
      sentence, 
      lang_tgt='en',
      lang_src = input_language_iso_alpha_2
      )
%%timeit
# def translate_news_df_to_english(news_df:pd.DataFrame)->pd.DataFrame:

input_language_iso_alpha_2 = news_df['market'].unique()[0]
news_df[['name','description']].applymap(lambda sentence: (async_series_translator(sentence,input_language_iso_alpha_2)).result())

# return news_df
# translate_news_df_to_english(news_df)
1 loop, best of 5: 1.28 s per loop
input_language_iso_alpha_2 = news_df['market'].unique()[0]

news_df[['name','description']] =  news_df[['name','description']].applymap(lambda sentence: google_translator().translate(
      sentence, 
      lang_tgt='en',
      lang_src = 'nl'
      ))
def create_news_df(response)
import backoff
import logging
import aiohttp
import asyncio

mkt = 'nl-NL'
keywords = 'Luchtvaart vliegmaatschappij Vluchten Luchthaven Vliegtuig'

logging.getLogger('backoff').addHandler(logging.StreamHandler())

search_url = "https://api.cognitive.microsoft.com/bing/v7.0/news/search"
freshness = 'Week'
category = 'Business'
headers = {"Ocp-Apim-Subscription-Key": os.getenv('BING_NEWS_API_KEY')}

@unsync
@backoff.on_exception(backoff.expo, aiohttp.ClientError, max_time=60)
async def get_bing_news(market_code:str,keywords:str):
  params = {
    "q": keywords,
    'freshness': freshness,
    'count': 10,
    'mkt': mkt,
    # 'category':category,
    # "textDecorations": True, "textFormat": "RAW"
}
  async with aiohttp.ClientSession() as session:
      async with session.get(search_url, headers=headers, params=params) as response:
          return await pd.DataFrame.from_dict(response.json()['value'])[['name', 'url', 'datePublished']]


get_bing_news(mkt,keywords).result()

# def bing_aviation_news(market_keywords:dict):
  
#         search_url = "https://api.cognitive.microsoft.com/bing/v7.0/news/search"
#         freshness = 'Week'
#         category = 'Business'
#         headers = {"Ocp-Apim-Subscription-Key": os.getenv('BING_NEWS_API_KEY')}
#         params = {
#             "q": keywords,
#             'freshness': freshness,
#             'count': 10,
#             'mkt': mkt,
#             # 'category':category,
#             # "textDecorations": True, "textFormat": "RAW"
#         }


#     translator = google_translator()

#     def bing_news_country(keywords, mkt,iso_alpha):
#         try:
#             resp = req.get(search_url, headers=headers, params=params)
#             resp.raise_for_status()
#             df = pd.DataFrame.from_dict(resp.json()['value'])[['name', 'url', 'datePublished']]
#             if mkt.split('-')[0] != 'en':
#                 try:

#                     df['name'] = [translator.translate(title, lang_tgt='en') for title in df['name']]

#                 except Exception as e:
#                     print(e)


#         except:
#             df = pd.DataFrame([['no_news_found', None, None]], columns=['name','url','datePublished'])

#         df['date'] = today.date().strftime(dt_format)
#         df['iso_alpha'] = iso_alpha
#         return df
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-72-a3e56173edd1> in <module>()
     32 
     33 
---> 34 get_bing_news(mkt,keywords).result()
     35 
     36 # def bing_aviation_news(market_keywords:dict):

/usr/local/lib/python3.7/dist-packages/unsync/unsync.py in result(self, *args, **kwargs)
    142             raise asyncio.InvalidStateError("Calling result() in an unsync method is not allowed")
    143         # Wait on the concurrent Future outside unsync.thread
--> 144         return self.concurrent_future.result(*args, **kwargs)
    145 
    146     def done(self):

/usr/lib/python3.7/concurrent/futures/_base.py in result(self, timeout)
    433                 raise CancelledError()
    434             elif self._state == FINISHED:
--> 435                 return self.__get_result()
    436             else:
    437                 raise TimeoutError()

/usr/lib/python3.7/concurrent/futures/_base.py in __get_result(self)
    382     def __get_result(self):
    383         if self._exception:
--> 384             raise self._exception
    385         else:
    386             return self._result

/usr/local/lib/python3.7/dist-packages/backoff/_async.py in retry(*args, **kwargs)
    131 
    132             try:
--> 133                 ret = await target(*args, **kwargs)
    134             except exception as e:
    135                 giveup_result = await giveup(e)

<ipython-input-72-a3e56173edd1> in get_bing_news(market_code, keywords)
     26 }
     27   async with aiohttp.ClientSession() as session:
---> 28       async with session.get(search_url, headers=headers, params=params) as response:
     29           return await pd.DataFrame.from_dict(response.json()['value'])[['name', 'url', 'datePublished']]
     30 

/usr/local/lib/python3.7/dist-packages/aiohttp/client.py in __aenter__(self)
   1115 
   1116     async def __aenter__(self) -> _RetType:
-> 1117         self._resp = await self._coro
   1118         return self._resp
   1119 

/usr/local/lib/python3.7/dist-packages/aiohttp/client.py in _request(self, method, str_or_url, params, data, json, cookies, headers, skip_auto_headers, auth, allow_redirects, max_redirects, compress, chunked, expect100, raise_for_status, read_until_eof, proxy, proxy_auth, timeout, verify_ssl, fingerprint, ssl_context, ssl, proxy_headers, trace_request_ctx, read_bufsize)
    540                     try:
    541                         try:
--> 542                             resp = await req.send(conn)
    543                             try:
    544                                 await resp.start(conn)

/usr/local/lib/python3.7/dist-packages/aiohttp/client_reqrep.py in send(self, conn)
    666             self.method, path, self.version
    667         )
--> 668         await writer.write_headers(status_line, self.headers)
    669 
    670         self._writer = self.loop.create_task(self.write_bytes(writer, conn))

/usr/local/lib/python3.7/dist-packages/aiohttp/http_writer.py in write_headers(self, status_line, headers)
    116         """Write request/response status and headers."""
    117         # status + headers
--> 118         buf = _serialize_headers(status_line, headers)
    119         self._write(buf)
    120 

/usr/local/lib/python3.7/dist-packages/aiohttp/_http_writer.pyx in aiohttp._http_writer._serialize_headers()

/usr/local/lib/python3.7/dist-packages/aiohttp/_http_writer.pyx in aiohttp._http_writer.to_str()

TypeError: Cannot serialize non-str key None
import aiohttp
import asyncio
import time

start_time = time.time()


async def get_pokemon(session, url):
    async with session.get(url) as resp:
        pokemon = await resp.json()
        return pokemon['name']


async def main():

    async with aiohttp.ClientSession() as session:

        tasks = []
        for number in range(1, 151):
            url = f'https://pokeapi.co/api/v2/pokemon/{number}'
            tasks.append(asyncio.ensure_future(get_pokemon(session, url)))

        original_pokemon = await asyncio.gather(*tasks)
        for pokemon in original_pokemon:
            print(pokemon)

asyncio.run(main())
print("--- %s seconds ---" % (time.time() - start_time))
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-86-3b7a977ec65f> in <module>()
     25             print(pokemon)
     26 
---> 27 asyncio.run(main())
     28 print("--- %s seconds ---" % (time.time() - start_time))

/usr/lib/python3.7/asyncio/runners.py in run(main, debug)
     32     if events._get_running_loop() is not None:
     33         raise RuntimeError(
---> 34             "asyncio.run() cannot be called from a running event loop")
     35 
     36     if not coroutines.iscoroutine(main):

RuntimeError: asyncio.run() cannot be called from a running event loop

Why is this so much faster?

In the first version of this code, there was a single event loop which first did 35 queries one after the other, so the next request would only be sent of the previous one was finished. After that all the entries were translated, which are 10 35 2 = 700 calls one after the other. shuffling the order around would not have made this any faster. When using async, all 35 request were dispatched and serviced simultaneously, and for each request when the server responded, the 10 * 2 entries were immediately translated simultaneously as well. With the inclusion of the backoff package, connecting this to async requests and their logging system, by adding just 10 lines of code we made our code 10 times faster, more reliably and easier to maintain down the line.