Python programming using Trio and Asks

Python programming using Trio and Asks

Do you want to make many requests to lots of web pages in parallel and don’t want to write a lot of code to manage threads in python?

The answer is Trio and Asks packages for Asynchronous programming in python. 

Trio is one of the top 10 packages. It continues to be the star in concurrency programming in python.

Trio makes writing concurrent code simpler. It is relatively best and new when compared to other packages like Asyncio. As a result, we are using trio in our example.

Just remember two keywords async and await, you will write multithreaded code in python with ease.

Asks is similar to requests library in python. It supports,get()head() post()put()delete(),options() and request() functions.

We use get() function in our example below.

Asks package is to run multiple HTTP requests with Trio asynchronously.

Installation

Installing required python package using pip install

Now, we have trio and asks packages ready in the system. Let us code!

Use case: Movies playing in NewYork 

Let us see write code to pull data for movies playing in NewYork.

Using Gracenote web API to get theater and movie details.

We are using asks to make non-blocking HTTP requests to Gracenote web API and trio to process many movies in parallel

Step1: Get a list of all movie theaters in NewYork using python code

import trio
import asks
BASE_URL = "http://data.tmsapi.com/v1.1/theatres"
API_KEY =  '<API KEY>'
async def get_theatres_nyc(zip_code):
    '''Get theatres data from Gracenote'''
    result = await asks.get(BASE_URL, params={'zip': str(zip_code),'api_key':API_KEY})
    return result.json()


asks.init(trio) results_list = trio.run(get_theatres_nyc,10153) print(results_list)

  • You must specify what event loop asks should use after importing asks, and at some point, before you run any code that uses asks.
  • Here asks is using trio so we have asks.init(trio)
  • The entry point is trio.run() by passing the function name and parameters to pass. 
  • Variable results_list contains complete theaters details which will be used in Step 2.
  • Results sample is shown below

Step2: Pull movies data for each theater in parallel using simple code.

import trio
import asks

BASE_URL = "http://data.tmsapi.com/v1.1/theatres" API_KEY =  '<API KEY>'

async def get_movie_details(theatre):     '''get movie and showtime data from Gracenote and update result'''     theatre_id_num = theatre['theatreId']     url = BASE_URL+'/'+str(theatre_id)+'/showings'     result = await asks.get(url, params={'startDate': TODAY,'api_key':API_KEY})     theatre['movies'] = result

async def movie_showtime_details(results_list):     '''function to create nursery for each movie'''     async with trio.open_nursery() as nursery:     for theatre in results_list:         if theatre.get('theatreId'):             nursery.start_soon(get_movie_details, theatre)     return results_list

asks.init(trio) #results_list is from step 1 code results_list = trio.run(movie_showtime_details, results_list) print(results_list)

  • Open a trio nursery, we are starting a trio task for each movie.
  • asks.get() is fetching movie data in parallel and updating to results_list variable.
  • Await keyword is used to call the function concurrently.
  • Most importantly when await is used, trio will take care of thread wait and send back the results.

Get theaters, movies and showtime details in the rate of 20 requests/second. Find the complete source code in the GitHub repository:

View on GithHub

Originally published by Manasa MB at dunebook.com

=================================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Complete Python Bootcamp: Go from zero to hero in Python 3

☞ Python for Time Series Data Analysis

☞ Python Programming For Beginners From Scratch

☞ Python Network Programming | Network Apps & Hacking Tools

☞ Intro To SQLite Databases for Python Programming

☞ Ethical Hacking With Python, JavaScript and Kali Linux

☞ Beginner’s guide on Python: Learn python from scratch! (New)

☞ Python for Beginners: Complete Python Programming

python

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Python Tricks Every Developer Should Know

In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.

How to Remove all Duplicate Files on your Drive via Python

Today you're going to learn how to use Python programming in a way that can ultimately save a lot of space on your drive by removing all the duplicates. We gonna use Python OS remove( ) method to remove the duplicates on our drive. Well, that's simple you just call remove ( ) with a parameter of the name of the file you wanna remove done.

Basic Data Types in Python | Python Web Development For Beginners

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

How To Compare Tesla and Ford Company By Using Magic Methods in Python

Magic Methods are the special methods which gives us the ability to access built in syntactical features such as ‘<’, ‘>’, ‘==’, ‘+’ etc.. You must have worked with such methods without knowing them to be as magic methods. Magic methods can be identified with their names which start with __ and ends with __ like __init__, __call__, __str__ etc. These methods are also called Dunder Methods, because of their name starting and ending with Double Underscore (Dunder).

The Basics of Python OS Module

The OS module is a python module that provides the interface for interacting with the underlying operating system that Python is running.