My async function not work in python 3.8.13 - asynchronous

import asyncio
async def_1():
pass
async def_2(number):
for i in range(number):
globals['example_{}'.format(i)] = def_1()
asyncio.run(def_2)
My work file is .ipynb and python3.8.13 and use visual basic studio.
my code's structure is that. I want to work as ASynchronous function, but code didn't work.
so I want to know what I do to work this code.

Related

Task doesn't run in GUI, but OK in console

I am using a third-party library. That library contains an object with an async method that returns Task<SomeStuff>. I am wrapping that object and others into my own class. My wrapper method is also async and has the same return. Calling the wrapper method works fine in my unit tests and a console app. However, it doesn't work in my WPF GUI app. I have tried different methods for invoking in my GUI but nothing works.
In my unit tests, I invoke with GetAwaiter().GetResult(). However, in my GUI this never returns.
I tried using Start() but that results in an error: "Start may not be called on a promise-style task."
What do I need to do to make this work in my GUI?
// Foo() returns Task<SomeStuff>
// this works fine in unit test as well as console app, but not in GUI (WPF)
SomeStuff stuff = myWrapper.Foo().GetAwaiter().GetResult();
// this results in error: "Start may not be called on a promise-style task."
Task<SomeStuff> myTask = myWrapper.Foo();
myTask.Start();
myTask.Wait();
There is a very good discussion of various approaches to my issue here: [https://stackoverflow.com/questions/5095183/how-would-i-run-an-async-taskt-method-synchronously?rq=1][1]
For the moment I resolved my issue as below. I shall re-read the post from the link and perhaps refine my approach.
Task<SomeStuff> task = Task.Run(() => myWrapper.Foo());
task.Wait();
SomeStuff stuff = task.Result;

Django: SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async

I use Django 3.0.6 and Jupyter notebook running with shell_plus --notebook.
I try run queryset:
User.objects.all()
But return this error SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
I try this command
from asgiref.sync import sync_to_async
users = sync_to_async(User.objects.all())
for user in users:
print(user)
TypeError: 'SyncToAsync' object is not iterable
The solution of Django documentation
os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" in settings.py is the unique solution?
The error occurs because Jupyter notebooks has a running event loop.
From documentation
If you try to run any of these parts from a thread where there is a running event loop, you will get a SynchronousOnlyOperation error. Note that you don’t have to be inside an async function directly to have this error occur. If you have called a synchronous function directly from an asynchronous function without going through something like sync_to_async() or a threadpool, then it can also occur, as your code is still running in an asynchronous context.
If you encounter this error, you should fix your code to not call the offending code from an async context; instead, write your code that talks to async-unsafe in its own, synchronous function, and call that using asgiref.sync.sync_to_async(), or any other preferred way of running synchronous code in its own thread.
If you are absolutely in dire need to run this code from an asynchronous context - for example, it is being forced on you by an external environment, and you are sure there is no chance of it being run concurrently (e.g. you are in a Jupyter notebook), then you can disable the warning with the DJANGO_ALLOW_ASYNC_UNSAFE environment variable.
As the question is specific to jupyter notebook environment following is a valid solution.
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'rest.settings')
os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"
django.setup()
from users.models import User
User.objects.all()
One need to however by wary and not use it in production environment as per documentation warnings.
sync_to_async takes a callable, not the result. Instead, you want this:
from asgiref.sync import sync_to_async
users = sync_to_async(User.objects.all)()
for user in users:
print(user)
You can also put the call(s) you want to wrap in a decorated function:
from asgiref.sync import sync_to_async
#sync_to_async
def get_all_users():
return User.objects.all()
for user in await get_all_users():
print(user)
Note that this must be used from an async context, so a full example would look like:
from asgiref.sync import sync_to_async
#sync_to_async
def get_all_users():
return User.objects.all()
async def foo(request):
for user in await get_all_users():
print(user)
Full documentation
You cant pass around a Queryset between sync and async functions since it is lazy.
You need to evaluate it inside a async context.
Like this:
from django.contrib.auth.models import User
from asgiref.sync import sync_to_async
import asyncio
#sync_to_async
def get_users():
return list(
User.objects.all()
)
async def user_loop():
results = await get_users()
for r in results:
print(r.username)
loop = asyncio.get_event_loop()
loop.run_until_complete(user_loop())
From documentation
If you're trying to run any none-async parts of Django like ORM, you will get a SynchronousOnlyOperation error. Note that you don’t have to be inside an async function directly to have this error occur. If you have called a sync function directly from an async function, without using sync_to_async() or similar, then it can also occur. This is because your code is still running in a thread with an active event loop, even though it may not be declared as an async code.
You should use:
from asgiref.sync import sync_to_async
def _get_blog(pk):
return Blog.objects.get(pk=pk)
get_blog = await sync_to_async(_get_blog, thread_sensitive=True)(10)
....
Or
from asgiref.sync import sync_to_async
get_blog = await sync_to_async(Blog.objects.get, thread_sensitive=True)(10)
You can use database_sync_to_async of Django channel which is an improved sync_to_async function of asgiref.sync
for example:
from channels.db import database_sync_to_async
get_blog = await database_sync_to_async(Blog.objects.get, thread_sensitive=True)(10)
I just used this way to get all the user as normal sync method.
What is i done is
First i create a method the get all the query and then i iterate by for loop.
The for loop is only for put a time loop like time.sleep(seconds). The loop itself choose a time. If the queryset completely got in the users variable. The timer is started (i.e) the for loop.
from asgiref.sync import sync_to_async
#sync_to_async
def get_all_user():
users = None
users = User.objects.all()
for user in users:
'''
timming loop. itself set a time by the time taken for iterate over the all User.objects.all()
'''
pass
return users
You can find the answer from here: https://docs.djangoproject.com/en/3.2/topics/async/#async-safety
If you try to run any of these parts from a thread where there is a running event loop, you will get a SynchronousOnlyOperation error. Note that you don’t have to be inside an async function directly to have this error occur. If you have called a sync function directly from an async function, without using sync_to_async() or similar, then it can also occur. This is because your code is still running in a thread with an active event loop, even though it may not be declared as async code.

How can I ensure, that an asyncio future was started, before continuing?

I basically want to do something like this:
future_started = asyncio.Event()
async def my_future():
future_started.set()
await asyncio.sleep(0)
[...]
async def start_my_future():
"""Starts my_future() and only returns, after my_future() has been started."""
asyncio.ensure_future(my_future())
await future_started.wait()
return
Is there a more idiomatic way to schedule a future, but make sure, that it is started, before continuing?
EDIT: I probably should've added, that I'm running Python 3.6, since a lot of changes were made to asyncio later.
Using asyncio.create_task instead of asyncio.ensure_future will start it.

What's the difference between these two imports statement?

In Meteor 1.4, what's the difference between these two import statements in the client code and in the server code? Why?
Client code:
import { Items } from '../imports/api/items.js';
Server code:
import '../imports/api/items.js';
Both statements will execute the file given, however the first one will add Item to the scope. This can be useful if the file has many exports and you are only concerned with that single class/function/object/etc.
The second is used for side effects provided from importing it (like initializing a store or something like that; I confess I don't know much about meteor).
Mozilla has a great resource on the import statement https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

Access python function from javascript in QWebView

I am writing a Python/PyQt4 application that generates and displays a page in a QWebView widget. The page includes javascript code that I would like to be able to call functions returning data from the python application.
So far I can call functions that do not return data (using the pyqtSlot decorator), and call functions that do take parameters by exposing them as properties (using the pyqtProperty decorator). What I haven't worked out how to do is to call a python function with parameters, that returns data.
The question 9615194 explains how to do this from C++, but I cannot see how to transfer this to PyQt4.
I suspect you're not using the result= keyword to specify the return value in your pyqtSlot decorator?
#pyqtSlot(str, result=str)
def echo(self, phrase):
return self.parent().echo(phrase)
I ran afoul of this myself recently. No errors are generated if you omit result=, the method just silently returns nothing. Pretty maddening 'til I figured it out. See my answer to this question for a worked example.

Resources