aiohttp - How to save a persistent session in class namespaceHow can I wait for an object's __del__ to finish before the async loop closes?How to reset/clear aiohttp sessionKeep aiohttp session aliveInstances constantly timing out with aiohttpHow to manage a single aiohttp.ClientSession?aiohttp how to save a persistent ClientSession in a class?Multiple aiohttp sessionspython asyncio/aiohttp sharing globals across projectTypeError: _request() got an unexpected keyword argument 'cookies' (aiohttp)RuntimeError with aiohttp persistent sessionHow many aiohttp sessions for multiple API endpoints?

Can a USB hub be used to access a drive from two devices?

My professor has told me he will be the corresponding author. Will it hurt my future career?

How predictable is $RANDOM really?

Will Jimmy fall off his platform?

What is the fundamental difference between catching whales and hunting other animals?

Park the computer

I'm feeling like my character doesn't fit the campaign

How do I talk to my wife about unrealistic expectations?

Array or vector? Two dimensional array or matrix?

White's last move?

When is one 'Ready' to make Original Contributions to Mathematics?

Did William Shakespeare hide things in his writings?

Soda water first stored in refrigerator and then at room temperature

Multi-user CRUD: Valid, Problem, or Error?

What was the significance of Spider-Man: Far From Home being an MCU Phase 3 film instead of a Phase 4 film?

How important is it for multiple POVs to run chronologically?

Pressure in giant ball of water floating in space

As a supervisor, what feedback would you expect from a PhD who quits?

Taking my Ph.D. advisor out for dinner after graduation

How do resistors generate different heat if we make the current fixed and changed the voltage and resistance? Notice the flow of charge is constant

Why do airports remove/realign runways?

What's the big deal about the Nazgûl losing their horses?

How to get the speed of my spaceship?

Is a lowball salary then a part-time offer standard Japanese employment negotiations?



aiohttp - How to save a persistent session in class namespace


How can I wait for an object's __del__ to finish before the async loop closes?How to reset/clear aiohttp sessionKeep aiohttp session aliveInstances constantly timing out with aiohttpHow to manage a single aiohttp.ClientSession?aiohttp how to save a persistent ClientSession in a class?Multiple aiohttp sessionspython asyncio/aiohttp sharing globals across projectTypeError: _request() got an unexpected keyword argument 'cookies' (aiohttp)RuntimeError with aiohttp persistent sessionHow many aiohttp sessions for multiple API endpoints?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I am trying to use aiohttp in one of my projects and struggling to figure out how to create a persistent aiohttp.ClientSession object. I have gone through the official aiohttp documentation but did not find it help in this context.



I have looked through other online forums and noticed that a lot has changed ever since aiohttp was created. In some examples on github, the aiohttp author is shown to be creating a ClientSession outside a coroutine functions (i.e. class Session: def __init__(self): self.session = aiohttp.ClientSession()). I also found that one should not create a ClientSession outside coroutine.



I have tried the following:



class Session:
def __init__(self):
self._session = None

async def create_session(self):
self._session = aiohttp.ClientSession()

async fetch(self, url):
if self._session is None:
await self.create_session()
async with self._session.get(url) as resp:
return await resp.text()


I am getting a lot of warning about UnclosedSession and connector. I also frequently get SSLError. I also noticed that 2 out of three calls gets hung and I have to CTRL+C to kill it.



With requests I can simply initialize the session object in __init__, but it's not as simple as this with aiohttp.



I do not see any issues if I use the following (which is what I see as example all over the place) but unfortunately here I end up creating ClientSession with every request.



def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
return await resp.text()


I can wrap aiohttp.ClientSession() in another function and use that as context-manager, but then too I would end up creating a new session object every time I call the wrapper function. I am trying to figure how to save a aiohttp.ClientSession in class namespace and reuse it.



Any help would be greatly appreciated.










share|improve this question






















  • This might help stackoverflow.com/questions/54770360/…

    – antfuentes87
    Mar 26 at 2:26

















0















I am trying to use aiohttp in one of my projects and struggling to figure out how to create a persistent aiohttp.ClientSession object. I have gone through the official aiohttp documentation but did not find it help in this context.



I have looked through other online forums and noticed that a lot has changed ever since aiohttp was created. In some examples on github, the aiohttp author is shown to be creating a ClientSession outside a coroutine functions (i.e. class Session: def __init__(self): self.session = aiohttp.ClientSession()). I also found that one should not create a ClientSession outside coroutine.



I have tried the following:



class Session:
def __init__(self):
self._session = None

async def create_session(self):
self._session = aiohttp.ClientSession()

async fetch(self, url):
if self._session is None:
await self.create_session()
async with self._session.get(url) as resp:
return await resp.text()


I am getting a lot of warning about UnclosedSession and connector. I also frequently get SSLError. I also noticed that 2 out of three calls gets hung and I have to CTRL+C to kill it.



With requests I can simply initialize the session object in __init__, but it's not as simple as this with aiohttp.



I do not see any issues if I use the following (which is what I see as example all over the place) but unfortunately here I end up creating ClientSession with every request.



def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
return await resp.text()


I can wrap aiohttp.ClientSession() in another function and use that as context-manager, but then too I would end up creating a new session object every time I call the wrapper function. I am trying to figure how to save a aiohttp.ClientSession in class namespace and reuse it.



Any help would be greatly appreciated.










share|improve this question






















  • This might help stackoverflow.com/questions/54770360/…

    – antfuentes87
    Mar 26 at 2:26













0












0








0








I am trying to use aiohttp in one of my projects and struggling to figure out how to create a persistent aiohttp.ClientSession object. I have gone through the official aiohttp documentation but did not find it help in this context.



I have looked through other online forums and noticed that a lot has changed ever since aiohttp was created. In some examples on github, the aiohttp author is shown to be creating a ClientSession outside a coroutine functions (i.e. class Session: def __init__(self): self.session = aiohttp.ClientSession()). I also found that one should not create a ClientSession outside coroutine.



I have tried the following:



class Session:
def __init__(self):
self._session = None

async def create_session(self):
self._session = aiohttp.ClientSession()

async fetch(self, url):
if self._session is None:
await self.create_session()
async with self._session.get(url) as resp:
return await resp.text()


I am getting a lot of warning about UnclosedSession and connector. I also frequently get SSLError. I also noticed that 2 out of three calls gets hung and I have to CTRL+C to kill it.



With requests I can simply initialize the session object in __init__, but it's not as simple as this with aiohttp.



I do not see any issues if I use the following (which is what I see as example all over the place) but unfortunately here I end up creating ClientSession with every request.



def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
return await resp.text()


I can wrap aiohttp.ClientSession() in another function and use that as context-manager, but then too I would end up creating a new session object every time I call the wrapper function. I am trying to figure how to save a aiohttp.ClientSession in class namespace and reuse it.



Any help would be greatly appreciated.










share|improve this question














I am trying to use aiohttp in one of my projects and struggling to figure out how to create a persistent aiohttp.ClientSession object. I have gone through the official aiohttp documentation but did not find it help in this context.



I have looked through other online forums and noticed that a lot has changed ever since aiohttp was created. In some examples on github, the aiohttp author is shown to be creating a ClientSession outside a coroutine functions (i.e. class Session: def __init__(self): self.session = aiohttp.ClientSession()). I also found that one should not create a ClientSession outside coroutine.



I have tried the following:



class Session:
def __init__(self):
self._session = None

async def create_session(self):
self._session = aiohttp.ClientSession()

async fetch(self, url):
if self._session is None:
await self.create_session()
async with self._session.get(url) as resp:
return await resp.text()


I am getting a lot of warning about UnclosedSession and connector. I also frequently get SSLError. I also noticed that 2 out of three calls gets hung and I have to CTRL+C to kill it.



With requests I can simply initialize the session object in __init__, but it's not as simple as this with aiohttp.



I do not see any issues if I use the following (which is what I see as example all over the place) but unfortunately here I end up creating ClientSession with every request.



def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
return await resp.text()


I can wrap aiohttp.ClientSession() in another function and use that as context-manager, but then too I would end up creating a new session object every time I call the wrapper function. I am trying to figure how to save a aiohttp.ClientSession in class namespace and reuse it.



Any help would be greatly appreciated.







python-3.7 aiohttp






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 25 at 20:45









user6037143user6037143

12311 bronze badges




12311 bronze badges












  • This might help stackoverflow.com/questions/54770360/…

    – antfuentes87
    Mar 26 at 2:26

















  • This might help stackoverflow.com/questions/54770360/…

    – antfuentes87
    Mar 26 at 2:26
















This might help stackoverflow.com/questions/54770360/…

– antfuentes87
Mar 26 at 2:26





This might help stackoverflow.com/questions/54770360/…

– antfuentes87
Mar 26 at 2:26












1 Answer
1






active

oldest

votes


















0














Here is working example:



from aiohttp import ClientSession, TCPConnector
import asyncio


class CS:

_cs: ClientSession

def __init__(self):
self._cs = ClientSession(connector=TCPConnector(verify_ssl=False))

async def get(self, url):
async with self._cs.get(url) as resp:
return await resp.text()

async def close(self):
await self._cs.close()


async def func():
cs = CS()
print(await cs.get('https://google.com'))
await cs.close() # you must close session


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





share|improve this answer

























  • Which aiohttp version did you test with? I'd tried the same code (without explicitly passing the TCPConnector) but I was getting RuntimeError: Timeout context manager should be used inside a task. Moreover, creating ClientSession outside coroutine is considered dangerous and is not recommended.

    – user6037143
    Mar 26 at 10:55











  • @user6037143 I'm using last aiohttp version (3.5.4, python 3.7)

    – Yurii Kramarenko
    Mar 26 at 15:33












  • I have the same setup, but I get RuntimeError: Timeout context manager should be used inside a task when I get method. Also, the docs and faqs mention that creation of ClientSession outside coroutine is dangerous

    – user6037143
    Mar 26 at 16:46











  • If I call asyncio.run(func()), I get RuntimeError: Timeout context manager should be used inside a task. If I use loop = asyncio.get_event_loop(); loop.run_until_complete(func()) it works.

    – user6037143
    Mar 26 at 16:51











  • @user6037143 example has been changed

    – Yurii Kramarenko
    Mar 27 at 17:58










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55346145%2faiohttp-how-to-save-a-persistent-session-in-class-namespace%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














Here is working example:



from aiohttp import ClientSession, TCPConnector
import asyncio


class CS:

_cs: ClientSession

def __init__(self):
self._cs = ClientSession(connector=TCPConnector(verify_ssl=False))

async def get(self, url):
async with self._cs.get(url) as resp:
return await resp.text()

async def close(self):
await self._cs.close()


async def func():
cs = CS()
print(await cs.get('https://google.com'))
await cs.close() # you must close session


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





share|improve this answer

























  • Which aiohttp version did you test with? I'd tried the same code (without explicitly passing the TCPConnector) but I was getting RuntimeError: Timeout context manager should be used inside a task. Moreover, creating ClientSession outside coroutine is considered dangerous and is not recommended.

    – user6037143
    Mar 26 at 10:55











  • @user6037143 I'm using last aiohttp version (3.5.4, python 3.7)

    – Yurii Kramarenko
    Mar 26 at 15:33












  • I have the same setup, but I get RuntimeError: Timeout context manager should be used inside a task when I get method. Also, the docs and faqs mention that creation of ClientSession outside coroutine is dangerous

    – user6037143
    Mar 26 at 16:46











  • If I call asyncio.run(func()), I get RuntimeError: Timeout context manager should be used inside a task. If I use loop = asyncio.get_event_loop(); loop.run_until_complete(func()) it works.

    – user6037143
    Mar 26 at 16:51











  • @user6037143 example has been changed

    – Yurii Kramarenko
    Mar 27 at 17:58















0














Here is working example:



from aiohttp import ClientSession, TCPConnector
import asyncio


class CS:

_cs: ClientSession

def __init__(self):
self._cs = ClientSession(connector=TCPConnector(verify_ssl=False))

async def get(self, url):
async with self._cs.get(url) as resp:
return await resp.text()

async def close(self):
await self._cs.close()


async def func():
cs = CS()
print(await cs.get('https://google.com'))
await cs.close() # you must close session


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





share|improve this answer

























  • Which aiohttp version did you test with? I'd tried the same code (without explicitly passing the TCPConnector) but I was getting RuntimeError: Timeout context manager should be used inside a task. Moreover, creating ClientSession outside coroutine is considered dangerous and is not recommended.

    – user6037143
    Mar 26 at 10:55











  • @user6037143 I'm using last aiohttp version (3.5.4, python 3.7)

    – Yurii Kramarenko
    Mar 26 at 15:33












  • I have the same setup, but I get RuntimeError: Timeout context manager should be used inside a task when I get method. Also, the docs and faqs mention that creation of ClientSession outside coroutine is dangerous

    – user6037143
    Mar 26 at 16:46











  • If I call asyncio.run(func()), I get RuntimeError: Timeout context manager should be used inside a task. If I use loop = asyncio.get_event_loop(); loop.run_until_complete(func()) it works.

    – user6037143
    Mar 26 at 16:51











  • @user6037143 example has been changed

    – Yurii Kramarenko
    Mar 27 at 17:58













0












0








0







Here is working example:



from aiohttp import ClientSession, TCPConnector
import asyncio


class CS:

_cs: ClientSession

def __init__(self):
self._cs = ClientSession(connector=TCPConnector(verify_ssl=False))

async def get(self, url):
async with self._cs.get(url) as resp:
return await resp.text()

async def close(self):
await self._cs.close()


async def func():
cs = CS()
print(await cs.get('https://google.com'))
await cs.close() # you must close session


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





share|improve this answer















Here is working example:



from aiohttp import ClientSession, TCPConnector
import asyncio


class CS:

_cs: ClientSession

def __init__(self):
self._cs = ClientSession(connector=TCPConnector(verify_ssl=False))

async def get(self, url):
async with self._cs.get(url) as resp:
return await resp.text()

async def close(self):
await self._cs.close()


async def func():
cs = CS()
print(await cs.get('https://google.com'))
await cs.close() # you must close session


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






share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 27 at 10:37

























answered Mar 26 at 10:39









Yurii KramarenkoYurii Kramarenko

5312 silver badges12 bronze badges




5312 silver badges12 bronze badges












  • Which aiohttp version did you test with? I'd tried the same code (without explicitly passing the TCPConnector) but I was getting RuntimeError: Timeout context manager should be used inside a task. Moreover, creating ClientSession outside coroutine is considered dangerous and is not recommended.

    – user6037143
    Mar 26 at 10:55











  • @user6037143 I'm using last aiohttp version (3.5.4, python 3.7)

    – Yurii Kramarenko
    Mar 26 at 15:33












  • I have the same setup, but I get RuntimeError: Timeout context manager should be used inside a task when I get method. Also, the docs and faqs mention that creation of ClientSession outside coroutine is dangerous

    – user6037143
    Mar 26 at 16:46











  • If I call asyncio.run(func()), I get RuntimeError: Timeout context manager should be used inside a task. If I use loop = asyncio.get_event_loop(); loop.run_until_complete(func()) it works.

    – user6037143
    Mar 26 at 16:51











  • @user6037143 example has been changed

    – Yurii Kramarenko
    Mar 27 at 17:58

















  • Which aiohttp version did you test with? I'd tried the same code (without explicitly passing the TCPConnector) but I was getting RuntimeError: Timeout context manager should be used inside a task. Moreover, creating ClientSession outside coroutine is considered dangerous and is not recommended.

    – user6037143
    Mar 26 at 10:55











  • @user6037143 I'm using last aiohttp version (3.5.4, python 3.7)

    – Yurii Kramarenko
    Mar 26 at 15:33












  • I have the same setup, but I get RuntimeError: Timeout context manager should be used inside a task when I get method. Also, the docs and faqs mention that creation of ClientSession outside coroutine is dangerous

    – user6037143
    Mar 26 at 16:46











  • If I call asyncio.run(func()), I get RuntimeError: Timeout context manager should be used inside a task. If I use loop = asyncio.get_event_loop(); loop.run_until_complete(func()) it works.

    – user6037143
    Mar 26 at 16:51











  • @user6037143 example has been changed

    – Yurii Kramarenko
    Mar 27 at 17:58
















Which aiohttp version did you test with? I'd tried the same code (without explicitly passing the TCPConnector) but I was getting RuntimeError: Timeout context manager should be used inside a task. Moreover, creating ClientSession outside coroutine is considered dangerous and is not recommended.

– user6037143
Mar 26 at 10:55





Which aiohttp version did you test with? I'd tried the same code (without explicitly passing the TCPConnector) but I was getting RuntimeError: Timeout context manager should be used inside a task. Moreover, creating ClientSession outside coroutine is considered dangerous and is not recommended.

– user6037143
Mar 26 at 10:55













@user6037143 I'm using last aiohttp version (3.5.4, python 3.7)

– Yurii Kramarenko
Mar 26 at 15:33






@user6037143 I'm using last aiohttp version (3.5.4, python 3.7)

– Yurii Kramarenko
Mar 26 at 15:33














I have the same setup, but I get RuntimeError: Timeout context manager should be used inside a task when I get method. Also, the docs and faqs mention that creation of ClientSession outside coroutine is dangerous

– user6037143
Mar 26 at 16:46





I have the same setup, but I get RuntimeError: Timeout context manager should be used inside a task when I get method. Also, the docs and faqs mention that creation of ClientSession outside coroutine is dangerous

– user6037143
Mar 26 at 16:46













If I call asyncio.run(func()), I get RuntimeError: Timeout context manager should be used inside a task. If I use loop = asyncio.get_event_loop(); loop.run_until_complete(func()) it works.

– user6037143
Mar 26 at 16:51





If I call asyncio.run(func()), I get RuntimeError: Timeout context manager should be used inside a task. If I use loop = asyncio.get_event_loop(); loop.run_until_complete(func()) it works.

– user6037143
Mar 26 at 16:51













@user6037143 example has been changed

– Yurii Kramarenko
Mar 27 at 17:58





@user6037143 example has been changed

– Yurii Kramarenko
Mar 27 at 17:58








Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55346145%2faiohttp-how-to-save-a-persistent-session-in-class-namespace%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현