当前位置: 首页>>代码示例>>Python>>正文


Python threading.local函数代码示例

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


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


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