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

How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?