本文整理汇总了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
示例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
示例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
示例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)
示例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))
示例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))
示例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
示例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))
示例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
示例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
示例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
示例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