Python os.path.startswith() Examples

The following are code examples for showing how to use os.path.startswith(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: planb   Author: ossobv   File: zfs.py    GNU General Public License v3.0 6 votes vote down vote up
def rename_dataset(self, new_dataset_name):
        # Cannot rename while working from the dataset directory.
        # zfs rename will force a unmount/remount sequence for the filesystem
        # and any descendent file systems.
        assert not os.getcwd().startswith(self.get_mount_path()), (
            'Cannot rename dataset {} while working from dataset directory '
            '{}'.format(self.get_mount_path(), os.getcwd()))

        self.backend.zfs_rename_dataset(self.name, new_dataset_name)
        self.name = new_dataset_name

        # Clear cached properties.
        if hasattr(self, '_get_mount_path'):
            del self._get_mount_path
        if hasattr(self, '_get_data_path'):
            del self._get_data_path 
Example 2
Project: smbprotocol   Author: jborean93   File: shutil.py    MIT License 6 votes vote down vote up
def copymode(src, dst, follow_symlinks=True, **kwargs):
    """
    Copy the permission bits from src to dst. The file contents, owner, and group are unaffected. Due to the
    limitations of Windows, this function only sets/unsets the dst's FILE_ATTRIBUTE_READ_ONLY flag based on what src's
    attribute is set to.

    If follow_symlinks is 'False', and both src and dst are symbolic links, copymode() will attempt to modify the mode
    of dst itself (rather than the file it points to).

    This function supports src and dst being either a local or UNC path. A relative path will be resolved based on the
    current working directory.

    :param src: The src file or directory to copy the read only flag from.
    :param dst: The dst file or directory to copy the read only flag to.
    :param follow_symlinks: Whether to copy the read only flag on the symlink or the target of the symlink.
    :param kwargs: Common arguments used to build the SMB Session for any UNC paths.
    """
    src_mode = stat.S_IMODE(_get_file_stat(src, follow_symlinks, **kwargs).st_mode)

    norm_dst = ntpath.normpath(dst)
    if norm_dst.startswith('\\\\'):
        read_only = not (src_mode & stat.S_IWRITE == stat.S_IWRITE and src_mode & stat.S_IREAD == stat.S_IREAD)
        _set_file_basic_info(dst, follow_symlinks, read_only=read_only, **kwargs)
    else:
        _local_chmod(dst, src_mode, follow_symlinks) 
Example 3
Project: tornado-zh   Author: tao12345666333   File: s3server.py    MIT License 6 votes vote down vote up
def put(self, bucket, object_name):
        object_name = urllib.unquote(object_name)
        bucket_dir = os.path.abspath(os.path.join(
            self.application.directory, bucket))
        if not bucket_dir.startswith(self.application.directory) or \
           not os.path.isdir(bucket_dir):
            raise web.HTTPError(404)
        path = self._object_path(bucket, object_name)
        if not path.startswith(bucket_dir) or os.path.isdir(path):
            raise web.HTTPError(403)
        directory = os.path.dirname(path)
        if not os.path.exists(directory):
            os.makedirs(directory)
        object_file = open(path, "w")
        object_file.write(self.request.body)
        object_file.close()
        self.finish() 
Example 4
Project: tornado-zh   Author: tao12345666333   File: web.py    MIT License 6 votes vote down vote up
def get_browser_locale(self, default="en_US"):
        """从 ``Accept-Language`` 头决定用户的位置.

        参考 http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
        """
        if "Accept-Language" in self.request.headers:
            languages = self.request.headers["Accept-Language"].split(",")
            locales = []
            for language in languages:
                parts = language.strip().split(";")
                if len(parts) > 1 and parts[1].startswith("q="):
                    try:
                        score = float(parts[1][2:])
                    except (ValueError, TypeError):
                        score = 0.0
                else:
                    score = 1.0
                locales.append((parts[0], score))
            if locales:
                locales.sort(key=lambda pair: pair[1], reverse=True)
                codes = [l[0] for l in locales]
                return locale.get(*codes)
        return locale.get(default) 
Example 5
Project: tornado-zh   Author: tao12345666333   File: web.py    MIT License 6 votes vote down vote up
def get_browser_locale(self, default="en_US"):
        """从 ``Accept-Language`` 头决定用户的位置.

        参考 http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
        """
        if "Accept-Language" in self.request.headers:
            languages = self.request.headers["Accept-Language"].split(",")
            locales = []
            for language in languages:
                parts = language.strip().split(";")
                if len(parts) > 1 and parts[1].startswith("q="):
                    try:
                        score = float(parts[1][2:])
                    except (ValueError, TypeError):
                        score = 0.0
                else:
                    score = 1.0
                locales.append((parts[0], score))
            if locales:
                locales.sort(key=lambda pair: pair[1], reverse=True)
                codes = [l[0] for l in locales]
                return locale.get(*codes)
        return locale.get(default) 
Example 6
Project: TornadoWeb   Author: VxCoder   File: web.py    Apache License 2.0 6 votes vote down vote up
def get_browser_locale(self, default="en_US"):
        """Determines the user's locale from ``Accept-Language`` header.

        See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
        """
        if "Accept-Language" in self.request.headers:
            languages = self.request.headers["Accept-Language"].split(",")
            locales = []
            for language in languages:
                parts = language.strip().split(";")
                if len(parts) > 1 and parts[1].startswith("q="):
                    try:
                        score = float(parts[1][2:])
                    except (ValueError, TypeError):
                        score = 0.0
                else:
                    score = 1.0
                locales.append((parts[0], score))
            if locales:
                locales.sort(key=lambda pair: pair[1], reverse=True)
                codes = [l[0] for l in locales]
                return locale.get(*codes)
        return locale.get(default) 
Example 7
Project: GLUDB   Author: memphis-iis   File: s3server.py    Apache License 2.0 6 votes vote down vote up
def get(self, bucket, object_name):
        object_name = urllib.unquote(object_name)
        path = self._object_path(bucket, object_name)
        if not path.startswith(self.application.directory) or \
           not os.path.isfile(path):
            raise web.HTTPError(404)
        info = os.stat(path)
        self.object_file_name = path
        self.set_header("Content-Type", "application/unknown")
        self.set_header("Last-Modified", datetime.datetime.utcfromtimestamp(
            info.st_mtime))
        object_file = open(path, "rb")
        self.set_header(
            'x-amz-server-side-encryption-customer-algorithm',
            'testing'
        )
        try:
            self.finish(object_file.read())
        finally:
            object_file.close() 
Example 8
Project: neo4j-social-network   Author: bestvibes   File: easy_install.py    MIT License 6 votes vote down vote up
def unpack_and_compile(self, egg_path, destination):
        to_compile = []; to_chmod = []

        def pf(src,dst):
            if dst.endswith('.py') and not src.startswith('EGG-INFO/'):
                to_compile.append(dst)
                to_chmod.append(dst)
            elif dst.endswith('.dll') or dst.endswith('.so'):
                to_chmod.append(dst)
            self.unpack_progress(src,dst)
            return not self.dry_run and dst or None

        unpack_archive(egg_path, destination, pf)
        self.byte_compile(to_compile)
        if not self.dry_run:
            for f in to_chmod:
                mode = ((os.stat(f)[stat.ST_MODE]) | 0555) & 07755
                chmod(f, mode) 
Example 9
Project: fabsetup   Author: theno   File: fabutils.py    MIT License 6 votes vote down vote up
def _is_sudoer(what_for=''):
    '''Return True if current user is a sudoer, else False.

    Should be called non-eager if sudo is wanted only.
    '''
    if env.get('nosudo', None) is None:
        if what_for:
            print(yellow(what_for))
        with quiet():
            # possible outputs:
            #  en: "Sorry, user winhost-tester may not run sudo on <hostname>"
            #  en: "sudo: a password is required"     (=> is sudoer)
            #  de: "sudo: Ein Passwort ist notwendig" (=> is sudoer)
            output = run('sudo -nv', capture=True)
            env.nosudo = not (output.startswith('sudo: ') or output == '')
        if env.nosudo:
            print('Cannot execute sudo-commands')
    return not env.nosudo 
Example 10
Project: TESTGIT   Author: B-ROY   File: web.py    Apache License 2.0 6 votes vote down vote up
def get_browser_locale(self, default="en_US"):
        """Determines the user's locale from Accept-Language header.

        See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
        """
        if "Accept-Language" in self.request.headers:
            languages = self.request.headers["Accept-Language"].split(",")
            locales = []
            for language in languages:
                parts = language.strip().split(";")
                if len(parts) > 1 and parts[1].startswith("q="):
                    try:
                        score = float(parts[1][2:])
                    except (ValueError, TypeError):
                        score = 0.0
                else:
                    score = 1.0
                locales.append((parts[0], score))
            if locales:
                locales.sort(key=lambda (l, s): s, reverse=True)
                codes = [l[0] for l in locales]
                return locale.get(*codes)
        return locale.get(default) 
Example 11
Project: unhuman-resources   Author: agajdosi   File: web.py    GNU General Public License v3.0 6 votes vote down vote up
def get_browser_locale(self, default: str = "en_US") -> tornado.locale.Locale:
        """Determines the user's locale from ``Accept-Language`` header.

        See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
        """
        if "Accept-Language" in self.request.headers:
            languages = self.request.headers["Accept-Language"].split(",")
            locales = []
            for language in languages:
                parts = language.strip().split(";")
                if len(parts) > 1 and parts[1].startswith("q="):
                    try:
                        score = float(parts[1][2:])
                    except (ValueError, TypeError):
                        score = 0.0
                else:
                    score = 1.0
                locales.append((parts[0], score))
            if locales:
                locales.sort(key=lambda pair: pair[1], reverse=True)
                codes = [l[0] for l in locales]
                return locale.get(*codes)
        return locale.get(default) 
Example 12
Project: unhuman-resources   Author: agajdosi   File: web.py    GNU General Public License v3.0 6 votes vote down vote up
def get_browser_locale(self, default: str = "en_US") -> tornado.locale.Locale:
        """Determines the user's locale from ``Accept-Language`` header.

        See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
        """
        if "Accept-Language" in self.request.headers:
            languages = self.request.headers["Accept-Language"].split(",")
            locales = []
            for language in languages:
                parts = language.strip().split(";")
                if len(parts) > 1 and parts[1].startswith("q="):
                    try:
                        score = float(parts[1][2:])
                    except (ValueError, TypeError):
                        score = 0.0
                else:
                    score = 1.0
                locales.append((parts[0], score))
            if locales:
                locales.sort(key=lambda pair: pair[1], reverse=True)
                codes = [l[0] for l in locales]
                return locale.get(*codes)
        return locale.get(default) 
Example 13
Project: planb   Author: ossobv   File: zfs.py    GNU General Public License v3.0 5 votes vote down vote up
def get_datasets(self):
        output = self._perform_binary_command(('list', '-Hpo', 'name,used'))

        datasets = Datasets()
        for line in output.rstrip().split('\n'):
            dataset_name, used = line.split('\t')

            if dataset_name.startswith(self.poolname + '/'):
                dataset = ZfsDataset(backend=self, name=dataset_name)
                dataset.set_disk_usage(int(used))
                datasets.append(dataset)

        return datasets 
Example 14
Project: planb   Author: ossobv   File: zfs.py    GNU General Public License v3.0 5 votes vote down vote up
def begin_work(self, data_path=None):
        assert os.getcwd() == '/', os.getcwd()

        # The path we want to be in should be a subdirectory of the mount
        # point. Otherwise we cannot be sure that we have it locked.
        path = data_path or self.get_data_path()
        assert path.startswith(self.get_mount_path() + '/'), path

        # Try mounting a few times. There could be someone unmounting it just
        # now.
        for attempt in (1, 2, 3):
            try:
                # Attempt mount.
                self.backend.zfs_mount(self.name)  # zfs dataset
            except CalledProcessError:
                # Maybe it was already mounted?
                pass

            try:
                # Quickly jump into it. If it was already mounted, or we
                # mounted it just now, this should succeed.
                os.chdir(path)
            except FileNotFoundError:
                # Wait a bit before retrying.
                time.sleep(5)
            else:
                # Success!
                break
        else:
            # No luck after the Nth attempt. Fail.
            raise ValueError('Failed to work on {!r} ({})'.format(
                path, self.name))  # FIXME: better exception 
Example 15
Project: smbprotocol   Author: jborean93   File: shutil.py    MIT License 5 votes vote down vote up
def copystat(src, dst, follow_symlinks=True, **kwargs):
    """
    Copy the read only attribute, last access time, and last modification time from src to dst. The file contents,
    owner, and group are unaffected.

    If follow_symlinks is 'False' and src and dst both refer to symbolic links, copystat() will operate on the
    symbolic links themselves rather than the files the symbolic links refer to.

    :param src: The src file or directory to copy the read only flag from.
    :param dst: The dst file or directory to copy the read only flag to.
    :param follow_symlinks: Whether to copy the read only flag on the symlink or the target of the symlink.
    :param kwargs: Common arguments used to build the SMB Session for any UNC paths.
    """
    src_stat = _get_file_stat(src, follow_symlinks, **kwargs)
    src_mode = stat.S_IMODE(src_stat.st_mode)

    # *_ns was only added in Python 3, fallback to a manual calculation from seconds since EPOCH.
    atime_ns = getattr(src_stat, 'st_atime_ns', src_stat.st_atime * 1000000000)
    mtime_ns = getattr(src_stat, 'st_mtime_ns', src_stat.st_mtime * 1000000000)

    norm_dst = ntpath.normpath(dst)
    if norm_dst.startswith('\\\\'):
        read_only = not (src_mode & stat.S_IWRITE == stat.S_IWRITE and src_mode & stat.S_IREAD == stat.S_IREAD)
        _set_file_basic_info(dst, follow_symlinks, read_only=read_only, atime_ns=atime_ns, mtime_ns=mtime_ns, **kwargs)
    else:
        if not follow_symlinks and sys.version_info[0] < 3:
            # Python 2 always follows symlinks and does not have a kwarg to override, we can only just fail here.
            raise NotImplementedError("utime: follow_symlinks unavailable on this platform")

        _local_chmod(dst, src_mode, follow_symlinks)

        if sys.version_info[0] < 3:
            os.utime(dst, (atime_ns / 1000000000, mtime_ns / 1000000000))
        else:
            os.utime(dst, ns=(atime_ns, mtime_ns), follow_symlinks=follow_symlinks) 
Example 16
Project: smbprotocol   Author: jborean93   File: shutil.py    MIT License 5 votes vote down vote up
def _copy(src, dst, follow_symlinks, copy_meta_func, **kwargs):
    # Need to check if dst is a UNC path before checking if it's a dir in smbclient.path before checking to see if it's
    # a local directory. If either one is a dir, join the filename of src onto dst.
    if ntpath.normpath(dst).startswith('\\\\') and isdir(dst, **kwargs):
        dst = ntpath.join(dst, ntpath.basename(src))
    elif os.path.isdir(dst):
        dst = os.path.join(dst, os.path.basename(src))

    copyfile(src, dst, follow_symlinks=follow_symlinks)
    copy_meta_func(src, dst, follow_symlinks=follow_symlinks)
    return dst 
Example 17
Project: smbprotocol   Author: jborean93   File: shutil.py    MIT License 5 votes vote down vote up
def _get_file_stat(path, follow_symlinks=True, **kwargs):
    if path.startswith('//') or path.startswith('\\\\'):
        return smbclient_stat(path, follow_symlinks=follow_symlinks, **kwargs)
    else:
        # Source is a local path or accessible to the host, use the builtin os module to get the read only flag.
        if follow_symlinks:
            return os.stat(path)
        else:
            return os.lstat(path) 
Example 18
Project: AshsSDK   Author: thehappydinoa   File: misc.py    MIT License 5 votes vote down vote up
def run(self):
        """Include a file as part of the content of this reST file."""
        if not self.state.document.settings.file_insertion_enabled:
            raise self.warning('"%s" directive disabled.' % self.name)
        source = self.state_machine.input_lines.source(
            self.lineno - self.state_machine.input_offset - 1)
        source_dir = os.path.dirname(os.path.abspath(source))
        path = directives.path(self.arguments[0])
        if path.startswith('<') and path.endswith('>'):
            path = os.path.join(self.standard_include_path, path[1:-1])
        path = os.path.normpath(os.path.join(source_dir, path))
        path = utils.relative_path(None, path)
        path = nodes.reprunicode(path)
        encoding = self.options.get(
            'encoding', self.state.document.settings.input_encoding)
        e_handler=self.state.document.settings.input_encoding_error_handler
        tab_width = self.options.get(
            'tab-width', self.state.document.settings.tab_width)
        try:
            self.state.document.settings.record_dependencies.add(path)
            include_file = io.FileInput(source_path=path,
                                        encoding=encoding,
                                        error_handler=e_handler)
        except UnicodeEncodeError, error:
            raise self.severe(u'Problems with "%s" directive path:\n'
                              'Cannot encode input file path "%s" '
                              '(wrong locale?).' %
                              (self.name, SafeString(path))) 
Example 19
Project: senior_design_spring   Author: wodiesan   File: init_logger.py    MIT License 5 votes vote down vote up
def checkdir(path):
    '''Ensure that the path doesn't contain trailing slashes.'''
    path = posixpath.normpath(path)
    return not path.startswith(('/', '../')) 
Example 20
Project: tornado-zh   Author: tao12345666333   File: s3server.py    MIT License 5 votes vote down vote up
def put(self, bucket_name):
        path = os.path.abspath(os.path.join(
            self.application.directory, bucket_name))
        if not path.startswith(self.application.directory) or \
           os.path.exists(path):
            raise web.HTTPError(403)
        os.makedirs(path)
        self.finish() 
Example 21
Project: tornado-zh   Author: tao12345666333   File: s3server.py    MIT License 5 votes vote down vote up
def delete(self, bucket_name):
        path = os.path.abspath(os.path.join(
            self.application.directory, bucket_name))
        if not path.startswith(self.application.directory) or \
           not os.path.isdir(path):
            raise web.HTTPError(404)
        if len(os.listdir(path)) > 0:
            raise web.HTTPError(403)
        os.rmdir(path)
        self.set_status(204)
        self.finish() 
Example 22
Project: tornado-zh   Author: tao12345666333   File: s3server.py    MIT License 5 votes vote down vote up
def get(self, bucket, object_name):
        object_name = urllib.unquote(object_name)
        path = self._object_path(bucket, object_name)
        if not path.startswith(self.application.directory) or \
           not os.path.isfile(path):
            raise web.HTTPError(404)
        info = os.stat(path)
        self.set_header("Content-Type", "application/unknown")
        self.set_header("Last-Modified", datetime.datetime.utcfromtimestamp(
            info.st_mtime))
        object_file = open(path, "rb")
        try:
            self.finish(object_file.read())
        finally:
            object_file.close() 
Example 23
Project: tornado-zh   Author: tao12345666333   File: web.py    MIT License 5 votes vote down vote up
def check_etag_header(self):
        """针对请求的 ``If-None-Match`` 头检查 ``Etag`` 头.

        如果请求的ETag 匹配则返回 ``True`` 并将返回一个304. 例如::

            self.set_etag_header()
            if self.check_etag_header():
                self.set_status(304)
                return

        这个方法在请求结束的时候会被自动调用, 但也可以被更早的调用
        当复写了 `compute_etag` 并且想在请求完成之前先做一个
        ``If-None-Match`` 检查. ``Etag`` 头应该在这个方法被调用前设置
        (可以使用 `set_etag_header`).
        """
        computed_etag = utf8(self._headers.get("Etag", ""))
        # Find all weak and strong etag values from If-None-Match header
        # because RFC 7232 allows multiple etag values in a single header.
        etags = re.findall(
            br'\*|(?:W/)?"[^"]*"',
            utf8(self.request.headers.get("If-None-Match", ""))
        )
        if not computed_etag or not etags:
            return False

        match = False
        if etags[0] == b'*':
            match = True
        else:
            # Use a weak comparison when comparing entity-tags.
            val = lambda x: x[2:] if x.startswith(b'W/') else x
            for etag in etags:
                if val(etag) == val(computed_etag):
                    match = True
                    break
        return match 
Example 24
Project: tornado-zh   Author: tao12345666333   File: web.py    MIT License 5 votes vote down vote up
def _load_ui_methods(self, methods):
        if isinstance(methods, types.ModuleType):
            self._load_ui_methods(dict((n, getattr(methods, n))
                                       for n in dir(methods)))
        elif isinstance(methods, list):
            for m in methods:
                self._load_ui_methods(m)
        else:
            for name, fn in methods.items():
                if not name.startswith("_") and hasattr(fn, "__call__") \
                        and name[0].lower() == name[0]:
                    self.ui_methods[name] = fn 
Example 25
Project: tornado-zh   Author: tao12345666333   File: web.py    MIT License 5 votes vote down vote up
def _compressible_type(self, ctype):
        return ctype.startswith('text/') or ctype in self.CONTENT_TYPES 
Example 26
Project: tornado-zh   Author: tao12345666333   File: web.py    MIT License 5 votes vote down vote up
def _decode_signed_value_v1(secret, name, value, max_age_days, clock):
    parts = utf8(value).split(b"|")
    if len(parts) != 3:
        return None
    signature = _create_signature_v1(secret, name, parts[0], parts[1])
    if not _time_independent_equals(parts[2], signature):
        gen_log.warning("Invalid cookie signature %r", value)
        return None
    timestamp = int(parts[1])
    if timestamp < clock() - max_age_days * 86400:
        gen_log.warning("Expired cookie %r", value)
        return None
    if timestamp > clock() + 31 * 86400:
        # _cookie_signature does not hash a delimiter between the
        # parts of the cookie, so an attacker could transfer trailing
        # digits from the payload to the timestamp without altering the
        # signature.  For backwards compatibility, sanity-check timestamp
        # here instead of modifying _cookie_signature.
        gen_log.warning("Cookie timestamp in future; possible tampering %r",
                        value)
        return None
    if parts[1].startswith(b"0"):
        gen_log.warning("Tampered cookie %r", value)
        return None
    try:
        return base64.b64decode(parts[0])
    except Exception:
        return None 
Example 27
Project: tornado-zh   Author: tao12345666333   File: web.py    MIT License 5 votes vote down vote up
def check_etag_header(self):
        """针对请求的 ``If-None-Match`` 头检查 ``Etag`` 头.

        如果请求的ETag 匹配则返回 ``True`` 并将返回一个304. 例如::

            self.set_etag_header()
            if self.check_etag_header():
                self.set_status(304)
                return

        这个方法在请求结束的时候会被自动调用, 但也可以被更早的调用
        当复写了 `compute_etag` 并且想在请求完成之前先做一个
        ``If-None-Match`` 检查. ``Etag`` 头应该在这个方法被调用前设置
        (可以使用 `set_etag_header`).
        """
        computed_etag = utf8(self._headers.get("Etag", ""))
        # Find all weak and strong etag values from If-None-Match header
        # because RFC 7232 allows multiple etag values in a single header.
        etags = re.findall(
            br'\*|(?:W/)?"[^"]*"',
            utf8(self.request.headers.get("If-None-Match", ""))
        )
        if not computed_etag or not etags:
            return False

        match = False
        if etags[0] == b'*':
            match = True
        else:
            # Use a weak comparison when comparing entity-tags.
            val = lambda x: x[2:] if x.startswith(b'W/') else x
            for etag in etags:
                if val(etag) == val(computed_etag):
                    match = True
                    break
        return match 
Example 28
Project: tornado-zh   Author: tao12345666333   File: web.py    MIT License 5 votes vote down vote up
def _load_ui_methods(self, methods):
        if isinstance(methods, types.ModuleType):
            self._load_ui_methods(dict((n, getattr(methods, n))
                                       for n in dir(methods)))
        elif isinstance(methods, list):
            for m in methods:
                self._load_ui_methods(m)
        else:
            for name, fn in methods.items():
                if not name.startswith("_") and hasattr(fn, "__call__") \
                        and name[0].lower() == name[0]:
                    self.ui_methods[name] = fn 
Example 29
Project: tornado-zh   Author: tao12345666333   File: web.py    MIT License 5 votes vote down vote up
def _find_groups(self):
        """返回一个基于url的元组(reverse string, group count).

        例如: 给定一个url 模式 /([0-9]{4})/([a-z-]+)/, 这个方法
        将会返回('/%s/%s/', 2).
        """
        pattern = self.regex.pattern
        if pattern.startswith('^'):
            pattern = pattern[1:]
        if pattern.endswith('$'):
            pattern = pattern[:-1]

        if self.regex.groups != pattern.count('('):
            # The pattern is too complicated for our simplistic matching,
            # so we can't support reversing it.
            return (None, None)

        pieces = []
        for fragment in pattern.split('('):
            if ')' in fragment:
                paren_loc = fragment.index(')')
                if paren_loc >= 0:
                    pieces.append('%s' + fragment[paren_loc + 1:])
            else:
                pieces.append(fragment)

        return (''.join(pieces), self.regex.groups) 
Example 30
Project: tornado-zh   Author: tao12345666333   File: web.py    MIT License 5 votes vote down vote up
def _decode_signed_value_v1(secret, name, value, max_age_days, clock):
    parts = utf8(value).split(b"|")
    if len(parts) != 3:
        return None
    signature = _create_signature_v1(secret, name, parts[0], parts[1])
    if not _time_independent_equals(parts[2], signature):
        gen_log.warning("Invalid cookie signature %r", value)
        return None
    timestamp = int(parts[1])
    if timestamp < clock() - max_age_days * 86400:
        gen_log.warning("Expired cookie %r", value)
        return None
    if timestamp > clock() + 31 * 86400:
        # _cookie_signature does not hash a delimiter between the
        # parts of the cookie, so an attacker could transfer trailing
        # digits from the payload to the timestamp without altering the
        # signature.  For backwards compatibility, sanity-check timestamp
        # here instead of modifying _cookie_signature.
        gen_log.warning("Cookie timestamp in future; possible tampering %r",
                        value)
        return None
    if parts[1].startswith(b"0"):
        gen_log.warning("Tampered cookie %r", value)
        return None
    try:
        return base64.b64decode(parts[0])
    except Exception:
        return None 
Example 31
Project: TornadoWeb   Author: VxCoder   File: web.py    Apache License 2.0 5 votes vote down vote up
def check_etag_header(self):
        """Checks the ``Etag`` header against requests's ``If-None-Match``.

        Returns ``True`` if the request's Etag matches and a 304 should be
        returned. For example::

            self.set_etag_header()
            if self.check_etag_header():
                self.set_status(304)
                return

        This method is called automatically when the request is finished,
        but may be called earlier for applications that override
        `compute_etag` and want to do an early check for ``If-None-Match``
        before completing the request.  The ``Etag`` header should be set
        (perhaps with `set_etag_header`) before calling this method.
        """
        computed_etag = utf8(self._headers.get("Etag", ""))
        # Find all weak and strong etag values from If-None-Match header
        # because RFC 7232 allows multiple etag values in a single header.
        etags = re.findall(
            br'\*|(?:W/)?"[^"]*"',
            utf8(self.request.headers.get("If-None-Match", ""))
        )
        if not computed_etag or not etags:
            return False

        match = False
        if etags[0] == b'*':
            match = True
        else:
            # Use a weak comparison when comparing entity-tags.
            def val(x):
                return x[2:] if x.startswith(b'W/') else x

            for etag in etags:
                if val(etag) == val(computed_etag):
                    match = True
                    break
        return match 
Example 32
Project: TornadoWeb   Author: VxCoder   File: web.py    Apache License 2.0 5 votes vote down vote up
def _load_ui_methods(self, methods):
        if isinstance(methods, types.ModuleType):
            self._load_ui_methods(dict((n, getattr(methods, n))
                                       for n in dir(methods)))
        elif isinstance(methods, list):
            for m in methods:
                self._load_ui_methods(m)
        else:
            for name, fn in methods.items():
                if not name.startswith("_") and hasattr(fn, "__call__") \
                        and name[0].lower() == name[0]:
                    self.ui_methods[name] = fn 
Example 33
Project: TornadoWeb   Author: VxCoder   File: web.py    Apache License 2.0 5 votes vote down vote up
def _compressible_type(self, ctype):
        return ctype.startswith('text/') or ctype in self.CONTENT_TYPES 
Example 34
Project: TornadoWeb   Author: VxCoder   File: web.py    Apache License 2.0 5 votes vote down vote up
def _decode_signed_value_v1(secret, name, value, max_age_days, clock):
    parts = utf8(value).split(b"|")
    if len(parts) != 3:
        return None
    signature = _create_signature_v1(secret, name, parts[0], parts[1])
    if not _time_independent_equals(parts[2], signature):
        gen_log.warning("Invalid cookie signature %r", value)
        return None
    timestamp = int(parts[1])
    if timestamp < clock() - max_age_days * 86400:
        gen_log.warning("Expired cookie %r", value)
        return None
    if timestamp > clock() + 31 * 86400:
        # _cookie_signature does not hash a delimiter between the
        # parts of the cookie, so an attacker could transfer trailing
        # digits from the payload to the timestamp without altering the
        # signature.  For backwards compatibility, sanity-check timestamp
        # here instead of modifying _cookie_signature.
        gen_log.warning("Cookie timestamp in future; possible tampering %r",
                        value)
        return None
    if parts[1].startswith(b"0"):
        gen_log.warning("Tampered cookie %r", value)
        return None
    try:
        return base64.b64decode(parts[0])
    except Exception:
        return None 
Example 35
Project: GLUDB   Author: memphis-iis   File: s3server.py    Apache License 2.0 5 votes vote down vote up
def head(self, bucket_name):
        path = os.path.abspath(os.path.join(
            self.application.directory,
            bucket_name
        ))
        if (
            not path.startswith(self.application.directory) or
            not os.path.isdir(path)
        ):
            raise web.HTTPError(404)
        self.set_status(200)
        self.finish() 
Example 36
Project: GLUDB   Author: memphis-iis   File: s3server.py    Apache License 2.0 5 votes vote down vote up
def put(self, bucket_name):
        path = os.path.abspath(os.path.join(
            self.application.directory, bucket_name))
        if not path.startswith(self.application.directory) or \
           os.path.exists(path):
            raise web.HTTPError(403)
        os.makedirs(path)
        self.finish() 
Example 37
Project: GLUDB   Author: memphis-iis   File: s3server.py    Apache License 2.0 5 votes vote down vote up
def delete(self, bucket_name):
        path = os.path.abspath(os.path.join(
            self.application.directory, bucket_name))
        if not path.startswith(self.application.directory) or \
           not os.path.isdir(path):
            raise web.HTTPError(404)
        if len(os.listdir(path)) > 0:
            raise web.HTTPError(403)
        os.rmdir(path)
        self.set_status(204)
        self.finish() 
Example 38
Project: GLUDB   Author: memphis-iis   File: s3server.py    Apache License 2.0 5 votes vote down vote up
def delete(self, bucket, object_name):
        object_name = urllib.unquote(object_name)
        path = self._object_path(bucket, object_name)
        if not path.startswith(self.application.directory) or \
           not os.path.isfile(path):
            raise web.HTTPError(404)
        self.object_file_name = path
        self.set_etag_header()
        os.unlink(path)
        self.set_status(204)
        self.set_header(
            'x-amz-server-side-encryption-customer-algorithm',
            'testing'
        )
        self.finish() 
Example 39
Project: Zoom2Youtube   Author: Welltory   File: zoom.py    MIT License 5 votes vote down vote up
def _join_url(self, path):
        if path.startswith('/'):
            path = path[1:]
        return urljoin(ZoomClient.BASE_URL, path) 
Example 40
Project: ems   Author: mtils   File: app.py    MIT License 5 votes vote down vote up
def relative_path(path):

    appPath = app_path()

    if not path.startswith(appPath):
        return path

    rPath = path.replace(appPath, "")
    if rPath.startswith(os.path.sep):
        return rPath[1:]
    return rPath 
Example 41
Project: ems   Author: mtils   File: app.py    MIT License 5 votes vote down vote up
def absolute_path(path):

    if os.path.isabs(path):
        return path

    if not path.startswith(os.path.sep):
        return os.path.join(app_path(), path)

    return path 
Example 42
Project: ems   Author: mtils   File: qwidget_application.py    MIT License 5 votes vote down vote up
def getRelativePath(self, path):
        rPath = path.replace(self.appPath, "")
        if rPath.startswith(os.path.sep):
            return rPath[1:]
        return rPath 
Example 43
Project: ems   Author: mtils   File: qwidget_application.py    MIT License 5 votes vote down vote up
def getAbsolutePath(self, path):
        if os.path.isabs(path):
            return path
        if not path.startswith(os.path.sep):
            return os.path.join(self.appPath, path)
        return path 
Example 44
Project: ems   Author: mtils   File: application.py    MIT License 5 votes vote down vote up
def getRelativePath(self, path):
        rPath = path.replace(self.appPath, "")
        if rPath.startswith(os.path.sep):
            return rPath[1:]
        return rPath 
Example 45
Project: data-repository-service-schemas   Author: ga4gh   File: schema.py    Apache License 2.0 5 votes vote down vote up
def from_chalice_routes(routes, base_path=''):
    """
    Given a :obj:`chalice.Chalice.routes` objects, computes the proper
    subset of the Data Object Service schema and presents it as an
    OpenAPI 2.0 JSON schema.
    :rvtype: dict
    :param chalice.Chalice.routes routes:
    :param str base_path: the base path of the endpoints listed in `routes`.
                          This is only necessary if a base path is manually
                          prepended to each endpoint your service exposes,
                          e.g. ``@app.route('/ga4gh/drs/v1/dataobjects')``.
                          This string will be stripped from the beginning of
                          each path in the `routes` object if it is present.
                          The schema will be updated with this value.
    """
    schema = present_schema()

    # Sanitize the routes that are provided so we can compare them easily.
    schema['basePath'] = base_path.rstrip('/').lower() or schema['basePath'].lower()
    sanitized = {}
    for chalice_path, chalice_methods in routes.items():
        path = chalice_path.lower()
        if path.startswith(schema['basePath']):
            path = path.replace(schema['basePath'], '', 1)
        sanitized[path] = [i.lower() for i in chalice_methods]
    routes = sanitized

    # Next, remove from the generated schema paths that are not defined
    # in :obj:`routes`.
    schema['paths'] = {k: v for k, v in schema['paths'].items()
                       if k in routes.keys()}

    # Loop over the remaining paths in the generated schema and remove
    # methods that are not listed in :obj:`routes`.
    for path in schema['paths'].keys():
        schema['paths'][path] = {k: v for k, v in schema['paths'][path].items()
                                 if k in [r.lower() for r in routes[path]]}

    return schema 
Example 46
Project: codimension   Author: SergeySatskiy   File: filesbrowserbase.py    GNU General Public License v3.0 5 votes vote down vote up
def _onFSChanged(self, items):
        """Triggered when the project files set has been changed"""
        itemsToDel = []
        itemsToAdd = []
        for item in items:
            item = str(item)
            if item.startswith('-'):
                itemsToDel.append(item[1:])
            else:
                itemsToAdd.append(item[1:])
        itemsToDel.sort()
        itemsToAdd.sort()

        # It is important that items are deleted first and then new are added!
        for item in itemsToDel:
            dirname, basename = self._splitPath(item)

            # For all root items
            for treeItem in self.model().sourceModel().rootItem.childItems:
                self._delFromTree(treeItem, dirname, basename)

        for item in itemsToAdd:
            dirname, basename = self._splitPath(item)

            # For all root items
            for treeItem in self.model().sourceModel().rootItem.childItems:
                self.__addToTree(treeItem, item, dirname, basename)

        self.layoutDisplay() 
Example 47
Project: aws-cfn-plex   Author: lordmuffin   File: misc.py    MIT License 5 votes vote down vote up
def run(self):
        """Include a file as part of the content of this reST file."""
        if not self.state.document.settings.file_insertion_enabled:
            raise self.warning('"%s" directive disabled.' % self.name)
        source = self.state_machine.input_lines.source(
            self.lineno - self.state_machine.input_offset - 1)
        source_dir = os.path.dirname(os.path.abspath(source))
        path = directives.path(self.arguments[0])
        if path.startswith('<') and path.endswith('>'):
            path = os.path.join(self.standard_include_path, path[1:-1])
        path = os.path.normpath(os.path.join(source_dir, path))
        path = utils.relative_path(None, path)
        path = nodes.reprunicode(path)
        encoding = self.options.get(
            'encoding', self.state.document.settings.input_encoding)
        e_handler=self.state.document.settings.input_encoding_error_handler
        tab_width = self.options.get(
            'tab-width', self.state.document.settings.tab_width)
        try:
            self.state.document.settings.record_dependencies.add(path)
            include_file = io.FileInput(source_path=path,
                                        encoding=encoding,
                                        error_handler=e_handler)
        except UnicodeEncodeError, error:
            raise self.severe(u'Problems with "%s" directive path:\n'
                              'Cannot encode input file path "%s" '
                              '(wrong locale?).' %
                              (self.name, SafeString(path))) 
Example 48
Project: neo4j-social-network   Author: bestvibes   File: easy_install.py    MIT License 5 votes vote down vote up
def install_eggs(self, spec, dist_filename, tmpdir):
        # .egg dirs or files are already built, so just return them
        if dist_filename.lower().endswith('.egg'):
            return [self.install_egg(dist_filename, tmpdir)]
        elif dist_filename.lower().endswith('.exe'):
            return [self.install_exe(dist_filename, tmpdir)]

        # Anything else, try to extract and build
        setup_base = tmpdir
        if os.path.isfile(dist_filename) and not dist_filename.endswith('.py'):
            unpack_archive(dist_filename, tmpdir, self.unpack_progress)
        elif os.path.isdir(dist_filename):
            setup_base = os.path.abspath(dist_filename)

        if (setup_base.startswith(tmpdir)   # something we downloaded
            and self.build_directory and spec is not None
        ):
            setup_base = self.maybe_move(spec, dist_filename, setup_base)

        # Find the setup.py file
        setup_script = os.path.join(setup_base, 'setup.py')

        if not os.path.exists(setup_script):
            setups = glob(os.path.join(setup_base, '*', 'setup.py'))
            if not setups:
                raise DistutilsError(
                    "Couldn't find a setup script in %s" % os.path.abspath(dist_filename)
                )
            if len(setups)>1:
                raise DistutilsError(
                    "Multiple setup scripts in %s" % os.path.abspath(dist_filename)
                )
            setup_script = setups[0]

        # Now run it, and return the result
        if self.editable:
            log.info(self.report_editable(spec, setup_script))
            return []
        else:
            return self.build_and_install(setup_script, setup_base) 
Example 49
Project: neo4j-social-network   Author: bestvibes   File: easy_install.py    MIT License 5 votes vote down vote up
def install_egg(self, egg_path, tmpdir):
        destination = os.path.join(self.install_dir,os.path.basename(egg_path))
        destination = os.path.abspath(destination)
        if not self.dry_run:
            ensure_directory(destination)

        dist = self.egg_distribution(egg_path)
        self.check_conflicts(dist)
        if not samefile(egg_path, destination):
            if os.path.isdir(destination) and not os.path.islink(destination):
                dir_util.remove_tree(destination, dry_run=self.dry_run)
            elif os.path.exists(destination):
                self.execute(os.unlink,(destination,),"Removing "+destination)
            uncache_zipdir(destination)
            if os.path.isdir(egg_path):
                if egg_path.startswith(tmpdir):
                    f,m = shutil.move, "Moving"
                else:
                    f,m = shutil.copytree, "Copying"
            elif self.should_unzip(dist):
                self.mkpath(destination)
                f,m = self.unpack_and_compile, "Extracting"
            elif egg_path.startswith(tmpdir):
                f,m = shutil.move, "Moving"
            else:
                f,m = shutil.copy2, "Copying"

            self.execute(f, (egg_path, destination),
                (m+" %s to %s") %
                (os.path.basename(egg_path),os.path.dirname(destination)))

        self.add_output(destination)
        return self.egg_distribution(destination) 
Example 50
Project: neo4j-social-network   Author: bestvibes   File: easy_install.py    MIT License 5 votes vote down vote up
def create_home_path(self):
        """Create directories under ~."""
        if not self.user:
            return
        home = convert_path(os.path.expanduser("~"))
        for name, path in self.config_vars.iteritems():
            if path.startswith(home) and not os.path.isdir(path):
                self.debug_print("os.makedirs('%s', 0700)" % path)
                os.makedirs(path, 0700)