當前位置: 首頁>>代碼示例>>Python>>正文


Python version.InvalidVersion方法代碼示例

本文整理匯總了Python中packaging.version.InvalidVersion方法的典型用法代碼示例。如果您正苦於以下問題:Python version.InvalidVersion方法的具體用法?Python version.InvalidVersion怎麽用?Python version.InvalidVersion使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在packaging.version的用法示例。


在下文中一共展示了version.InvalidVersion方法的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: deserialize_version

# 需要導入模塊: from packaging import version [as 別名]
# 或者: from packaging.version import InvalidVersion [as 別名]
def deserialize_version(version: str) -> Version:
    try:
        return Version(version)
    except InvalidVersion as e:
        raise SerializerError("Invalid version") from e 
開發者ID:maubot,項目名稱:maubot,代碼行數:7,代碼來源:abc.py

示例2: version

# 需要導入模塊: from packaging import version [as 別名]
# 或者: from packaging.version import InvalidVersion [as 別名]
def version(val: str) -> Version:
    try:
        return Version(val)
    except InvalidVersion as e:
        raise click.BadParameter(f"{val} is not a valid PEP-440 version") from e 
開發者ID:maubot,項目名稱:maubot,代碼行數:7,代碼來源:validators.py

示例3: _translate_index_item

# 需要導入模塊: from packaging import version [as 別名]
# 或者: from packaging.version import InvalidVersion [as 別名]
def _translate_index_item(test_id, i, _, item):
    name = item["name"]
    try:
        version = Version(item["version"])
    except InvalidVersion:
        raise MalformedYAML(
            test_id, "index[{}] has an invalid version: {}", i, item["version"]
        )

    # Compose Dependencies
    dependencies = {}
    errors = AggregatedYAMLErrors()

    # Top level first.
    key = "{} {}".format(name, version)
    try:
        dependencies[key] = _translate_list(
            test_id, item["depends"], "index[{}], depends".format(i), function=_make_req
        )
    except YAMLException as e:
        errors.add(e)

    # Extras next.
    for extra in item["extras"]:
        key = "{}[{}] {}".format(name, extra, version)
        try:
            dependencies[key] = _translate_list(
                test_id,
                item["extras"][extra],
                "index[{}], extra={!r}".format(i, extra),
                function=_make_req,
            )
        except YAMLException as e:
            errors.add(e)

    if errors:
        raise errors

    return YAMLCandidate(name, version), dependencies 
開發者ID:pradyunsg,項目名稱:zazo,代碼行數:41,代碼來源:translate.py

示例4: get_project_from_pypi

# 需要導入模塊: from packaging import version [as 別名]
# 或者: from packaging.version import InvalidVersion [as 別名]
def get_project_from_pypi(project, extras):
    """Return candidates created from the project name and extras."""
    url = "https://pypi.org/simple/{}".format(project)
    data = requests.get(url).content
    doc = html5lib.parse(data, namespaceHTMLElements=False)
    for i in doc.findall(".//a"):
        url = i.attrib["href"]
        py_req = i.attrib.get("data-requires-python")
        # Skip items that need a different Python version
        if py_req:
            spec = SpecifierSet(py_req)
            if PYTHON_VERSION not in spec:
                continue

        path = urlparse(url).path
        filename = path.rpartition("/")[-1]
        # We only handle wheels
        if not filename.endswith(".whl"):
            continue

        # TODO: Handle compatibility tags?

        # Very primitive wheel filename parsing
        name, version = filename[:-4].split("-")[:2]
        try:
            version = Version(version)
        except InvalidVersion:
            # Ignore files with invalid versions
            continue

        yield Candidate(name, version, url=url, extras=extras) 
開發者ID:sarugaku,項目名稱:resolvelib,代碼行數:33,代碼來源:pypi_wheel_provider.py

示例5: test_good_init_api_version

# 需要導入模塊: from packaging import version [as 別名]
# 或者: from packaging.version import InvalidVersion [as 別名]
def test_good_init_api_version(self):
        try:
            data = "1.13"
            Version('{}'.format(data))
        except InvalidVersion:
            self.fail("Version {} raised InvalidVersion exception!".format(data)) 
開發者ID:teamhephy,項目名稱:controller,代碼行數:8,代碼來源:test_deployments.py

示例6: test_bad_init_api_version

# 需要導入模塊: from packaging import version [as 別名]
# 或者: from packaging.version import InvalidVersion [as 別名]
def test_bad_init_api_version(self):
        data = "1.13+"
        with self.assertRaises(
            InvalidVersion,
            msg='packaging.version.InvalidVersion: Invalid version: {}'.format(data)  # noqa
        ):
            Version('{}'.format(data)) 
開發者ID:teamhephy,項目名稱:controller,代碼行數:9,代碼來源:test_deployments.py

示例7: _check_match

# 需要導入模塊: from packaging import version [as 別名]
# 或者: from packaging.version import InvalidVersion [as 別名]
def _check_match(self, name: str, version_string: str) -> bool:
        """
        Check if the package name and version matches against a blacklisted
        package version specifier.

        Parameters
        ==========
        name: str
            Package name

        version: str
            Package version

        Returns
        =======
        bool:
            True if it matches, False otherwise.
        """
        if not name or not version_string:
            return False

        try:
            version = Version(version_string)
        except InvalidVersion:
            logger.debug(f"Package {name}=={version_string} has an invalid version")
            return False
        for requirement in self.blacklist_release_requirements:
            if name != requirement.name:
                continue
            if version in requirement.specifier:
                logger.debug(
                    f"MATCH: Release {name}=={version} matches specifier "
                    f"{requirement.specifier}"
                )
                return True
        return False 
開發者ID:pypa,項目名稱:bandersnatch,代碼行數:38,代碼來源:blacklist_name.py

示例8: travis_build_package

# 需要導入模塊: from packaging import version [as 別名]
# 或者: from packaging.version import InvalidVersion [as 別名]
def travis_build_package():
    """Assumed called on Travis, to prepare a package to be deployed
    This method prints on stdout for Travis.
    Return is obj to pass to sys.exit() directly
    """
    travis_tag = os.environ.get("TRAVIS_TAG")
    if not travis_tag:
        print("TRAVIS_TAG environment variable is not present")
        return "TRAVIS_TAG environment variable is not present"

    try:
        version = Version(travis_tag)
    except InvalidVersion:
        failure = "Version must be a valid PEP440 version (version is: {})".format(version)
        print(failure)
        return failure

    abs_dist_path = Path(os.environ["TRAVIS_BUILD_DIR"], "dist")
    [create_package(package, str(abs_dist_path)) for package in package_list]

    print("Produced:\n{}".format(list(abs_dist_path.glob("*"))))

    pattern = "*{}*".format(version)
    packages = list(abs_dist_path.glob(pattern))
    if not packages:
        return "Package version does not match tag {}, abort".format(version)
    pypi_server = os.environ.get("PYPI_SERVER", "default PyPI server")
    print("Package created as expected and will be pushed to {}".format(pypi_server)) 
開發者ID:Azure,項目名稱:azure-kusto-python,代碼行數:30,代碼來源:build_packages.py

示例9: _check_required_version

# 需要導入模塊: from packaging import version [as 別名]
# 或者: from packaging.version import InvalidVersion [as 別名]
def _check_required_version(self, required_version, target_version):
    if required_version is None:
      return True
    try:
      match_versions = SpecifierSet(required_version)
    except InvalidSpecifier:
      raise HokusaiError("Could not parse '%s' as a valid version specifier. See https://www.python.org/dev/peps/pep-0440/#version-specifiers" % required_version)
    try:
      compare_version = Version(target_version)
    except InvalidVersion:
      raise HokusaiError("Could not parse '%s' as a valid version identifier. See https://www.python.org/dev/peps/pep-0440/#version-scheme" % target_version)
    return compare_version in match_versions 
開發者ID:artsy,項目名稱:hokusai,代碼行數:14,代碼來源:config.py

示例10: parse_lang_str

# 需要導入模塊: from packaging import version [as 別名]
# 或者: from packaging.version import InvalidVersion [as 別名]
def parse_lang_str(string):
    """
    Parses any given language `string` into name and a list of either
    ``int``, ``float``, or ``str`` versions (ignores leading whitespace):

    >>> parse_lang_str("Python")
    ('Python', [])
    >>> parse_lang_str("Python 3.3")
    ('Python', [3.3])
    >>> parse_lang_str("Python 3.6, 3.3.1")
    ('Python', [3.6, '3.3.1'])
    >>> parse_lang_str("Objective C 3.6, 3")
    ('Objective C', [3.6, 3])
    >>> parse_lang_str("Cobol, stupid!")
    Traceback (most recent call last):
     ...
    packaging.version.InvalidVersion: Invalid version: 'stupid!'
    >>> parse_lang_str("Cobol seems at least stupid ;)")
    ('Cobol seems at least stupid ;)', [])
    """
    name, *str_versions = re.split(r'\s*,\s*', str(string).strip())
    versions = []
    for version in str_versions:
        version = convert_int_float_str(version)
        Version(str(version))  # raises if not valid
        versions.append(version)
    try:
        realname, version = name.rsplit(maxsplit=1)
        version = convert_int_float_str(version)
        Version(str(version))
    except (ValueError, InvalidVersion):
        pass
    else:
        versions.insert(0, version)
        return realname, versions

    return name, versions 
開發者ID:coala,項目名稱:coala,代碼行數:39,代碼來源:Language.py

示例11: check_latest

# 需要導入模塊: from packaging import version [as 別名]
# 或者: from packaging.version import InvalidVersion [as 別名]
def check_latest():
    """Determine whether this is the latest version."""
    from packaging.version import Version, InvalidVersion

    latest = None
    date = None
    outdated = None
    cachefile = Path.home() / ".cache" / "mriqc" / "latest"
    cachefile.parent.mkdir(parents=True, exist_ok=True)

    try:
        latest, date = cachefile.read_text().split("|")
    except Exception:
        pass
    else:
        try:
            latest = Version(latest)
            date = datetime.strptime(date, DATE_FMT)
        except (InvalidVersion, ValueError):
            latest = None
        else:
            if abs((datetime.now() - date).days) > RELEASE_EXPIRY_DAYS:
                outdated = True

    if latest is None or outdated is True:
        try:
            response = requests.get(url="https://pypi.org/pypi/mriqc/json", timeout=1.0)
        except Exception:
            response = None

        if response and response.status_code == 200:
            versions = [Version(rel) for rel in response.json()["releases"].keys()]
            versions = [rel for rel in versions if not rel.is_prerelease]
            if versions:
                latest = sorted(versions)[-1]
        else:
            latest = None

    if latest is not None:
        try:
            cachefile.write_text(
                "|".join(("%s" % latest, datetime.now().strftime(DATE_FMT)))
            )
        except Exception:
            pass

    return latest 
開發者ID:poldracklab,項目名稱:mriqc,代碼行數:49,代碼來源:version.py

示例12: check_latest

# 需要導入模塊: from packaging import version [as 別名]
# 或者: from packaging.version import InvalidVersion [as 別名]
def check_latest():
    """Determine whether this is the latest version."""
    from packaging.version import Version, InvalidVersion

    latest = None
    date = None
    outdated = None
    cachefile = Path.home() / ".cache" / "dmriprep" / "latest"
    cachefile.parent.mkdir(parents=True, exist_ok=True)

    try:
        latest, date = cachefile.read_text().split("|")
    except Exception:
        pass
    else:
        try:
            latest = Version(latest)
            date = datetime.strptime(date, DATE_FMT)
        except (InvalidVersion, ValueError):
            latest = None
        else:
            if abs((datetime.now() - date).days) > RELEASE_EXPIRY_DAYS:
                outdated = True

    if latest is None or outdated is True:
        try:
            response = requests.get(
                url="https://pypi.org/pypi/dmriprep/json", timeout=1.0
            )
        except Exception:
            response = None

        if response and response.status_code == 200:
            versions = [Version(rel) for rel in response.json()["releases"].keys()]
            versions = [rel for rel in versions if not rel.is_prerelease]
            if versions:
                latest = sorted(versions)[-1]
        else:
            latest = None

    if latest is not None:
        try:
            cachefile.write_text(
                "|".join(("%s" % latest, datetime.now().strftime(DATE_FMT)))
            )
        except Exception:
            pass

    return latest 
開發者ID:nipreps,項目名稱:dmriprep,代碼行數:51,代碼來源:version.py


注:本文中的packaging.version.InvalidVersion方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。