Example #1
0
def get_running_loop():
    try:
        import asyncio
        return asyncio.get_running_loop()
    except AttributeError:  # 3.5 / 3.6
        loop = asyncio._get_running_loop()  # pylint: disable=protected-access
        if loop is None:
            raise RuntimeError('No running event loop')
        return loop
Example #2
0
    def test_get_event_loop_returns_running_loop(self):
        class Policy(asyncio.DefaultEventLoopPolicy):
            def get_event_loop(self):
                raise NotImplementedError

        loop = None

        old_policy = asyncio.get_event_loop_policy()
        try:
            asyncio.set_event_loop_policy(Policy())
            loop = uvloop.new_event_loop()
            self.assertIs(asyncio._get_running_loop(), None)

            async def func():
                self.assertIs(asyncio.get_event_loop(), loop)
                self.assertIs(asyncio._get_running_loop(), loop)

            loop.run_until_complete(func())
        finally:
            asyncio.set_event_loop_policy(old_policy)
            if loop is not None:
                loop.close()

        self.assertIs(asyncio._get_running_loop(), None)
Example #3
0
    def test_get_event_loop_returns_running_loop(self):
        class Policy(asyncio.DefaultEventLoopPolicy):
            def get_event_loop(self):
                raise NotImplementedError

        loop = None

        old_policy = asyncio.get_event_loop_policy()
        try:
            asyncio.set_event_loop_policy(Policy())
            loop = uvloop.new_event_loop()
            self.assertIs(asyncio._get_running_loop(), None)

            async def func():
                self.assertIs(asyncio.get_event_loop(), loop)
                self.assertIs(asyncio._get_running_loop(), loop)

            loop.run_until_complete(func())
        finally:
            asyncio.set_event_loop_policy(old_policy)
            if loop is not None:
                loop.close()

        self.assertIs(asyncio._get_running_loop(), None)
async def test_parallel():
    loops = [None, None]
    async with trio.open_nursery() as n:

        async def gen_loop(i, task_status=trio.TASK_STATUS_IGNORED):
            task_status.started()
            async with trio_asyncio.open_loop() as loop:
                loops[i] = loop

        assert not isinstance(asyncio._get_running_loop(), trio_asyncio.TrioEventLoop)
        await n.start(gen_loop, 0)
        await n.start(gen_loop, 1)

    assert isinstance(loops[0], trio_asyncio.TrioEventLoop)
    assert isinstance(loops[1], trio_asyncio.TrioEventLoop)
    assert loops[0] is not loops[1]
Example #5
0
 def start(self):
     '''启动代理服务
     '''
     if sys.version_info[0] > 2:
         import asyncio
         if not asyncio._get_running_loop():
             # 设置事件循环
             asyncio.set_event_loop(asyncio.new_event_loop())
     app = tornado.web.Application([
         (r'.*', ProxyRequestHandler),
     ])
     app.listen(self._port, self._address)
     logger.info('HTTP proxy server is listening on %s:%d' %
                 (self._address, self._port))
     self._ioloop = self._ioloop or tornado.ioloop.IOLoop.instance()
     self._ioloop.start()
Example #6
0
def get_running_loop():
    try:
        return asyncio.get_running_loop()
    except AttributeError:  # 3.5 / 3.6
        loop = None
        try:
            loop = asyncio._get_running_loop()  # pylint: disable=protected-access
        except AttributeError:
            _log.warning('This version of Python is deprecated, please upgrade to >= v3.5.3')
        if loop is None:
            _log.warning('No running event loop')
            loop = asyncio.get_event_loop()
        return loop
    except RuntimeError:
        # For backwards compatibility, create new event loop
        _log.warning('No running event loop')
        return asyncio.get_event_loop()
Example #7
0
def create(hub):
    """
    Create the loop at hub.pop.Loop
    """
    if not hasattr(hub.pop, "Loop"):
        hub.pop.loop.FUT_QUE = asyncio.Queue()
        if os.name == "nt":
            hub.pop.Loop = asyncio._get_running_loop()
            if hub.pop.Loop is not None:
                return
            # The default event loop on Windows, "SelectorEventLoop" has certain limitations
            # ProactorEventLoop makes use of Window's I/O Completion Ports:
            #   https://docs.microsoft.com/en-ca/windows/win32/fileio/i-o-completion-ports
            hub.pop.Loop = asyncio.ProactorEventLoop()
            asyncio.set_event_loop(hub.pop.Loop)
        else:
            hub.pop.Loop = asyncio.get_event_loop()
Example #8
0
def get_running_loop() -> Optional[AbstractEventLoop]:
    warnings.warn(
        "get_running_loop() is deprecated, as support for Python 3.6 will be dropped in dazl 8. "
        "Use Python 3.7+'s asyncio.get_running_loop() instead.",
        DeprecationWarning,
    )
    try:
        from asyncio import get_running_loop

        try:
            return get_running_loop()
        except RuntimeError:
            return None
    except ImportError:
        # noinspection PyProtectedMember
        from asyncio import _get_running_loop

        return _get_running_loop()
Example #9
0
def feed_message_saved(sender, instance, created, **kwargs):
    if created:
        feed = instance.feed
        feed.new_messages += 1
        feed.save()
        if feed.user_id is not None:
            usergroup = "%d.user" % feed.user_id
            loop = _get_running_loop()
            if loop is None:
                async_to_sync(channel_layer.group_send)(usergroup, {
                    "type": "feed.new_message",
                    "feed": feed.id
                })
            else:
                loop.create_task(
                    channel_layer.group_send(usergroup, {
                        "type": "feed.new_message",
                        "feed": feed.id
                    }))
Example #10
0
    def is_asyncio_context() -> bool:
        """
    Check if running within a synchronous or asynchronous context.

    :returns: **True** if within an asyncio conext, **False** otherwise
    """

        try:
            asyncio.get_running_loop()
            return True
        except RuntimeError:
            return False
        except AttributeError:
            # TODO: drop when we remove python 3.6 support

            try:
                return asyncio._get_running_loop() is not None
            except AttributeError:
                return False  # python 3.5.3 or below
Example #11
0
async def _test_same_task():
    assert isinstance(asyncio.get_event_loop_policy(), TrioPolicy)

    def get_loop(i, loop, policy):
        assert loop == asyncio.get_event_loop()
        assert policy == asyncio.get_event_loop_policy()

    async with trio.open_nursery():
        async with trio_asyncio.open_loop() as loop1:
            policy = asyncio.get_event_loop_policy()
            assert isinstance(policy, TrioPolicy)
            async with trio_asyncio.open_loop() as loop2:
                p2 = asyncio.get_event_loop_policy()
                assert policy is p2, (policy, p2)
                loop1.call_later(0.1, get_loop, 0, loop1, policy)
                loop2.call_later(0.1, get_loop, 1, loop2, policy)
                await trio.sleep(0.2)

    assert isinstance(asyncio.get_event_loop_policy(), TrioPolicy)
    assert asyncio._get_running_loop() is None
Example #12
0
def get_or_create_event_loop_for_thread():
    """
    Asyncio helper function to attempt to get a currently running loop and
    if there isn't one in the thread, create one and set it so future calls
    get the same event loop.
    """
    try:
        loop = asyncio.get_running_loop()
    except RuntimeError:
        # no loop for this thread, so create one
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
    except AttributeError:
        # handle older versions of asyncio for previous versions of Python,
        # specifically this allows Python 3.6 asyncio to get a loop
        loop = asyncio._get_running_loop()
        if not loop:
            loop = asyncio.get_event_loop()

    return loop
    def __init__(self, room_id, up_name, ssl=True):
        """
        :param room_id: URL中的房间ID
        :param ssl: True表示用默认的SSLContext验证,False表示不验证,也可以传入SSLContext
        :param loop: 协程事件循环
        """
        self._short_id = room_id
        self.up_name = up_name
        self._room_id = None
        # 未登录
        self._uid = 0

        self._ssl = ssl if ssl else _create_unverified_context()
        self._websocket = None

        self._loop = _get_running_loop()
        self._future = None
        # self.mongo_db = pymongo.MongoClient('locahost')
        self.cli = pymongo.MongoClient().bilbil
        self.coll_name = "{}-{}".format(time.strftime("%Y-%m-%d"), self.up_name)
Example #14
0
    async def __ainit__(self, iterable=None, loop=None):
        self.loop = loop if loop else asyncio._get_running_loop()
        self._edit_mutex = asyncio.Lock()
        self._edit_tasks = []

        self.left_anchor = self.Node(None)
        self.right_anchor = self.Node(None)
        self.left_anchor.next = self.right_anchor
        self.right_anchor.prev = self.left_anchor

        self._nodes = set()
        self._nodes.add(self.left_anchor)
        self._nodes.add(self.right_anchor)

        if iterable:
            if not isinstance(iterable, Iterable):
                raise TypeError('Iterable instance is expected!')

            for el in iterable:
                await self.append(el)
Example #15
0
def just_run(coro: Awaitable) -> Any:
    """Make the coroutine run, even if there is an event loop running (using nest_asyncio)"""
    # original from vaex/asyncio.py
    loop = asyncio._get_running_loop()
    if loop is None:
        had_running_loop = False
        try:
            loop = asyncio.get_event_loop()
        except RuntimeError:
            # we can still get 'There is no current event loop in ...'
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
    else:
        had_running_loop = True
    if had_running_loop:
        # if there is a running loop, we patch using nest_asyncio
        # to have reentrant event loops
        check_ipython()
        import nest_asyncio
        nest_asyncio.apply()
        check_patch_tornado()
    return loop.run_until_complete(coro)
Example #16
0
 async def connect(self):
     try:
         if self.connected.is_set():
             return
     except AttributeError:
         pass
     loop = asyncio._get_running_loop()
     while self.running:
         try:
             if self.client_port:
                 sock = await self.build_reuse_socket()
                 self.transport, self.protocol = await asyncio.wait_for(
                     loop.create_connection(
                         lambda: ModbusTcpProtocol(self),
                         sock=sock,
                     ),
                     2,
                 )
             else:
                 self.transport, self.protocol = await asyncio.wait_for(
                     loop.create_connection(lambda: ModbusTcpProtocol(self),
                                            self.host, self.port),
                     2,
                 )
             self.connected.set()
             return
         except (OSError, asyncio.TimeoutError) as e:
             if self.auto_reconnect_after:
                 log.warning(e)
                 log.info("Reconnecting to ModbusTCP")
                 await asyncio.sleep(self.auto_reconnect_after)
             else:
                 log.exception(e)
                 raise
         except BaseException as e:
             log.exception(e)
             raise
Example #17
0
async def controlespider(url, word, ignorecache):
    #Testa se o termo de pesquisa não é vazio
    if (not word.strip()):
        print("Termo de pesquisa vazio")
        raise AttributeError
    
    #inicia e controla o loop
    parser = LinkParser()
    
    #Filas utilizadas pra transitar os dados
    loop = asyncio._get_running_loop()
    ToProcessUrlQueue = asyncio.Queue(loop=loop) #Fila de urls a serem baixadas pela getlinks
    ToConsumeDataQueue =  asyncio.Queue(loop=loop) #HTML em string baixado pela getlinks para processamento da ConsumeHtml
    ToConsumeUrlQueue =  asyncio.Queue(loop=loop) #URL do html baixado pela getlinks para processamento da ConsumeHtml
    ToStoreDataQueue =  asyncio.Queue(loop=loop) #HTML em string baixado pela getlinks para processamento da storecache
    ToStoreUrlQueue =  asyncio.Queue(loop=loop) #URL do html baixado pela getlinks para processamento da storecache
    FinalQueue = asyncio.Queue(loop=loop)
    
    #inicia e aguarda os processos necessários
    await spider(url, ignorecache, ToProcessUrlQueue)
    await parser.getLinks(ToProcessUrlQueue, ToConsumeDataQueue, ToConsumeUrlQueue, ToStoreDataQueue, ToStoreUrlQueue)
    await ConsumeHtml (word, ToConsumeDataQueue, ToConsumeUrlQueue, FinalQueue)
    await storeCache(ToStoreDataQueue, ToStoreUrlQueue)
    return await createreturn(FinalQueue)
Example #18
0
async def timeout(ctx, member: discord.Member, TO_time=0):

    guild = ctx.guild
    old_roles = member.roles
    guild_roles = guild.roles
    timeout_role_name = "Timeout"
    found = False

    time_out_time = TO_time

    for i in guild_roles:
        if i.name == timeout_role_name:
            timeout_role = i
            found = True

    if found == False:
        timeout_role = await guild.create_role(name=timeout_role_name)

    await member.edit(roles=[timeout_role])

    loop = asyncio._get_running_loop()
    end_time = loop.time() + (TO_time * 60)

    await member.create_dm()
    await member.dm_channel.send(
        content=("You have been timed out from the server for %d minutes." %
                 (TO_time)))

    while True:

        if (loop.time() + 1) >= end_time:
            await member.edit(roles=old_roles)
            break
        await asyncio.sleep(1)

    await member.dm_channel.send(content=("You are no longer timed out"))
Example #19
0
import pkg_resources
import sys
import asyncio
import nest_asyncio

if sys.version_info < (3, 6):
    raise EnvironmentError(
        'Hail requires Python 3.6 or later, found {}.{}'.format(
            sys.version_info.major, sys.version_info.minor))

if sys.version_info[:2] == (3, 6):
    if asyncio._get_running_loop() is not None:
        nest_asyncio.apply()
else:
    try:
        asyncio.get_running_loop()
        nest_asyncio.apply()
    except RuntimeError as err:
        assert 'no running event loop' in err.args[0]

__pip_version__ = pkg_resources.resource_string(
    __name__, 'hail_pip_version').decode().strip()
del pkg_resources
del sys

__doc__ = r"""
    __  __     <>__
   / /_/ /__  __/ /
  / __  / _ `/ / /
 /_/ /_/\_,_/_/_/
===================
Example #20
0
 async def func():
     self.assertIs(asyncio.get_event_loop(), loop)
     self.assertIs(asyncio._get_running_loop(), loop)
 async def connect(cls, host, port, worker_id, request_id, connect_timeout):
     loop = asyncio._get_running_loop()
     disp = cls(loop, host, port, worker_id, request_id, connect_timeout)
     disp._grpc_thread.start()
     await disp._grpc_connected_fut
     return disp
Example #22
0
 def get_running_loop() -> AbstractEventLoop:
     loop = _get_running_loop()
     if loop:
         return loop
     raise RuntimeError("no running event loop")
Example #23
0
 def _get_state():
     loop = asyncio._get_running_loop()
     if loop is None:
         return _state
     task = asyncio.Task.current_task(loop=loop)
     return _state if task is None else task
Example #24
0
 def has_asyncio_loop(cls) -> bool:
     ""
     return asyncio._get_running_loop() is not None
Example #25
0
 async def _set_aiotask_factory():
     loop = asyncio._get_running_loop()
     loop.set_task_factory(ctx.task_factory)
     self.loop = loop
Example #26
0
 def get_running_loop() -> asyncio.AbstractEventLoop:
     loop = asyncio._get_running_loop()
     if loop is not None:
         return loop
     else:
         raise RuntimeError('no running event loop')
Example #27
0
def run(coro: Coroutine,
        *,
        loop: Optional[asyncio.AbstractEventLoop] = None,
        debug: bool = False,
        set_to_none: bool = False) -> Any:
    """Run a |coroutine_link|_.

    This function runs the passed coroutine, taking care
    of the event loop and shutting down asynchronous generators.

    This function is basically ported from Python 3.7 for backwards compability
    with earlier versions of Python.

    This function cannot be called when another event loop is
    running in the same thread.

    If ``debug`` is ``True``, the event loop will be run in debug mode.

    This function creates a new event loop and closes it at the end if a ``loop`` is ``None``.

    If a loop is given, this function basically calls :meth:`asyncio.AbstractEventLoop.run_until_complete`.

    It should be used as a main entry point to asyncio programs, and should
    ideally be called only once.

    Example:

    .. code-block:: python3

        async def test(pid):
            return pid

        one = gd.utils.run(test(1))

    Parameters
    ----------
    coro: |coroutine_link|_
        Coroutine to run.

    loop: Optional[:class:`asyncio.AbstractEventLoop`]
        A loop to run ``coro`` with. If ``None`` or omitted, a new event loop is created.

    debug: :class:`bool`
        Whether or not to run event loop in debug mode.

    set_to_none: :class:`bool`
        Indicates if the loop should be set to None after execution.

    Returns
    -------
    `Any`
        Anything that ``coro`` returns.
    """
    if asyncio._get_running_loop() is not None:
        raise RuntimeError(
            'Can not perform gd.utils.run() in a running event loop.')

    if not asyncio.iscoroutine(coro):
        raise ValueError('A coroutine was expected, got {!r}.'.format(coro))

    shutdown = False

    if loop is None:
        loop = asyncio.new_event_loop()
        shutdown = True

    try:
        asyncio.set_event_loop(loop)
        loop.set_debug(debug)
        return loop.run_until_complete(coro)

    finally:
        if shutdown:
            shutdown_loop(loop)

        if set_to_none:
            loop = None

        else:
            loop = asyncio.new_event_loop()

        asyncio.set_event_loop(loop)
Example #28
0
 async def func():
     self.assertIs(asyncio.get_event_loop(), loop)
     self.assertIs(asyncio._get_running_loop(), loop)
Example #29
0
def test_aiohttp_loop():
    import asyncio
    from azure.core.pipeline.transport import AioHttpTransport
    loop = asyncio._get_running_loop()
    with pytest.raises(ValueError):
        transport = AioHttpTransport(loop=loop)
Example #30
0
def get_running_loop():
    """ provide asyncio.get_running_loop in Python 3.6 """
    loop = asyncio._get_running_loop()
    if loop is None:
        raise RuntimeError('no running event loop')
    return loop
Example #31
0
 def tearDown(self):
     self.assertIsNone(asyncio._get_running_loop())
     self.loop.close()
     del self.loop
Example #32
0
 def get_running_loop():
     loop = _get_running_loop()
     if loop is None:
         raise RuntimeError("no running event loop")
     return loop
Example #33
0
                   AdvancedAuth)
from .friend import Friend, PendingFriend
from .message import FriendMessage, PartyMessage
from .party import (DefaultPartyConfig, DefaultPartyMemberConfig, PartyMember,
                    ClientPartyMember, JustChattingClientPartyMember, Party,
                    ClientParty, ReceivedPartyInvitation, SentPartyInvitation,
                    PartyJoinConfirmation)
from .presence import Presence, PresenceGameplayStats, PresenceParty
from .user import (ClientUser, User, BlockedUser, ExternalAuth,
                   ProfileSearchEntryUser, SacSearchEntryUser)
from .stats import StatsV2
from .enums import *
from .errors import *
from .store import Store, FeaturedStoreItem, DailyStoreItem
from .news import BattleRoyaleNewsPost
from .playlist import Playlist
from .kairos import Avatar

# fix for python 3.8
loop = asyncio._get_running_loop()
if loop is not None:
    if isinstance(asyncio.get_event_loop_policy(),
                  asyncio.WindowsProactorEventLoopPolicy):
        raise RuntimeError(
            'Incompatible event loop running. Read more here: '
            'https://fortnitepy.readthedocs.io/en/latest/faq.html#python-3-8-why-does-other-asynchronous-libraries-suddenly-break-when-using-fortnitepy'
        )

if platform == 'win32' and version_info >= (3, 8):
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())