PyVulnerabilityLookup/pyvulnerabilitylookup/api.py

51 lines
1.8 KiB
Python
Raw Normal View History

2023-05-19 13:21:11 +00:00
#!/usr/bin/env python3
2024-01-17 11:41:24 +00:00
from __future__ import annotations
2023-05-19 13:21:11 +00:00
from importlib.metadata import version
from pathlib import Path
2024-01-17 11:41:24 +00:00
from typing import Any
2023-05-19 13:21:11 +00:00
from urllib.parse import urljoin, urlparse
import requests
class PyVulnerabilityLookup():
2024-01-17 11:41:24 +00:00
def __init__(self, root_url: str, useragent: str | None=None,
*, proxies: dict[str, str] | None=None) -> None:
2023-05-19 13:21:11 +00:00
'''Query a specific instance.
:param root_url: URL of the instance to query.
:param useragent: The User Agent used by requests to run the HTTP requests against the vulnerability lookup instance
:param proxies: The proxies to use to connect to the vulnerability lookup instance - More details: https://requests.readthedocs.io/en/latest/user/advanced/#proxies
2023-05-19 13:21:11 +00:00
'''
self.root_url = root_url
if not urlparse(self.root_url).scheme:
self.root_url = 'http://' + self.root_url
if not self.root_url.endswith('/'):
self.root_url += '/'
self.session = requests.session()
self.session.headers['user-agent'] = useragent if useragent else f'PyProject / {version("pyvulnerabilitylookup")}'
if proxies:
self.session.proxies.update(proxies)
2023-05-19 13:21:11 +00:00
@property
def is_up(self) -> bool:
'''Test if the given instance is accessible'''
try:
r = self.session.head(self.root_url)
except requests.exceptions.ConnectionError:
return False
return r.status_code == 200
2024-01-17 11:41:24 +00:00
def redis_up(self) -> bool:
2023-05-19 13:21:11 +00:00
'''Check if redis is up and running'''
r = self.session.get(urljoin(self.root_url, 'redis_up'))
return r.json()
2024-01-17 11:41:24 +00:00
def get_vulnerability(self, vulnerability_id: str) -> dict[str, Any]:
2023-05-19 13:21:11 +00:00
r = self.session.get(urljoin(self.root_url, str(Path('vulnerability', vulnerability_id))))
return r.json()