How to save a session when using asynchronous websites?

I have this code for interacting with apseries api using python async and websokets :

 #!/usr/bin/env python3 import sys, json import asyncio from websockets import connect class AsyncWebsocket(): async def __aenter__(self): self._conn = connect('wss://ws.myws.com/v2') self.websocket = await self._conn.__aenter__() return self async def __aexit__(self, *args, **kwargs): await self._conn.__aexit__(*args, **kwargs) async def send(self, message): await self.websocket.send(message) async def receive(self): return await self.websocket.recv() class mtest(): def __init__(self, api_token): self.aws = AsyncWebsocket() self.loop = asyncio.get_event_loop() self.api_token = api_token self.authorize() def authorize(self): jdata = self.__async_exec({ 'authorize': self.api_token }) try: print (jdata['email']) ret = True except: ret = False return ret def sendtest(self): jdata = self.__async_exec({ "hello": 1 }) print (jdata) def __async_exec(self, jdata): try: ret = json.loads(self.loop.run_until_complete(self.__async_send_recieve(jdata))) except: ret = None return ret async def __async_send_recieve(self, jdata): async with self.aws: await self.aws.send(json.dumps(jdata)) return await self.aws.receive() 

So I have main.py:

 from webclass import * a = mtest('12341234') print (a.sendtest()) 

The problem is that it does not save an authorized session, so this is the output:

 root@ubupc1 :/home/dinocob# python3 test.py asd@gmail.com {'error': {'message': 'Please log in.', 'code': 'AuthorizationRequired'}} 

As you can see, the login works fine, but the session does not match when calling and sending the hello in sendtest function.

  • Where is the session destroyed?
  • How can I save it (without changing my class structure)?
+5
source share
2 answers

I think the problem may be in the context of the_manager or with statement.

 async def __async_send_recieve(self, jdata): async with self.aws: await self.aws.send(json.dumps(jdata)) return await self.aws.receive() 

When you call "c", the context should be reproduced as follows (with better exception handling and all the benefits of context managers, so you can present the __async_send_recieve stream as:

  self.aws.__aenter__() self.aws.send(data) self.aws.receive() self.aws.__aexit__() 

To prove this theory, add a print statement to the __aenter__ and __aexit__ , and you can better visualize the context manager flow.

The correction will consist of re-authorization in each request. But I assume that you want your test class to control the context used to communicate with the remote server. (my asynchronous syntax may be a little wrong here, but conceptually with context managers):

 class Mtest(): def __init__(self, ...): ... def __enter__(self,): self.authorize() def __exit__(self): self.deauthorize() async def make_async_request(self, data): await self.aws.send(json.dumps(data)) return await self.aws.receive() with Mtest(api_key) as m: m.make_async_request({'test_data': 'dummy_test_data'}) m.make_async_request({'more_data': 'more_mock_data'}) 
+1
source

From your code, it seems that the server remembers the login status for each network connection, so you do not need to do anything on the client side.

Where is the session destroyed?

The session is being destroyed on the server side.

How can I save it?

Fix server error?

0
source

Source: https://habr.com/ru/post/1263891/


All Articles