Close API client on exit

This commit is contained in:
Ivan Kravets
2023-07-31 19:09:32 +03:00
parent 30fad62d05
commit 527e7f16f6
38 changed files with 160 additions and 153 deletions

View File

@ -19,7 +19,7 @@ from platformio.account.client import AccountClient, AccountNotAuthorized
@click.command("destroy", short_help="Destroy account")
def account_destroy_cmd():
client = AccountClient()
with AccountClient() as client:
click.confirm(
"Are you sure you want to delete the %s user account?\n"
"Warning! All linked data will be permanently removed and can not be restored."

View File

@ -20,7 +20,7 @@ from platformio.account.client import AccountClient
@click.command("forgot", short_help="Forgot password")
@click.option("--username", prompt="Username or email")
def account_forgot_cmd(username):
client = AccountClient()
with AccountClient() as client:
client.forgot_password(username)
click.secho(
"If this account is registered, we will send the "

View File

@ -21,6 +21,6 @@ from platformio.account.client import AccountClient
@click.option("-u", "--username", prompt="Username or email")
@click.option("-p", "--password", prompt=True, hide_input=True)
def account_login_cmd(username, password):
client = AccountClient()
with AccountClient() as client:
client.login(username, password)
click.secho("Successfully logged in!", fg="green")

View File

@ -19,6 +19,6 @@ from platformio.account.client import AccountClient
@click.command("logout", short_help="Log out of PlatformIO Account")
def account_logout_cmd():
client = AccountClient()
with AccountClient() as client:
client.logout()
click.secho("Successfully logged out!", fg="green")

View File

@ -21,6 +21,6 @@ from platformio.account.client import AccountClient
@click.option("--old-password", prompt=True, hide_input=True)
@click.option("--new-password", prompt=True, hide_input=True, confirmation_prompt=True)
def account_password_cmd(old_password, new_password):
client = AccountClient()
with AccountClient() as client:
client.change_password(old_password, new_password)
click.secho("Password successfully changed!", fg="green")

View File

@ -43,7 +43,7 @@ from platformio.account.validate import (
@click.option("--firstname", prompt=True)
@click.option("--lastname", prompt=True)
def account_register_cmd(username, email, password, firstname, lastname):
client = AccountClient()
with AccountClient() as client:
client.registration(username, email, password, firstname, lastname)
click.secho(
"An account has been successfully created. "

View File

@ -25,7 +25,7 @@ from platformio.account.client import AccountClient
@click.option("--offline", is_flag=True)
@click.option("--json-output", is_flag=True)
def account_show_cmd(offline, json_output):
client = AccountClient()
with AccountClient() as client:
info = client.get_account_info(offline)
if json_output:
click.echo(json.dumps(info))

View File

@ -24,7 +24,7 @@ from platformio.account.client import AccountClient
@click.option("--regenerate", is_flag=True)
@click.option("--json-output", is_flag=True)
def account_token_cmd(password, regenerate, json_output):
client = AccountClient()
with AccountClient() as client:
auth_token = client.auth_token(password, regenerate)
if json_output:
click.echo(json.dumps({"status": "success", "result": auth_token}))

View File

@ -25,7 +25,7 @@ from platformio.account.validate import validate_email, validate_username
@click.option("--firstname")
@click.option("--lastname")
def account_update_cmd(current_password, **kwargs):
client = AccountClient()
with AccountClient() as client:
profile = client.get_profile()
new_profile = profile.copy()
if not any(kwargs.values()):

View File

@ -25,7 +25,7 @@ from platformio.account.client import AccountClient
"username",
)
def org_add_cmd(orgname, username):
client = AccountClient()
with AccountClient() as client:
client.add_org_owner(orgname, username)
return click.secho(
"The new owner `%s` has been successfully added to the `%s` organization."

View File

@ -30,7 +30,7 @@ from platformio.account.validate import validate_email, validate_orgname
"--displayname",
)
def org_create_cmd(orgname, email, displayname):
client = AccountClient()
with AccountClient() as client:
client.create_org(orgname, email, displayname)
return click.secho(
"The organization `%s` has been successfully created." % orgname,

View File

@ -20,7 +20,7 @@ from platformio.account.client import AccountClient
@click.command("destroy", short_help="Destroy organization")
@click.argument("orgname")
def org_destroy_cmd(orgname):
client = AccountClient()
with AccountClient() as client:
click.confirm(
"Are you sure you want to delete the `%s` organization account?\n"
"Warning! All linked data will be permanently removed and can not be restored."

View File

@ -23,7 +23,7 @@ from platformio.account.client import AccountClient
@click.command("list", short_help="List organizations and their members")
@click.option("--json-output", is_flag=True)
def org_list_cmd(json_output):
client = AccountClient()
with AccountClient() as client:
orgs = client.list_orgs()
if json_output:
return click.echo(json.dumps(orgs))

View File

@ -25,7 +25,7 @@ from platformio.account.client import AccountClient
"username",
)
def org_remove_cmd(orgname, username):
client = AccountClient()
with AccountClient() as client:
client.remove_org_owner(orgname, username)
return click.secho(
"The `%s` owner has been successfully removed from the `%s` organization."

View File

@ -31,7 +31,7 @@ from platformio.account.validate import validate_email, validate_orgname
)
@click.option("--displayname")
def org_update_cmd(cur_orgname, **kwargs):
client = AccountClient()
with AccountClient() as client:
org = client.get_org(cur_orgname)
new_org = {
key: value if value is not None else org[key] for key, value in kwargs.items()

View File

@ -29,7 +29,7 @@ from platformio.account.validate import validate_orgname_teamname
)
def team_add_cmd(orgname_teamname, username):
orgname, teamname = orgname_teamname.split(":", 1)
client = AccountClient()
with AccountClient() as client:
client.add_team_member(orgname, teamname, username)
return click.secho(
"The new member %s has been successfully added to the %s team."

View File

@ -29,7 +29,7 @@ from platformio.account.validate import validate_orgname_teamname
)
def team_create_cmd(orgname_teamname, description):
orgname, teamname = orgname_teamname.split(":", 1)
client = AccountClient()
with AccountClient() as client:
client.create_team(orgname, teamname, description)
return click.secho(
"The team %s has been successfully created." % teamname,

View File

@ -32,7 +32,7 @@ def team_destroy_cmd(orgname_teamname):
),
abort=True,
)
client = AccountClient()
with AccountClient() as client:
client.destroy_team(orgname, teamname)
return click.secho(
"The team %s has been successfully destroyed." % teamname,

View File

@ -24,7 +24,7 @@ from platformio.account.client import AccountClient
@click.argument("orgname", required=False)
@click.option("--json-output", is_flag=True)
def team_list_cmd(orgname, json_output):
client = AccountClient()
with AccountClient() as client:
data = {}
if not orgname:
for item in client.list_orgs():
@ -33,10 +33,13 @@ def team_list_cmd(orgname, json_output):
else:
teams = client.list_teams(orgname)
data[orgname] = teams
if json_output:
return click.echo(json.dumps(data[orgname] if orgname else data))
if not any(data.values()):
return click.secho("You do not have any teams.", fg="yellow")
for org_name, teams in data.items():
for team in teams:
click.echo()

View File

@ -27,7 +27,7 @@ from platformio.account.validate import validate_orgname_teamname
@click.argument("username")
def team_remove_cmd(orgname_teamname, username):
orgname, teamname = orgname_teamname.split(":", 1)
client = AccountClient()
with AccountClient() as client:
client.remove_team_member(orgname, teamname, username)
return click.secho(
"The %s member has been successfully removed from the %s team."

View File

@ -34,7 +34,7 @@ from platformio.account.validate import validate_orgname_teamname, validate_team
)
def team_update_cmd(orgname_teamname, **kwargs):
orgname, teamname = orgname_teamname.split(":", 1)
client = AccountClient()
with AccountClient() as client:
team = client.get_team(orgname, teamname)
new_team = {
key: value if value is not None else team[key] for key, value in kwargs.items()

View File

@ -21,4 +21,5 @@ class AccountRPC(BaseRPCHandler):
@staticmethod
def call_client(method, *args, **kwargs):
return getattr(AccountClient(), method)(*args, **kwargs)
with AccountClient() as client:
return getattr(client, method)(*args, **kwargs)

View File

@ -29,8 +29,6 @@ from platformio.http import HTTPSession, ensure_internet_on
class OSRPC(BaseRPCHandler):
NAMESPACE = "os"
_http_session = None
@classmethod
def fetch_content(cls, url, data=None, headers=None, cache_valid=None):
if not headers:
@ -44,27 +42,25 @@ class OSRPC(BaseRPCHandler):
cache_key = ContentCache.key_from_args(url, data) if cache_valid else None
with ContentCache() as cc:
if cache_key:
result = cc.get(cache_key)
if result is not None:
return result
content = cc.get(cache_key)
if content is not None:
return content
# check internet before and resolve issue with 60 seconds timeout
ensure_internet_on(raise_exception=True)
if not cls._http_session:
cls._http_session = HTTPSession()
with HTTPSession() as session:
if data:
r = cls._http_session.post(url, data=data, headers=headers)
response = session.post(url, data=data, headers=headers)
else:
r = cls._http_session.get(url, headers=headers)
response = session.get(url, headers=headers)
r.raise_for_status()
result = r.text
response.raise_for_status()
content = response.text
if cache_valid:
with ContentCache() as cc:
cc.set(cache_key, result, cache_valid)
return result
cc.set(cache_key, content, cache_valid)
return content
@classmethod
def request_content(cls, uri, data=None, headers=None, cache_valid=None):

View File

@ -21,4 +21,5 @@ class RegistryRPC(BaseRPCHandler):
@staticmethod
def call_client(method, *args, **kwargs):
return getattr(RegistryClient(), method)(*args, **kwargs)
with RegistryClient() as client:
return getattr(client, method)(*args, **kwargs)

View File

@ -87,7 +87,8 @@ def package_publish_cmd( # pylint: disable=too-many-arguments, too-many-locals
):
click.secho("Preparing a package...", fg="cyan")
no_interactive = no_interactive or non_interactive
owner = owner or AccountClient().get_logged_username()
with AccountClient() as client:
owner = owner or client.get_logged_username()
do_not_pack = (
not os.path.isdir(package)
and isinstance(FileUnpacker.new_archiver(package), TARArchiver)
@ -145,7 +146,8 @@ def package_publish_cmd( # pylint: disable=too-many-arguments, too-many-locals
fg="yellow",
)
click.echo("Publishing...")
response = RegistryClient().publish_package(
with RegistryClient() as client:
response = client.publish_package(
owner, typex, archive_path, released_at, private, notify
)
if not do_not_pack:

View File

@ -29,7 +29,7 @@ from platformio.registry.client import RegistryClient
type=click.Choice(["relevance", "popularity", "trending", "added", "updated"]),
)
def package_search_cmd(query, page, sort):
client = RegistryClient()
with RegistryClient() as client:
result = client.list_packages(query, page=page, sort=sort)
if not result["total"]:
click.secho("Nothing has been found by your request", fg="yellow")

View File

@ -124,7 +124,7 @@ def package_show_cmd(spec, pkg_type):
def fetch_package_data(spec, pkg_type=None):
assert isinstance(spec, PackageSpec)
client = RegistryClient()
with RegistryClient() as client:
if pkg_type and spec.owner and spec.name:
return client.get_package(
pkg_type, spec.owner, spec.name, version=spec.requirements

View File

@ -36,8 +36,11 @@ from platformio.registry.client import RegistryClient
)
def package_unpublish_cmd(package, type, undo): # pylint: disable=redefined-builtin
spec = PackageSpec(package)
response = RegistryClient().unpublish_package(
owner=spec.owner or AccountClient().get_logged_username(),
with AccountClient() as client:
owner = spec.owner or client.get_logged_username()
with RegistryClient() as client:
response = client.unpublish_package(
owner=owner,
type=type,
name=spec.name,
version=str(spec.requirements),

View File

@ -31,7 +31,7 @@ from platformio.registry.client import RegistryClient
)
@click.option("--urn-type", type=click.Choice(["prn:reg:pkg"]), default="prn:reg:pkg")
def access_grant_cmd(level, client, urn, urn_type): # pylint: disable=unused-argument
reg_client = RegistryClient()
with RegistryClient() as reg_client:
reg_client.grant_access_for_resource(urn=urn, client=client, level=level)
return click.secho(
"Access for resource %s has been granted for %s" % (urn, client),

View File

@ -25,8 +25,8 @@ from platformio.registry.client import RegistryClient
@click.option("--urn-type", type=click.Choice(["prn:reg:pkg"]), default="prn:reg:pkg")
@click.option("--json-output", is_flag=True)
def access_list_cmd(owner, urn_type, json_output): # pylint: disable=unused-argument
reg_client = RegistryClient()
resources = reg_client.list_resources(owner=owner)
with RegistryClient() as client:
resources = client.list_resources(owner=owner)
if json_output:
return click.echo(json.dumps(resources))
if not resources:

View File

@ -25,7 +25,7 @@ from platformio.registry.client import RegistryClient
)
@click.option("--urn-type", type=click.Choice(["prn:reg:pkg"]), default="prn:reg:pkg")
def access_private_cmd(urn, urn_type): # pylint: disable=unused-argument
client = RegistryClient()
with RegistryClient() as client:
client.update_resource(urn=urn, private=1)
return click.secho(
"The resource %s has been successfully updated." % urn,

View File

@ -25,7 +25,7 @@ from platformio.registry.client import RegistryClient
)
@click.option("--urn-type", type=click.Choice(["prn:reg:pkg"]), default="prn:reg:pkg")
def access_public_cmd(urn, urn_type): # pylint: disable=unused-argument
client = RegistryClient()
with RegistryClient() as client:
client.update_resource(urn=urn, private=0)
return click.secho(
"The resource %s has been successfully updated." % urn,

View File

@ -30,7 +30,7 @@ from platformio.registry.client import RegistryClient
)
@click.option("--urn-type", type=click.Choice(["prn:reg:pkg"]), default="prn:reg:pkg")
def access_revoke_cmd(client, urn, urn_type): # pylint: disable=unused-argument
reg_client = RegistryClient()
with RegistryClient() as reg_client:
reg_client.revoke_access_from_resource(urn=urn, client=client)
return click.secho(
"Access for resource %s has been revoked for %s" % (urn, client),

View File

@ -34,7 +34,8 @@ class RegistryClient(HTTPClient):
]
)
try:
info = AccountClient().get_account_info() or {}
with AccountClient() as client:
info = client.get_account_info() or {}
for item in info.get("packages", []):
if set(item.keys()) & private_permissions:
return True

View File

@ -37,7 +37,8 @@ class RemoteClientFactory(pb.PBClientFactory, protocol.ReconnectingClientFactory
auth_token = None
try:
auth_token = AccountClient().fetch_authentication_token()
with AccountClient() as client:
auth_token = client.fetch_authentication_token()
except Exception as exc: # pylint:disable=broad-except
d = defer.Deferred()
d.addErrback(self.clientAuthorizationFailed)

View File

@ -19,11 +19,11 @@ import os
import random
import pytest
import requests
from platformio.account.cli import cli as cmd_account
from platformio.account.org.cli import cli as cmd_org
from platformio.account.team.cli import cli as cmd_team
from platformio.http import HTTPSession
pytestmark = pytest.mark.skipif(
not all(
@ -60,12 +60,11 @@ def verify_account(email_contents):
.split("This link will expire within 12 hours.")[0]
.strip()
)
with requests.Session() as session:
with HTTPSession() as session:
result = session.get(link).text
link = result.split('<a href="')[1].split('"', 1)[0]
link = link.replace("&amp;", "&")
session.get(link)
session.close()
def test_account_register(

View File

@ -143,7 +143,7 @@ def get_pkg_latest_version():
if not isinstance(spec, PackageSpec):
spec = PackageSpec(spec)
pkg_type = pkg_type or PackageType.LIBRARY
client = RegistryClient()
with RegistryClient() as client:
pkg = client.get_package(pkg_type, spec.owner, spec.name)
return pkg["version"]["name"]

View File

@ -15,7 +15,6 @@
# pylint: disable=unused-argument
import pytest
import requests
from platformio import __check_internet_hosts__, http, proc
from platformio.registry.client import RegistryClient
@ -30,19 +29,20 @@ def test_platformio_cli():
def test_ping_internet_ips():
for host in __check_internet_hosts__:
requests.get("http://%s" % host, allow_redirects=False, timeout=2)
with http.HTTPSession(follow_redirects=False, timeout=2) as session:
session.get("http://%s" % host)
def test_api_internet_offline(without_internet, isolated_pio_core):
regclient = RegistryClient()
with RegistryClient() as client:
with pytest.raises(http.InternetConnectionError):
regclient.fetch_json_data("get", "/v3/search")
client.fetch_json_data("get", "/v3/search")
def test_api_cache(monkeypatch, isolated_pio_core):
regclient = RegistryClient()
with RegistryClient() as client:
api_kwargs = {"method": "get", "path": "/v3/search", "x_cache_valid": "10s"}
result = regclient.fetch_json_data(**api_kwargs)
result = client.fetch_json_data(**api_kwargs)
assert result and "total" in result
monkeypatch.setattr(http, "_internet_on", lambda: False)
assert regclient.fetch_json_data(**api_kwargs) == result
assert client.fetch_json_data(**api_kwargs) == result