How to use the portalocker.lock function in portalocker

To help you get started, we’ve selected a few portalocker examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github spiffytech / MobileBlur / gluon / globals.py View on Github external
client = request.client and request.client.replace(':', '.')
            if response.session_id_name in request.cookies:
                response.session_id = \
                    request.cookies[response.session_id_name].value
                if regex_session_id.match(response.session_id):
                    response.session_filename = \
                        os.path.join(up(request.folder), masterapp,
                            'sessions', response.session_id)
                else:
                    response.session_id = None
            if response.session_id:
                try:
                    response.session_file = \
                        open(response.session_filename, 'rb+')
                    try:
                        portalocker.lock(response.session_file,portalocker.LOCK_EX)
                        response.session_locked = True
                        self.update(cPickle.load(response.session_file))
                        response.session_file.seek(0)
                        oc = response.session_filename.split('/')[-1].split('-')[0]
                        if check_client and client!=oc:
                            raise Exception, "cookie attack"
                    finally:
                        pass
                        #This causes admin login to break. Must find out why.
                        #self._close(response)
                except:
                    response.session_id = None
            if not response.session_id:
                uuid = web2py_uuid()
                response.session_id = '%s-%s' % (client, uuid)
                if separate:
github realpython / book2-exercises / py2manager / gluon / newcron.py View on Github external
stop == 0 if job started but did not yet complete
        if a cron job started within less than 60 seconds, acquire returns None
        if a cron job started before 60 seconds and did not stop,
        a warning is issue "Stale cron.master detected"
        """
        if sys.platform == 'win32':
            locktime = 59.5
        else:
            locktime = 59.99
        if portalocker.LOCK_EX is None:
            logger.warning('WEB2PY CRON: Disabled because no file locking')
            return None
        self.master = open(self.path, 'rb+')
        try:
            ret = None
            portalocker.lock(self.master, portalocker.LOCK_EX)
            try:
                (start, stop) = pickle.load(self.master)
            except:
                (start, stop) = (0, 1)
            if startup or self.now - start > locktime:
                ret = self.now
                if not stop:
                    # this happens if previous cron job longer than 1 minute
                    logger.warning('WEB2PY CRON: Stale cron.master detected')
                logger.debug('WEB2PY CRON: Acquiring lock')
                self.master.seek(0)
                pickle.dump((self.now, 0), self.master)
                self.master.flush()
        finally:
            portalocker.unlock(self.master)
        if not ret:
github aosabook / 500lines / data-store / dbdb / storage.py View on Github external
def lock(self):
        if not self.locked:
            portalocker.lock(self._f, portalocker.LOCK_EX)
            self.locked = True
            return True
        else:
            return False
github hyperledger / indy-plenum / stp_core / network / port_dispenser.py View on Github external
def get(self, count: int=1, readOnly: bool=False, recurlvl=0):
        with open(self.FILE, "r+") as file:
            portalocker.lock(file, portalocker.LOCK_EX)
            ports = []
            while len(ports) < count:
                file.seek(0)
                port = int(file.readline())
                if readOnly:
                    return port
                port += 1
                if port > self.maxPort:
                    port = self.minPort
                file.seek(0)
                file.write(str(port))
                try:
                    checkPortAvailable(("", port))
                    ports.append(port)
                    self.logger.debug("new port dispensed: {}".format(port))
                except:
github pyspace / pyspace / pySPACE / missions / nodes / meta / same_input_layer.py View on Github external
def _load_cache(self):
        self.cache = defaultdict(dict)
        # Check if there are cached results for this ensemble
        for flow_path in self.flow_pathes: 
            file_path = self.cache_dir + os.sep + "ensemble_cache" + os.sep \
                            + "cache_%s" % hash(flow_path)
            if os.path.exists(file_path):
                # Load ensemble cache
                self._log("Loading flow cache from %s" % file_path)
                lock_file = open(file_path + ".lock", 'w')
                portalocker.lock(lock_file, portalocker.LOCK_EX)
                # fcntl.flock(lock_file, fcntl.LOCK_EX)
                self._log("Got exclusive lock on %s" % (file_path + ".lock"),
                          logging.INFO)
                cache_file = open(file_path, 'r')
                self.cache[flow_path] = cPickle.load(cache_file)
                cache_file.close()
                self._log("Release exclusive lock on %s" % (file_path + ".lock"),
                          logging.INFO)
                # fcntl.flock(lock_file, fcntl.LOCK_UN)
                portalocker.unlock(lock_file)
github thought-machine / please / tools / please_pex / pex / pex_main.py View on Github external
def pex_lockfile(basepath, uniquedir):
        # Acquire the lockfile.
        lockfile_path = os.path.join(basepath, '.lock-%s' % uniquedir)
        lockfile = open(lockfile_path, "a+")
        # Block until we can acquire the lockfile.
        portalocker.lock(lockfile, portalocker.LOCK_EX)
        lockfile.seek(0)
        yield lockfile
        portalocker.lock(lockfile, portalocker.LOCK_UN)
github hyperledger / indy-plenum / plenum / common / port_dispenser.py View on Github external
def get(self, count: int=1, readOnly: bool=False, recurlvl=0):
        with open(self.FILE, "r+") as file:
            portalocker.lock(file, portalocker.LOCK_EX)
            ports = []
            while len(ports) < count:
                file.seek(0)
                port = int(file.readline())
                if readOnly:
                    return port
                port += 1
                if port > self.maxPort:
                    port = self.minPort
                file.seek(0)
                file.write(str(port))
                try:
                    checkPortAvailable(("",port))
                    ports.append(port)
                    self.logger.debug("new port dispensed: {}".format(port))
                except:
github mayank93 / Twitter-Sentiment-Analysis / front-end / web2py / gluon / globals.py View on Github external
del self.__hash
            if __hash == hashlib.md5(str(self)).digest():
                self._close(response)
                return

        if not response.session_id or self._forget:
            self._close(response)
            return

        if response.session_new:
            # Tests if the session sub-folder exists, if not, create it
            session_folder = os.path.dirname(response.session_filename)
            if not os.path.exists(session_folder):
                os.mkdir(session_folder)
            response.session_file = open(response.session_filename, 'wb')
            portalocker.lock(response.session_file, portalocker.LOCK_EX)
            response.session_locked = True

        if response.session_file:
            cPickle.dump(dict(self), response.session_file)
            response.session_file.truncate()
            self._close(response)