logo
Tags down

shadow

Asyncio tasks stopping on await


By : amrtsh
Date : September 10 2020, 01:00 PM
will help you I don't see the details of how you are really running the code, but I'd guess you're not giving the task you create (with asyncio.create_task) its turn for execution.
await registerit(arg1,arg0) works, because when you use await you switch the current execution context to another coroutine, which might just turn out to be the one that you've just initiated with await. Await creates that new coroutine AND waits for it to finish and get its output.
code :
# test.py
# python 3.8.1

import asyncio
import aiohttp


async def non_working_solution():
    task = asyncio.create_task(registerit())


async def working_solution():
    await registerit()


async def registerit():
    async with aiohttp.ClientSession() as session:
        url="https://google.com"
        headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'}
        response = await session.get(url, headers=headers)
        print(response)


async def main():
    print('Running working solution')
    await working_solution()
    print('Running NON-working solution')
    await non_working_solution()

    # THE FIX
    # =======
    time_to_sleep = 5
    print('Waiting for', time_to_sleep, 'seconds for the output of the non-working solution')
    await asyncio.sleep(time_to_sleep)
    # =======


if __name__ == '__main__':
    asyncio.run(main())


Share : facebook icon twitter icon

asyncio - await coroutine more than once (periodic tasks)


By : dharm
Date : March 29 2020, 07:55 AM
hope this fix your issue It seems you are confusing async functions (coroutine functions) with coroutines - values that these async functions produce.
Consider this async function:
code :
async def sample():
    await asyncio.sleep(3.14)
while True:
    await _async_func()
    await asyncio.sleep(_interval)

Python asyncio Await Tasks


By : Karavay
Date : March 29 2020, 07:55 AM
it helps some times Because main1 creates all tasks at the same time and then awaits all of them after they are created. Everything happens in parallel. And so total time is maximum of all times which is 2s.
While main2 creates a new task only after previous one finishes. Everything happens sequentially. So total time is sum of all times which (judging from code) should be 30s.
code :
max(1,2) + ... + max(1,2) [10 times] = 20

Python asyncio confused about await and tasks


By : user2797935
Date : March 29 2020, 07:55 AM
this will help When you encapsulate a coroutine in a Task (or Future) object the coroutine is ready to work, so when the event loop start running on the first await, both task1 and task2 are running.
Trying to make it clearer, to execute a coroutine you need two things:

I'm using asyncio but async function is blocking other async functions with await asyncio.sleep(5)


By : user2904598
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , I've include asyncio to asynchronous my code in my library twbotlib (https://github.com/truedl/twbotlib). , The loop for line in data: is blocking you code.

Django Channels send group message from Celery task. Asyncio event loop stopping before all async tasks finished


By : user3253023
Date : March 29 2020, 07:55 AM
this will help In the end I couldn't solve the problem and choose an alternative solution using a Channels AsyncHttpConsumer to send the group message. It's not optimal but it works and keeps the workflow in the Channels library.
Consumer:
code :
class celeryMessageConsumer(AsyncHttpConsumer):

async def handle(self, body):
    # send response
    await self.send_response(200, b"Recieved Loud and Clear", headers=[
        (b"Content-Type", b"text/plain"),
    ])
    # formating url encoded string into json
    body_data = urllib.parse.unquote_plus(body.decode("utf-8"))
    body_data = json.loads(body_data)
    id = body_data['data']['id']

    await self.channel_layer.group_send(
        f"group_{id}",
        {
            'type': 'propergate.data',
            'data': body_data['data']
        }
    )
application = ProtocolTypeRouter({
    'websocket': AuthMiddlewareStack(
        URLRouter(
            myApp.routing.websocket_urlpatterns
        )
    ),
    'http': URLRouter([
        path("celeryToTemplate/", consumers.celeryMessageConsumer),
        re_path('genericMyAppPath/.*', AsgiHandler),
    ]),
})
data = json.dumps({'id': id, 'status': status})
response = internal_post_request('http://genericAddress/celeryToTemplate/', data)
if response.status_code == 200:
    # phew
    pass
else:
    # whoops
    pass
def internal_post_request(request_url, payload):
    headers={
        'Content-Type': 'application/json'
    }
    response = requests.post(request_url, data=payload, headers=headers)
    return response
Related Posts Related Posts :
  • Why is the interpreter call the variable i a local variable
  • Passing multiple list in a function as *args gives a None result
  • Getting a tclerror with PhotoIMage
  • How to efficiently disaggregate data from?
  • Group by the dates to weeks
  • Accuracy problems in estimating pi using Machin's method
  • Printing a list method return None
  • how to make scatter plot of two columns and divide x_axis in 3 column f1,f2,and f3
  • Can I install python 3.7 in ubuntu 18.04 without having python 3.6 in the system?
  • Applying a function to every cell of dataframes
  • Cant install allennlp with pip on mac
  • ModuleNotFoundError: No module named 'virtualenv' Exiting due to failure, even after virtual environment is successfully
  • How to fix " 'int' object is not subscriptable" on this code
  • question about custom sorting using key argument in sorted()
  • Python3-tk is already installed but python3.7 can't find module tkinter
  • Pickle messing up text
  • How to install torch==0.3.1 in python=3.6
  • Tkinter Checkbuttons' values won't change
  • How to call asynchronous functions without expecting returns from them?
  • Unable to convert string to date (Portuguese locale)
  • Use textract on PDF file located on Google Cloud Storage
  • How to fix 'Can't open libmsodbcsql-17.3.so.1.1'
  • Using the join method in python - confusing error
  • Pandas Dataframe to .csv file
  • Tell if an object's attribute has been used
  • Read files from Cloud Storage having definite prefix but random postfix
  • Extract Button link text from a website python selenium
  • Reverse string, but not integers
  • TkFiledialog.askopenfilename() launches a window for "save as" in windows 10
  • Printing last 3 lines of a .csv file
  • I can't install python packages by using pip3 on alpine
  • Setting up a Flask app that uses headed Selenium on a Ubuntu 18.04 LTS Server
  • How to convert month name to month number in a timeseries in DataFrame?
  • Why does pandas.where() returning 'None'
  • How to extract matching keywords from two columns in a pandas dataframe?
  • python converting a List of Tuples into a Dict with external keys
  • How to fix ModuleNotFoundError: No module named 'pip._internal' with python source code installation
  • Pytorch RuntimeError: Expected tensor for argument #1 'indices' to have scalar type Long; but got CUDAType instead
  • Covert a dataframe into a matrix form
  • i am webscraping with bs4 and the urls wont show up
  • docker build: Returned a non-zero code: 5
  • Pandas read_csv from FileStorage in Flask
  • How do I add elements of a set and print their sum?
  • Is there a way to add a column to a geopandas dataframe using a single value geoseries?
  • Issue with appending to an array
  • no module named "tensorflow.python.platform" when importing tensorflow || tflearn on python shell
  • Accesing "Next" page with scrapy rules
  • How to take all combination of a pandas dataframe (choosing 2 at a time) and make a new dataframe with each two combinat
  • Connecting the missing pixels
  • Returns Nothing [] from Google + API using Python
  • pd.DataFrame: adding values in specific locations
  • Validating phone numbers in python using RE
  • How to fetch all data of solr which contains 40k rows into csv?
  • Inheritance of modules in Python?
  • ModuleNotFoundError: No module named 'frontend'
  • Only One Pod is consuming all the computing resource although specified the limits and requests resources in pod templat
  • IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Python number
  • Scraping 'next' page after finishing in the main one using Rules
  • Add custom headers to SOAP request using zeep.Client Python
  • It the any proper way how to take a two byte elemetns from list, concat them, and convert them to integer
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk