• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python threads.deferToThread函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中twisted.internet.threads.deferToThread函数的典型用法代码示例。如果您正苦于以下问题:Python deferToThread函数的具体用法?Python deferToThread怎么用?Python deferToThread使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了deferToThread函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: loginSuccessful

    def loginSuccessful(self, username, password):
        self.passwordTried = True
        self.loginSuccess = True
        dt = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        self.makeSessionFolder()
        if self.cfg.get('txtlog', 'enabled') == 'true':
            txtlog.authLog(self.cfg.get('folders', 'log_path') + "/" + datetime.datetime.now().strftime("%Y%m%d"), self.endIP, username, password, True)
            txtlog.log(self.txtlog_file, self.connectionString)
            txtlog.log(self.txtlog_file, '[SSH  ] Login Successful: ' + username + ':' + password)
 
        if self.cfg.get('email', 'login') == 'true':
            threads.deferToThread(self.email, self.sensorName + ' - Login Successful', self.txtlog_file)
        
        if self.cfg.get('database_mysql', 'enabled') == 'true':
            self.dbLog.handleLoginSucceeded(username, password)
            self.dbLog.createSession(self.sessionID, self.endIP, self.endPort, self.honeyIP, self.honeyPort, self.sensorName)
            self.dbLog.handleClientVersion(self.sessionID, self.version)
                    
        if self.cfg.get('hpfeeds', 'enabled') == 'true':
            self.hpLog.handleLoginSucceeded(username, password)
            self.hpLog.createSession(self.sessionID, self.endIP, self.endPort, self.honeyIP, self.honeyPort)
            self.hpLog.handleClientVersion(self.version)
            
        if self.cfg.has_option('app_hooks', 'login_successful'):
            if self.cfg.get('app_hooks', 'login_successful') != '':
                cmdString = self.cfg.get('app_hooks', 'login_successful') + " LOGIN_SUCCESSFUL " + dt + " " + self.endIP + " " + username + " " + password
                threads.deferToThread(self.runCommand, cmdString)
开发者ID:JacobJacob,项目名称:honssh,代码行数:27,代码来源:output.py


示例2: sendBuildbotNetUsageData

def sendBuildbotNetUsageData(master):
    if master.config.buildbotNetUsageData is None:
        return
    data = computeUsageData(master)
    if data is None:
        return
    threads.deferToThread(_sendBuildbotNetUsageData, data)
开发者ID:pieterlexis,项目名称:buildbot,代码行数:7,代码来源:buildbot_net_usage_data.py


示例3: parse_message

    def parse_message(self, sqs_message):
        e = []
        # decode JSON
        try:
            parsed_json = simplejson.loads(sqs_message.get_body())
        except Exception as exception:
            logger.error('Error parsing JSON %s' % exception)
            return False
        for k in self.message_format:
            if not k in parsed_json:
                logger.error('MessageTag %s not defined in sqs_message.id:%s, sqs_message_body:%s' %
                             (k, sqs_message.id, parsed_json))
                return False
        e = parsed_json['event']
        for k in self.event_format:
            if not k in e:
                logger.error('EventTag %s not defined in sqs_message.id:%s, sqsMessageBody:%s' %
                             (k, sqs_message.id, parsed_json))
                return False

        # Add incident to Database
        incident = add_incident(e, parsed_json['timestamp'])

        # Check incident thresholds and fire events
        if incident and incident.status == 'Active':
            threads.deferToThread(ProcessIncident, incident, e['message'])
        logger.info('MsgOk: EventID:%s, Element:%s, Message%s on Timestamp:%s' % (e['eventid'],
                                                                                  e['element'],
                                                                                  e['message'],
                                                                                  parsed_json['timestamp']))
        return True
开发者ID:meetjitesh,项目名称:cito_engine,代码行数:31,代码来源:sqspoller.py


示例4: persist_file

 def persist_file(self, path, buf, info, meta=None, headers=None):
     """Upload file to S3 storage"""
     key_name = '%s%s' % (self.prefix, path)
     buf.seek(0)
     if self.is_botocore:
         extra = self._headers_to_botocore_kwargs(self.HEADERS)
         if headers:
             extra.update(self._headers_to_botocore_kwargs(headers))
         return threads.deferToThread(
             self.s3_client.put_object,
             Bucket=self.bucket,
             Key=key_name,
             Body=buf,
             Metadata={k: str(v) for k, v in six.iteritems(meta or {})},
             ACL=self.POLICY,
             **extra)
     else:
         b = self._get_boto_bucket()
         k = b.new_key(key_name)
         if meta:
             for metakey, metavalue in six.iteritems(meta):
                 k.set_metadata(metakey, str(metavalue))
         h = self.HEADERS.copy()
         if headers:
             h.update(headers)
         return threads.deferToThread(
             k.set_contents_from_string, buf.getvalue(),
             headers=h, policy=self.POLICY)
开发者ID:CPoirot3,项目名称:scrapy,代码行数:28,代码来源:files.py


示例5: start

    def start(self):
        """
        Start the buildstep.
        """
        instance_id = self.getProperty('instance_id')
        assert instance_id

        volume_tags = dict(self.object_tags)
        volume_tags['timestamp'] = self._timestamp()

        conn = yield threads.deferToThread(self._connect)
        volume_id, device, error = yield threads.deferToThread(
            create_ami.create_volume,
            conn,
            instance_id,
            self.volume_gib,
            self.location,
            volume_tags)

        self.setProperty('volume_id', volume_id)
        self.setProperty('device', device)
        self.setProperty('volume_tags', volume_tags)

        if volume_id and not error:
            self.finished(results.SUCCESS)
        else:
            self.failed(failure.Failure(error))
开发者ID:lseror,项目名称:outscale-factory-buildbot,代码行数:27,代码来源:buildsteps.py


示例6: start

    def start(self, args={}, subtask_key=None, callback=None, callback_args={}, errback=None):
        """
        starts the task.  This will spawn the work in a workunit thread.
        """

        # only start if not already running
        if self._status == STATUS_RUNNING:
            return

        #if this was subtask find it and execute just that subtask
        if subtask_key:
            logger.debug('Task - starting subtask %s' % (subtask_key))
            split = subtask_key.split('.')
            subtask = self.get_subtask(split)
            logger.debug('Task - got subtask')
            self.work_deferred = threads.deferToThread(subtask._start, args, callback, callback_args)

        #else this is a normal task just execute it
        else:
            logger.debug('Task - starting task: %s' % self)
            self.work_deferred = threads.deferToThread(self._start, args, callback, callback_args)

        if errback:
            self.work_deferred.addErrback(errback)


        return 1
开发者ID:jlg,项目名称:pydra-map-reduce,代码行数:27,代码来源:tasks.py


示例7: _update_user_permissions

 def _update_user_permissions(self, user_id):
   """ Updates the permissions for the indicated user.
   
   This method downloads (or loads), validates, and saves the specified user's permission settings.
   
   @note If a non-remote permissions endpoint is specified, the permissions will be loaded from the offline local file.
   @note If the indicated user already has permission settings recorded, they will be overridden with the new settings.
   
   @throws Throws PermissionsInvalidSchema if the dictionary defined in permission_settings does not conform to the 
           permission settings schema, as checked by _validate_permissions().
   @throws PermissionsUserNotFound if the indicated user couldn't be located in the loaded permissions resource.
   
   @param user_id  The ID of the user that the command permissions are for.
   @return Returns a deferred that will be fired with the results of the permission settings load/download. That is,
           an error or the permissions object for the indicated user.
   """
   
   # Attempt to load the user's permissions
   if self.use_remote_permissions:
     defer_download = threads.deferToThread(self._download_remote_permissions, user_id)
   else:
     defer_download = threads.deferToThread(self._load_local_permissions, user_id)
   
   # Validate & save
   defer_download.addCallback(self._validate_permissions, user_id)
   defer_download.addCallback(self._save_permissions, user_id)
   
   return defer_download
开发者ID:MichiganExplorationLab,项目名称:Mercury2-HWM,代码行数:28,代码来源:permissions.py


示例8: _handle_event

 def _handle_event(self, event_type, args=(), respond_to=False):
     """handles event dispatch"""
     for event in self.events[event_type]:
         if self.config['threaded']:
             threads.deferToThread(self._event, event, args, respond_to)
         else:
             defer.execute(self._event, event, args, respond_to)
开发者ID:zeekay,项目名称:chii,代码行数:7,代码来源:chii.py


示例9: listen

 def listen(self):
     try:
         deferToThread(self.server.serve_forever)
         self.running = True
     except TFTPServerConfigurationError, e:
         self.logger.error('TFTP server configuration error: %s!' %
                       e.message)
开发者ID:jfmorcillo,项目名称:mmc,代码行数:7,代码来源:tftp_server.py


示例10: __CREA

    def __CREA(self, data):
        """
            Massive reading files from file storage, using threads in Twisted
        """
        algorithm = self.gui.FileManager.options_frame.getCryptoAlgorithm()
        key = self.gui.FileManager.options_frame.getCryptoKey()
        tmp_dir = self.gui.FileManager.options_frame.tmpFolder
        user_folder = self.gui.FileManager.files_folder.getUsersDir()

        def defferedReadFile(user_id, name, path, file_id, servers):
            new_folders = os.path.normpath(user_folder + '/' + path)
            try:
                os.makedirs(new_folders)
            except OSError:
                pass
            for ip, port in servers:
                src_file = os.path.normpath(user_folder + '/' + path + '/' + name)
                server_ip = str(ip)
                server_port = str(port)
                json_file = os.path.normpath(tmp_dir + '/fsc_' + self.login + '_' + name + '_' + str(randint(0, 100000)) + '.json')
                dumpConfigToJSON(json_file, "READU_FILE", user_id, file_id, src_file, key, algorithm)
                self.__SendInfoToFileServer(json_file, server_ip, server_port)
                evt = UpdateFileListCtrlEvent()
                wx.PostEvent(self.gui, evt)

        for name, path, file_id, servers in data['files_read']:
            threads.deferToThread(defferedReadFile, data['user_id'], name, path, file_id, servers)
        del data['files_read']
        del data['user_id']
开发者ID:Relrin,项目名称:Helenae,代码行数:29,代码来源:client_gui.py


示例11: __CLNK

    def __CLNK(self, data):
        """
            Downloading file by link from another file storage
        """
        tmp_dir = self.gui.FileManager.options_frame.tmpFolder

        def defferedDownloadByLink(user_id, save_in, filename, file_id, key, server):
            src_file = os.path.normpath(save_in + '/' + filename)
            server_ip = str(server[0][0])
            server_port = str(server[0][1])
            json_file = os.path.normpath(tmp_dir + '/fsc_link_' + self.login + '_' + filename + '_' + str(randint(0, 100000)) + '.json')
            dumpConfigToJSON(json_file, "READU_FILE", user_id, file_id, src_file, key)
            self.__SendInfoToFileServer(json_file, server_ip, server_port)
            wx.MessageBox("File downloading {0} has completed!".format(filename), "Message")

        file_info = data.get('file_info', None)
        if file_info:
            file_id, filename, key, server = file_info
            if file_id and filename and key and server:
                dlg = wx.DirDialog(self.gui, "Choose directory for saving file", style=wx.DD_DEFAULT_STYLE)
                if dlg.ShowModal() == wx.ID_OK:
                    save_in = dlg.GetPath()
                    threads.deferToThread(defferedDownloadByLink, data['user_id'], save_in, filename, file_id, key, server)
            else:
                wx.MessageBox("Incorrect link or file has deleted!", "Error")
            del data['user_id']
            del data['file_info']
        else:
            wx.MessageBox("Incorrect link or file has deleted!", "Error")
开发者ID:Relrin,项目名称:Helenae,代码行数:29,代码来源:client_gui.py


示例12: afterDownload

	def afterDownload(self, result, filename, deleteFile=False):
		if os.path.getsize(filename) > 0:
			print>>log, "[EPGImport] afterDownload", filename
			if self.source.parser == 'epg.dat':
				if twisted.python.runtime.platform.supportsThreads():
					print>>log, "[EPGImport] Using twisted thread for DAT file"
					threads.deferToThread(self.readEpgDatFile, filename, deleteFile).addCallback(lambda ignore: self.nextImport())
				else:
					self.readEpgDatFile(filename, deleteFile)
				return
			if filename.endswith('.gz'):
				self.fd = gzip.open(filename, 'rb')
			else:
				self.fd = open(filename, 'rb')
			if twisted.python.runtime.platform.supportsThreads():
				print>>log, "[EPGImport] Using twisted thread!"
				threads.deferToThread(self.doThreadRead).addCallback(lambda ignore: self.nextImport())
			else:
				self.iterator = self.createIterator()
				reactor.addReader(self)
			if deleteFile:
				try:
					print>>log, "[EPGImport] unlink", filename
					os.unlink(filename)
				except Exception, e:
					print>>log, "[EPGImport] warning: Could not remove '%s' intermediate" % filename, e
开发者ID:sotocirus,项目名称:epg_SF_TEAM,代码行数:26,代码来源:EPGImport.py


示例13: connectionMade

    def connectionMade(self, ip, port, honeyIP, honeyPort, sensorName):
        dt = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        self.sensorName = sensorName
        self.honeyIP = honeyIP
        self.honeyPort = honeyPort
        self.logLocation = self.cfg.get('folders', 'session_path') + "/" + self.sensorName + "/"+ ip + "/"
        self.downloadFolder = self.logLocation + 'downloads/'
        self.txtlog_file = self.logLocation + dt + ".log"
        self.endIP = ip
        self.endPort = port
        self.sessionID = uuid.uuid4().hex
        self.passwordTried = False
        self.loginSuccess = False
        self.ttyFiles = []

        
        if self.cfg.get('txtlog', 'enabled') == 'true':
            self.connectionString = '[POT  ] ' + self.sensorName + ' - ' + self.honeyIP + ':' + str(self.honeyPort)
            self.addConnectionString('[SSH  ] Incoming Connection from ' + ip +  ':' + str(port))
            country = self.cname(ip)
            if country != None:
                self.connectionString = self.connectionString + ' - ' + self.cname(ip)
            
        if self.cfg.get('database_mysql', 'enabled') == 'true':
            self.dbLog = mysql.DBLogger()
            self.dbLog.setClient(self.dbLogClient, self.cfg)
                        
        if self.cfg.get('hpfeeds', 'enabled') == 'true':
            self.hpLog = hpfeeds.HPLogger()
            self.hpLog.setClient(self.hpLogClient, self.cfg, self.sensorName)
        
        if self.cfg.has_option('app_hooks', 'connection_made'):
            if self.cfg.get('app_hooks', 'connection_made') != '':
                cmdString = self.cfg.get('app_hooks', 'connection_made') + " CONNECTION_MADE " + dt + " " + self.endIP + " " + str(port) + " " + self.honeyIP
                threads.deferToThread(self.runCommand, cmdString)    
开发者ID:JacobJacob,项目名称:honssh,代码行数:35,代码来源:output.py


示例14: update_schedule

    def update_schedule(self):
        """ Downloads the most recent version of the schedule from the active source.
    
    @note This method loads the schedule from the active source (either a local file or network address) and updates 
          the local copy using callbacks. If use_local_schedule is true, the schedule will be loaded from a local file 
          (specified in the configuration files). If it is false, it will be loaded from the user interface API.
    
    @return Returns a deferred that will be called with the result of the file access (the schedule object or a 
            Failure).
    """

        # Setup local variables
        defer_download = None

        # Attempt to download the schedule
        if self.use_network_schedule:
            defer_download = threads.deferToThread(self._download_remote_schedule)
        else:
            defer_download = threads.deferToThread(self._download_local_schedule)

        # Add a callback to store the schedule
        defer_download.addCallback(self._validate_schedule)
        defer_download.addCallback(self._save_schedule)

        return defer_download
开发者ID:beldonl,项目名称:Mercury2-HWM,代码行数:25,代码来源:schedule.py


示例15: __init__

    def __init__(self, server, **kwargs):
        AbstractBackendStore.__init__(self, server, **kwargs)

        self.name = 'audio CD'
        self.device_name = kwargs.get('device_name', "/dev/cdom")

        threads.deferToThread(self.extractAudioCdInfo)
开发者ID:pezam,项目名称:Cohen,代码行数:7,代码来源:audiocd_storage.py


示例16: auth

        def auth(client):
            @fsync_readonly
            def get_file_status():
                file_id = self._state.file
                try:
                    file = self.usr0.get_node(file_id)
                except errors.DoesNotExist:
                    return 'Dead'
                return file.status

            d = client.dummy_authenticate("open sesame")
            d.addCallback(lambda r: client.get_root())
            d.addCallbacks(
                lambda r: client.make_file(request.ROOT, r, "hola"),
                client.test_fail)
            d.addCallback(lambda req: self._save_state("file", req.new_id))
            d.addCallback(lambda _: threads.deferToThread(get_file_status))
            d.addCallback(lambda status: self.assert_(status == 'Live'))
            d.addCallbacks(
                lambda mkfile_req: client.unlink(request.ROOT,
                                                 self._state.file),
                client.test_fail)
            d.addCallback(lambda _: threads.deferToThread(get_file_status))
            d.addCallback(lambda status: self.assert_(status == 'Dead'))
            d.addCallbacks(client.test_done, client.test_fail)
开发者ID:cloudfleet,项目名称:filesync-server,代码行数:25,代码来源:test_fileops.py


示例17: _gotDMResult

    def _gotDMResult(self, feed):
        plains = []
        feed.entry.reverse()
        hasNew = False
        for a in feed.entry:
            entry = doubanapi.Entry(a)
            entry_id = int(entry.id)
            if entry_id > self.last_dm_id:
                self.last_dm_id = entry_id
                hasNew = True
                if entry.isRead is True:
                    continue

                plain = "Got a doumail from %s: %s\n%s" % (
                    entry.authorName.decode("utf-8"),
                    entry.title.decode("utf-8"),
                    entry.alternateLink,
                )
                plains.append(plain)

        if len(plains) > 0:
            log.msg("User: %s got %s new doumail" % (self.uid, len(plains)))
            conn = protocol.current_conn
            for jid in self.bare_jids():
                conn.send_plain(jid, "\n".join(plains))

        if hasNew:
            threads.deferToThread(self._deferred_write, self.short_jid, "last_dm_id", self.last_dm_id)
开发者ID:guzb,项目名称:doubanbot,代码行数:28,代码来源:scheduling.py


示例18: delete

    def delete(self, combo):
        """HTTP DELETE

        Invalidate a UAID (and all channels associated with it).

        """
        combo = combo.strip("/")
        if "/" in combo:
            (uaid, chid) = combo.split("/", 2)
        else:
            uaid = combo
            chid = None
        # what is request
        if not self._validate_auth(uaid):
            return self._write_response(
                401, 109, message="Invalid Authentication")
        message = self.ap_settings.message
        if chid:
            # mark channel as dead
            self.ap_settings.metrics.increment("updates.client.unregister",
                                               tags=self.base_tags())
            d = deferToThread(self._deleteChannel, message, uaid, chid)
            d.addCallback(self._success)
            d.addErrback(self._chid_not_found_err)
            d.addErrback(self._response_err)
            return d
        # nuke uaid
        d = deferToThread(self._deleteUaid, message, uaid,
                          self.ap_settings.router)
        d.addCallback(self._success)
        d.addErrback(self._uaid_not_found_err)
        d.addErrback(self._response_err)
        return d
开发者ID:ncalexan,项目名称:autopush,代码行数:33,代码来源:endpoint.py


示例19: handleConnectionLost

 def handleConnectionLost(self, dt):
     log.msg('[HPFEEDS] - publishing metadata to hpfeeds')
     meta = self.sessionMeta
     meta['endTime'] = dt
     log.msg("[HPFEEDS] - sessionMeta: " + str(meta))
     
     threads.deferToThread(self.client.publish, HONSSHSESHCHAN, **meta)
开发者ID:CZ-NIC,项目名称:honssh,代码行数:7,代码来源:hpfeeds.py


示例20: send_successful

 def send_successful(self, results):
     """
     Generic callback for when send methods are successful.  This method
     cleans up and shuts down the worker
     """
     if (results):
         threads.deferToThread(self.shutdown)
开发者ID:brianmartin,项目名称:Pydra,代码行数:7,代码来源:worker_task_controls.py



注:本文中的twisted.internet.threads.deferToThread函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python threads.deferToThreadPool函数代码示例发布时间:2022-05-27
下一篇:
Python threads.blockingCallFromThread函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap