Python aiohttp websocket server

How to Set Up a Simple Python WebSocket with AioHTTP

A web socket consists of two significant endpoints. One end sends data, and the other end receives data. Take an example of what you can do over the internet. In this case, different nodes/computers are connected to establish a connection that will allow you to send or receive data.

A node can be a server or a client. A client sends a request, and the server will send back a response. These connections between the server and client are achieved through sockets. Thus, a socket acts as the communication endpoint.

This guide will help you understand the socket concept by building client-server socket architecture using the AioHTTP.

AioHTTP is an asynchronous HTTP client/server for Python and asyncio.

The library supports client and HTTP servers, client WebSockets and server WebSockets out of the box without callbacks.

We will build a WebSocket by setting up the client and the server with AioHTTP and sending data between the client and the server.

Table of contents

Prerequisites

Setting up a virtual environment using virtualenv

Virtualenv is a library for creating an independent Python environment. All the libraries we install will be installed locally for our project. First, create a project folder and open it in a command line.

Читайте также:  Media запросы css размеры

Then install virtualenv by running the following command:

If you have pre-installed virtualenv, ensure that your pip is up to date by running the following command from your terminal.

You can check the version of virtualenv installed on your computer by running:

If the virtualenv version is not up to date, run this command to get the latest version installed:

python3 -m pip install --upgrade pip 

This will output the path as the already installed virtualenv. Initialize the environment for this project using virtualenv

Then run Activate to activate this environment by running:

At this point, virtualenv is set up, and we can proceed to the next step.

Installing AioHTTP

To install AioHTTP along with the related modules, run the following command:

pip install aiohttp[speedups] 

The above command will install AioHTTP along with the following packages:

  • Charset-normalizer : A universal charset detector.
  • Aiodns : A DNS resolver for asyncio.
  • Brotli: A data compression libarry.

The modules ensure that the AioHTTP module is as fast as possible when receiving and sending requests.

Building a server with AioHTTP

Create a server.py file in the project folder. We will configure an AioHTTP server here.

Import the web module from the aiohttp library.

The web module will enable us to create a local webserver. First, add a dummy list of todos.

todos = [  "id":"1","title":"Go to the garden">,  "id":"2","title":"Go to the market">,  "id":"3","title":"Prepare dinner">, ] 

The dummy data will be the server’s response when called by the client.

Create a handler function that will send the dummy data.

async def handle(request):  return web.json_response(todos) 

Notice that the handler is an async function returning JSON data.

  • Initialize the application, set up the routes with their listeners, and add scripts for starting a server as shown below:
app = web.Application()  app.add_routes([web.get('/', handle),  web.get('/todos', handle)])  if __name__ == '__main__':  web.run_app(app) 

Here we target the / route and the /todos route, both of which will be handled by the same function. We are also starting our server by running the application instance.

You can start the server by running the following command on your terminal. Before running the command, ensure you are in the project folder that hosts the server.py file.

Your response should be similar to;

The server is up and running, and as you can the server is listening on port 8080 .

Building a client with AioHTTP

Create a client.py file in the project folder. Next, let’s configure the client using the AioHTTP.

Import the aiohttp and asyncio modules.

import aiohttp import asyncio 
  • aiohttp will create a client session that will listen to the server.
  • asyncio will initialize an event loop which the client will listen to.

Create a method for creating the client session and listening to the server.

async def main():  async with aiohttp.ClientSession() as session:  async with session.get('http://localhost:8080/todos') as response:   print(response.status)  print(await response.json()) 

Here we are creating a client session, awaiting the response from our local server, and printing out the status and JSON response from the server.

Initialize an event loop and run the main function in the event loop until completion.

loop = asyncio.get_event_loop() loop.run_until_complete(main()) 

The event loop will only close when the main function has been fully executed.

Sending data between client and server

To send the client and the server data, we need to run the client.py file to receive the dummy data we set from the server.

Open a separate tab of your terminal and run the following command inside the project folder.

The above command will run the main function inside the client.py file, and your response should be comparable to:

200 [    'id':'1',  'title': 'Go to the garden'  >,    'id':'2',  'title': 'Go to the market'  >,    'id':'3',  'title': 'Prepare dinner'  > ] 

Conclusion

We have built a simple WebSocket by setting up an AioHTTP server and client and sending data between them. Check the following resources to learn more about the AioHTTP client and server.

Peer Review Contributions by: Odhiambo Paul

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Websockets example with Python 3.6 aiohttp and asyncio

ftobia/aiohttp-websockets-example

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

aiohttp websocket example

This is a simple example of an asyncio websocket server and client using Python 3.6 and the aiohttp library.

Getting started with Docker

If you don’t already have Docker installed, get it here.

To start the client and the server, run:

docker-compose run --rm aiows-client 

To start the server independently, run:

docker-compose up aiows-server 

You can test to see if the server is running correctly by visiting http://localhost:8080/ in your favorite browser.

Getting started without Docker

Make sure Python 3.6 or greater is installed.

Create a virtual environment and install dependencies:

python3.6 -m venv env source env/bin/activate pip install -r requirements.txt 

In a different terminal, run the client:

source env/bin/activate python client.py 

About

Websockets example with Python 3.6 aiohttp and asyncio

Источник

Оцените статью