Python源码示例:asyncio.Lock()

示例1
def __init__(self, bot: Bot):
        super().__init__()

        self.bot = bot

        # Categories
        self.available_category: discord.CategoryChannel = None
        self.in_use_category: discord.CategoryChannel = None
        self.dormant_category: discord.CategoryChannel = None

        # Queues
        self.channel_queue: asyncio.Queue[discord.TextChannel] = None
        self.name_queue: t.Deque[str] = None

        self.name_positions = self.get_names()
        self.last_notification: t.Optional[datetime] = None

        # Asyncio stuff
        self.queue_tasks: t.List[asyncio.Task] = []
        self.ready = asyncio.Event()
        self.on_message_lock = asyncio.Lock()
        self.init_task = self.bot.loop.create_task(self.init_cog()) 
示例2
def _async_send(self, request: Request):
        if request.method.lower() != 'get':
            return await self.sender.send(request)

        if self._lock is None:
            self._lock = asyncio.Lock()

        async with self._lock:
            cached, etag = self._load(request)

        if cached is not None and etag is None:
            return cached
        elif etag is not None:
            request.headers.update(ETag=etag)

        fresh = await self.sender.send(request)
        async with self._lock:
            return self._handle_fresh(request, fresh, cached) 
示例3
def __init__(self, hostname, sasl,
                 container_id=False,
                 max_frame_size=None,
                 channel_max=None,
                 idle_timeout=None,
                 properties=None,
                 remote_idle_timeout_empty_frame_send_ratio=None,
                 error_policy=None,
                 debug=False,
                 encoding='UTF-8',
                 loop=None):
        self.loop = loop or get_running_loop()
        super(ConnectionAsync, self).__init__(
            hostname, sasl,
            container_id=container_id,
            max_frame_size=max_frame_size,
            channel_max=channel_max,
            idle_timeout=idle_timeout,
            properties=properties,
            remote_idle_timeout_empty_frame_send_ratio=remote_idle_timeout_empty_frame_send_ratio,
            error_policy=error_policy,
            debug=debug,
            encoding=encoding)
        self._async_lock = asyncio.Lock(loop=self.loop) 
示例4
def __init__(self, connection):
        """
        Constructs this handler on a given validator connection.

        Args:
            connection (messaging.Connection): the validator connection
        """
        self._connection = connection

        self._latest_state_delta_event = None
        self._subscribers = []
        self._subscriber_lock = asyncio.Lock()
        self._delta_task = None
        self._listening = False
        self._accepting = True

        self._connection.on_connection_state_change(
            ConnectionEvent.DISCONNECTED,
            self._handle_disconnect)
        self._connection.on_connection_state_change(
            ConnectionEvent.RECONNECTED,
            self._handle_reconnection) 
示例5
def __init__(self, stream_id, window_getter, loop=None):
        if loop is None:
            loop = asyncio.get_event_loop()
        self._stream_id = stream_id
        self._window_getter = window_getter

        self._wlock = asyncio.Lock(loop=loop)
        self._window_open = CallableEvent(self._is_window_open, loop=loop)

        self._rlock = asyncio.Lock(loop=loop)
        self._buffers = deque()
        self._buffer_size = 0
        self._buffer_ready = asyncio.Event(loop=loop)
        self._response = asyncio.Future(loop=loop)
        self._trailers = asyncio.Future(loop=loop)
        self._eof_received = False
        self._closed = False 
示例6
def __init__(
        self, token: CancelToken = None, loop: asyncio.AbstractEventLoop = None
    ) -> None:
        self.events = ServiceEvents()
        self._run_lock = asyncio.Lock()
        self._child_services = WeakSet()
        self._tasks = WeakSet()
        self._finished_callbacks = []

        self._loop = loop

        base_token = CancelToken(type(self).__name__, loop=loop)

        if token is None:
            self.cancel_token = base_token
        else:
            self.cancel_token = base_token.chain(token) 
示例7
def __init__(self, config, queue, events, loop=None):
        """
        Initialize instance of the NodeManager class

        :param config: config object
        :param queue: broadcast queue
        :type config: tattle.config.Configuration
        :type events: tattle.event.EventManager
        :type queue: tattle.queue.BroadcastQueue
        """
        self.config = config
        self._queue = queue
        self._events = events
        self._loop = loop or asyncio.get_event_loop()
        self._leaving = False
        self._nodes = list()
        self._nodes_map = dict()
        self._nodes_lock = asyncio.Lock()
        self._suspect_nodes = dict()
        self._local_node_name = None
        self._local_node_seq = sequence.Sequence() 
示例8
def _cache_instances(self, region: str):
        async with self._regional_instances_cache_locks.setdefault(region, Lock()):
            if region in self._instances_cache:
                return

            self._instances_cache[region] = await AWSFacadeUtils.get_all_pages(
                'rds', region, self.session, 'describe_db_instances', 'DBInstances')

            for instance in self._instances_cache[region]:
                instance['VpcId'] = instance['DBSubnetGroup']['VpcId'] \
                    if 'DBSubnetGroup' in instance and 'VpcId' in instance['DBSubnetGroup'] \
                    and instance['DBSubnetGroup']['VpcId'] \
                    else ec2_classic

            await get_and_set_concurrently(
                [self._get_and_set_instance_clusters, self._get_and_set_instance_tags], self._instances_cache[region], region=region) 
示例9
def cache_load_balancers(self, region):
        async with self.regional_load_balancers_cache_locks.setdefault(region, asyncio.Lock()):
            if region in self.load_balancers_cache:
                return

            self.load_balancers_cache[region] = \
                await AWSFacadeUtils.get_all_pages('elb', region, self.session,
                                                   'describe_load_balancers', 'LoadBalancerDescriptions')

            for load_balancer in self.load_balancers_cache[region]:
                load_balancer['VpcId'] = \
                    load_balancer['VPCId'] if 'VPCId' in load_balancer and load_balancer['VPCId'] else ec2_classic

            await get_and_set_concurrently(
                [self._get_and_set_load_balancer_attributes], self.load_balancers_cache[region], region=region)

            await get_and_set_concurrently(
                [self._get_and_set_load_balancer_tags], self.load_balancers_cache[region], region=region) 
示例10
def cache_load_balancers(self, region):
        async with self.regional_load_balancers_cache_locks.setdefault(region, asyncio.Lock()):
            if region in self.load_balancers_cache:
                return

            self.load_balancers_cache[region] = \
                await AWSFacadeUtils.get_all_pages('elbv2', region, self.session,
                                                   'describe_load_balancers', 'LoadBalancers')

            for load_balancer in self.load_balancers_cache[region]:
                load_balancer['VpcId'] = \
                    load_balancer['VpcId'] if 'VpcId' in load_balancer and load_balancer['VpcId'] else ec2_classic

            await get_and_set_concurrently(
                [self._get_and_set_load_balancer_attributes], self.load_balancers_cache[region], region=region)

            await get_and_set_concurrently(
                [self._get_and_set_load_balancer_tags], self.load_balancers_cache[region], region=region) 
示例11
def __init__(self, period=DEFAULT_THROTTLE, params=[], log=True, count=1):
		self.period = period
		self.watchparams = params
		self.lastrun = {}
		self.lastreturn = {}
		self.lastcleanup = time.time()
		self.log = log
		self.count = count
		self.lock = asyncio.Lock()

		# need to decorate this here, rather than putting a decorator on the actual
		# function, as it needs to wrap the *bound* method, so there's no "self"
		# parameter. Meanwhile, we're wrapping this "decorate" function instead of
		# just wrapping __call__ as setting __call__ directly on instances doesn't
		# work, Python gets the __call__ function from the class, not individual
		# instances.
		self.decorate = coro_decorator(self.decorate) 
示例12
def __init__(self, host=None, listen=15):
        assert V.DATA_PATH is not None, 'Setup p2p params before CoreClass init.'
        assert host is None or host == 'localhost'
        # status params
        self.f_stop = False
        self.f_finish = False
        self.f_running = False
        # working info
        self.start_time = int(time())
        self.number = 0
        self.user: List[User] = list()
        self.user_lock = asyncio.Lock()
        self.host = host  # local=>'localhost', 'global'=>None
        self.core_que = asyncio.Queue()
        self.backlog = listen
        self.traffic = Traffic()
        self.ping_status: Dict[int, asyncio.Event] = ExpiringDict(max_len=5000, max_age_seconds=900) 
示例13
def __init__(self,
                 topic: Optional[str] = None,
                 max_connections: int = 10,
                 max_connection_attempts: Optional[int] = None,
                 loop: Optional[asyncio.AbstractEventLoop] = None,
                 use_sandbox: bool = False):

        self.apns_topic = topic
        self.max_connections = max_connections
        if use_sandbox:
            self.protocol_class = APNsDevelopmentClientProtocol
        else:
            self.protocol_class = APNsProductionClientProtocol

        self.loop = loop or asyncio.get_event_loop()
        self.connections = []
        self._lock = asyncio.Lock(loop=self.loop)
        self.max_connection_attempts = max_connection_attempts 
示例14
def add_item(self, success_cb_id, firstname, lastname, date,
                 source, destination, train_num, ct_letter=None):
        scan_id = uuid4().hex
        self.__state[scan_id] = dict(
            success_cb_id=success_cb_id,
            firstname=firstname,
            lastname=lastname,
            date=date,
            source=source,
            destination=destination,
            train_num=train_num,
            ct_letter=ct_letter,
            lock=asyncio.Lock(),
            attempts=0,
            error=None)
        return scan_id 
示例15
def __init__(self, event_loop, session_name, api_id, api_hash, phone_number, workdir=None):

        self.event_loop = event_loop
        self.username_flood_until = None
        self._message_intervals = {}
        self._last_ping = None
        self.__photos_lock = asyncio.Lock(loop=self.event_loop)

        super(BotChecker, self).__init__(
            session_name,
            api_id,
            api_hash,
            workers=4,
            phone_number=phone_number,
            workdir=workdir
        )
        self.logger.setLevel(logging.WARNING) 
示例16
def __init__(self,
                 timer_key,
                 duration,
                 timer_service: TimerService,
                 callback,
                 callback_lock: asyncio.Lock,
                 loop,
                 call_instantly: bool):
        self.__slot = 0
        self.__delayed = True
        self.__timer_key = timer_key
        self.__timer_service = timer_service
        self.__duration = duration
        self.__callback = callback
        self.__callback_lock = callback_lock
        self.__loop = loop
        self.is_running = False

        if call_instantly:
            self.call = self.call_instantly
        else:
            self.call = self.call_in_slot 
示例17
def __init__(self, hass, amcrest):
        """Initialize an Amcrest camera."""
        super(AmcrestCam, self).__init__()
        self._name = amcrest.name
        self._camera = amcrest.device
        self._ffmpeg = hass.data[DATA_FFMPEG]
        self._ffmpeg_arguments = amcrest.ffmpeg_arguments
        self._stream_source = amcrest.stream_source
        self._resolution = amcrest.resolution
        self._token = self._auth = amcrest.authentication
        self._is_recording = False
        self._motion_detection_enabled = None
        self._model = None
        self._audio_enabled = None
        self._motion_recording_enabled = None
        self._color_bw = None
        self._snapshot_lock = asyncio.Lock() 
示例18
def __init__(
        self,
        app: ASGIFramework,
        loop: asyncio.AbstractEventLoop,
        config: Config,
        reader: asyncio.StreamReader,
        writer: asyncio.StreamWriter,
    ) -> None:
        self.app = app
        self.config = config
        self.loop = loop
        self.protocol: ProtocolWrapper
        self.reader = reader
        self.writer = writer
        self.send_lock = asyncio.Lock()
        self.timeout_lock = asyncio.Lock()

        self._keep_alive_timeout_handle: Optional[asyncio.Task] = None 
示例19
def __init__(self, path: Union[Path, str], *,
                 watcher_cls: Type[AllWatcher] = DefaultWatcher,
                 watcher_kwargs: Optional[Dict[str, Any]] = None,
                 debounce=1600,
                 normal_sleep=400,
                 min_sleep=50,
                 stop_event: asyncio.Event = None,
                 loop=None):
        self._loop = loop or asyncio.get_event_loop()
        self._executor = ThreadPoolExecutor(max_workers=4)
        self._path = path
        self._watcher_cls = watcher_cls
        self._watcher_kwargs = watcher_kwargs or dict()
        self._debounce = debounce
        self._normal_sleep = normal_sleep
        self._min_sleep = min_sleep
        self._stop_event = stop_event
        self._w = None
        asyncio.set_event_loop(self._loop)
        self.lock = asyncio.Lock() 
示例20
def __init__(self, retries=3):
        self.panel = None  # type: Panel
        self._connection = None
        self.retries = retries
        self.work_loop = asyncio.get_event_loop()  # type: asyncio.AbstractEventLoop
        self.work_loop.set_exception_handler(async_loop_unhandled_exception_handler)
        self.receive_worker_task = None

        self.storage = Storage()

        self._run_state = RunState.STOP
        self.request_lock = asyncio.Lock()
        self.busy = asyncio.Lock()
        self.loop_wait_event = asyncio.Event()

        ps.subscribe(self._on_labels_load, "labels_loaded")
        ps.subscribe(self._on_definitions_load, "definitons_loaded")
        ps.subscribe(self._on_status_update, "status_update")
        ps.subscribe(self._on_event, "events")
        ps.subscribe(self._on_property_change, "changes") 
示例21
def __init__(
        self,
        filename: str,
        mode: str = "a",
        encoding: str = None,
        namer: Namer = None,
        rotator: Rotator = None,
        *,
        loop: Optional[AbstractEventLoop] = None,
    ) -> None:
        super().__init__(filename, mode, encoding, loop=loop)
        self.mode = mode
        self.encoding = encoding
        self.namer = namer
        self.rotator = rotator
        self._rollover_lock: Optional[asyncio.Lock] = None 
示例22
def emit(self, record: LogRecord):  # type: ignore
        """
        Emit a record.

        Output the record to the file, catering for rollover as described
        in `do_rollover`.
        """
        try:
            if self.should_rollover(record):
                if not self._rollover_lock:
                    self._rollover_lock = asyncio.Lock(loop=self.loop)

                async with self._rollover_lock:
                    if self.should_rollover(record):
                        await self.do_rollover()
            await super().emit(record)
        except Exception as exc:
            await self.handle_error(record, exc) 
示例23
def __init__(
        self,
        stream=None,
        level: Union[str, int, LogLevel] = LogLevel.NOTSET,
        formatter: Formatter = None,
        filter: Filter = None,
        *,
        loop: Optional[AbstractEventLoop] = None,
    ) -> None:
        super().__init__(loop=loop)
        if stream is None:
            stream = sys.stderr
        self.stream = stream
        self.level = level
        if formatter is None:
            formatter = Formatter()
        self.formatter: Formatter = formatter
        if filter:
            self.add_filter(filter)
        self.protocol_class = AiologgerProtocol
        self._initialization_lock = asyncio.Lock(loop=self.loop)
        self.writer: Optional[StreamWriter] = None 
示例24
def __init__(self, bot):
        self.bot = bot
        self.json = compat_load(JSON)

        # queue variables
        self.queue = asyncio.PriorityQueue(loop=bot.loop)
        self.queue_lock = asyncio.Lock(loop=bot.loop)
        self.pending = {}
        self.enqueued = set()

        try:
            self.analytics = CogAnalytics(self)
        except Exception as error:
            self.bot.logger.exception(error)
            self.analytics = None

        self.task = bot.loop.create_task(self.on_load()) 
示例25
def main(loop):
  lock = asyncio.Lock()
  await asyncio.wait([myWorker(lock), myWorker(lock)]), 
示例26
def __init__(
        self,
        name: str,
        dsn: str,
        connect_sql: Optional[List[str]] = None,
        keep_connected: Optional[bool] = True,
        autocommit: Optional[bool] = True,
        labels: Optional[Dict[str, str]] = None,
    ):
        self.name = name
        self.dsn = dsn
        self.connect_sql = connect_sql or []
        self.keep_connected = keep_connected
        self.autocommit = autocommit
        self.labels = labels or {}
        self._connect_lock = asyncio.Lock()
        try:
            self._engine = create_engine(
                dsn,
                strategy=ASYNCIO_STRATEGY,
                execution_options={"autocommit": self.autocommit},
            )
        except ImportError as error:
            raise self._db_error(f'module "{error.name}" not found', fatal=True)
        except (ArgumentError, ValueError, NoSuchModuleError):
            raise self._db_error(f'Invalid database DSN: "{self.dsn}"', fatal=True)

        self._setup_query_latency_tracking() 
示例27
def __init__(self, client):
        self._client = client
        self._id = None
        self._file = None
        self._lock = asyncio.Lock() 
示例28
def __init__(self, client):
        self._client = client
        self._me = None
        self.db = None
        self._assets = None
        self._anti_double_lock = asyncio.Lock()
        self._anti_double_asset_lock = asyncio.Lock()
        self._data_already_exists = False
        self._assets_already_exists = False 
示例29
def resolve(self, client):
        """Helper method to allow event builders to be resolved before usage"""
        if self.resolved:
            return

        if not self._resolve_lock:
            self._resolve_lock = asyncio.Lock(loop=client.loop)

        async with self._resolve_lock:
            if not self.resolved:
                await self._resolve(client)
                self.resolved = True 
示例30
def __init__(self, sender: Sender = None, max_size: int = None):
        super().__init__(sender)
        self._max_size = max_size
        self._cache = {}
        self._deque = deque(maxlen=self.max_size)
        self._lock: asyncio.Lock = None