Skip to content

Commit

Permalink
style: set line length to 99 (#291)
Browse files Browse the repository at this point in the history
The maximum line length recommended in PEP-8 is 99.
  • Loading branch information
tdstein committed Sep 13, 2024
1 parent 4c306e2 commit 18f461d
Show file tree
Hide file tree
Showing 33 changed files with 137 additions and 432 deletions.
12 changes: 3 additions & 9 deletions examples/connect/databricks/dash/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,7 @@ def update_page(_):
Dash example application that shows user information and
the first few rows from a table hosted in Databricks.
"""
session_token = flask.request.headers.get(
"Posit-Connect-User-Session-Token"
)
session_token = flask.request.headers.get("Posit-Connect-User-Session-Token")
posit_strategy = PositCredentialsStrategy(
local_strategy=databricks_cli, user_session_token=session_token
)
Expand All @@ -63,16 +61,12 @@ def get_table():
server_hostname=DATABRICKS_HOST,
http_path=SQL_HTTP_PATH,
# https://github.com/databricks/databricks-sql-python/issues/148#issuecomment-2271561365
credentials_provider=posit_strategy.sql_credentials_provider(
cfg
),
credentials_provider=posit_strategy.sql_credentials_provider(cfg),
) as connection:
with connection.cursor() as cursor:
cursor.execute(query)
rows = cursor.fetchall()
df = pd.DataFrame(
rows, columns=[col[0] for col in cursor.description]
)
df = pd.DataFrame(rows, columns=[col[0] for col in cursor.description])

table = dash_table.DataTable(
id="table",
Expand Down
8 changes: 2 additions & 6 deletions examples/connect/databricks/shiny/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,7 @@ def server(i: Inputs, o: Outputs, session: Session):
Shiny for Python example application that shows user information and
the first few rows from a table hosted in Databricks.
"""
session_token = session.http_conn.headers.get(
"Posit-Connect-User-Session-Token"
)
session_token = session.http_conn.headers.get("Posit-Connect-User-Session-Token")
posit_strategy = PositCredentialsStrategy(
local_strategy=databricks_cli, user_session_token=session_token
)
Expand All @@ -48,9 +46,7 @@ def result():
with connection.cursor() as cursor:
cursor.execute(query)
rows = cursor.fetchall()
df = pd.DataFrame(
rows, columns=[col[0] for col in cursor.description]
)
df = pd.DataFrame(rows, columns=[col[0] for col in cursor.description])
return df

@render.text
Expand Down
4 changes: 1 addition & 3 deletions examples/connect/snowflake/streamlit/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@
TABLE = os.getenv("SNOWFLAKE_TABLE", "lineitem")

session_token = st.context.headers.get("Posit-Connect-User-Session-Token")
auth = PositAuthenticator(
local_authenticator="EXTERNALBROWSER", user_session_token=session_token
)
auth = PositAuthenticator(local_authenticator="EXTERNALBROWSER", user_session_token=session_token)

con = snowflake.connector.connect(
user=USER,
Expand Down
23 changes: 5 additions & 18 deletions integration/tests/posit/connect/oauth/test_associations.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,7 @@ def setup_class(cls):
# requires full bundle deployment to produce an interactive content type
cls.content = cls.client.content.create(name="example-flask-minimal")
# create bundle
path = Path(
"../../../../resources/connect/bundles/example-flask-minimal/bundle.tar.gz"
)
path = Path("../../../../resources/connect/bundles/example-flask-minimal/bundle.tar.gz")
path = (Path(__file__).parent / path).resolve()
bundle = cls.content.bundles.create(str(path))
# deploy bundle
Expand All @@ -73,10 +71,7 @@ def teardown_class(cls):
def test_find_by_integration(self):
associations = self.integration.associations.find()
assert len(associations) == 1
assert (
associations[0]["oauth_integration_guid"]
== self.integration["guid"]
)
assert associations[0]["oauth_integration_guid"] == self.integration["guid"]

no_associations = self.another_integration.associations.find()
assert len(no_associations) == 0
Expand All @@ -85,22 +80,14 @@ def test_find_update_by_content(self):
associations = self.content.oauth.associations.find()
assert len(associations) == 1
assert associations[0]["app_guid"] == self.content["guid"]
assert (
associations[0]["oauth_integration_guid"]
== self.integration["guid"]
)
assert associations[0]["oauth_integration_guid"] == self.integration["guid"]

# update content association to another_integration
self.content.oauth.associations.update(
self.another_integration["guid"]
)
self.content.oauth.associations.update(self.another_integration["guid"])
updated_associations = self.content.oauth.associations.find()
assert len(updated_associations) == 1
assert updated_associations[0]["app_guid"] == self.content["guid"]
assert (
updated_associations[0]["oauth_integration_guid"]
== self.another_integration.guid
)
assert updated_associations[0]["oauth_integration_guid"] == self.another_integration.guid

# unset content association
self.content.oauth.associations.delete()
Expand Down
8 changes: 2 additions & 6 deletions integration/tests/posit/connect/test_content.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,7 @@ def test_restart(self):
# create content
content = self.client.content.create(name="example-flask-minimal")
# create bundle
path = Path(
"../../../resources/connect/bundles/example-flask-minimal/bundle.tar.gz"
)
path = Path("../../../resources/connect/bundles/example-flask-minimal/bundle.tar.gz")
path = (Path(__file__).parent / path).resolve()
bundle = content.bundles.create(str(path))
# deploy bundle
Expand All @@ -70,9 +68,7 @@ def test_render(self):
# create content
content = self.client.content.create(name="example-quarto-minimal")
# create bundle
path = Path(
"../../../resources/connect/bundles/example-quarto-minimal/bundle.tar.gz"
)
path = Path("../../../resources/connect/bundles/example-quarto-minimal/bundle.tar.gz")
path = (Path(__file__).parent / path).resolve()
bundle = content.bundles.create(str(path))
# deploy bundle
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ version_file = "src/posit/_version.py"

[tool.ruff]
extend-exclude = ["integration/resources"]
line-length = 79
line-length = 99

[tool.ruff.format]
docstring-code-format = true
Expand Down
6 changes: 1 addition & 5 deletions src/posit/connect/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,11 +140,7 @@ def __init__(self, *args, **kwargs) -> None:
url = None
if len(args) == 1 and isinstance(args[0], str):
url = args[0]
elif (
len(args) == 2
and isinstance(args[0], str)
and isinstance(args[1], str)
):
elif len(args) == 2 and isinstance(args[0], str) and isinstance(args[1], str):
url = args[0]
api_key = args[1]
else:
Expand Down
12 changes: 3 additions & 9 deletions src/posit/connect/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,7 @@ def _get_api_key() -> str:
"""
value = os.environ.get("CONNECT_API_KEY")
if not value:
raise ValueError(
"Invalid value for 'CONNECT_API_KEY': Must be a non-empty string."
)
raise ValueError("Invalid value for 'CONNECT_API_KEY': Must be a non-empty string.")
return value


Expand All @@ -42,17 +40,13 @@ def _get_url() -> str:
"""
value = os.environ.get("CONNECT_SERVER")
if not value:
raise ValueError(
"Invalid value for 'CONNECT_SERVER': Must be a non-empty string."
)
raise ValueError("Invalid value for 'CONNECT_SERVER': Must be a non-empty string.")
return value


class Config:
"""Configuration object."""

def __init__(
self, api_key: Optional[str] = None, url: Optional[str] = None
) -> None:
def __init__(self, api_key: Optional[str] = None, url: Optional[str] = None) -> None:
self.api_key = api_key or _get_api_key()
self.url = urls.Url(url or _get_url())
16 changes: 4 additions & 12 deletions src/posit/connect/content.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@ def __init__(self, params: ResourceParameters, content_guid: str) -> None:

@property
def associations(self) -> ContentItemAssociations:
return ContentItemAssociations(
self.params, content_guid=self.content_guid
)
return ContentItemAssociations(self.params, content_guid=self.content_guid)


class ContentItemOwner(Resource):
Expand Down Expand Up @@ -124,9 +122,7 @@ def restart(self) -> None:
self.environment_variables.create(key, unix_epoch_in_seconds)
self.environment_variables.delete(key)
# GET via the base Connect URL to force create a new worker thread.
url = posixpath.join(
dirname(self.params.url), f"content/{self.guid}"
)
url = posixpath.join(dirname(self.params.url), f"content/{self.guid}")
self.params.session.get(url)
return None
else:
Expand Down Expand Up @@ -418,9 +414,7 @@ def find(
...

@overload
def find(
self, *args, include: Optional[str] = "owner,tags", **kwargs
) -> List[ContentItem]:
def find(self, *args, include: Optional[str] = "owner,tags", **kwargs) -> List[ContentItem]:
"""Find content items.
Parameters
Expand All @@ -434,9 +428,7 @@ def find(
"""
...

def find(
self, *args, include: Optional[str] = "owner,tags", **kwargs
) -> List[ContentItem]:
def find(self, *args, include: Optional[str] = "owner,tags", **kwargs) -> List[ContentItem]:
"""Find content items.
Parameters
Expand Down
4 changes: 1 addition & 3 deletions src/posit/connect/cursors.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@ class CursorPage:


class CursorPaginator:
def __init__(
self, session: requests.Session, url: str, params: dict = {}
) -> None:
def __init__(self, session: requests.Session, url: str, params: dict = {}) -> None:
self.session = session
self.url = url
self.params = params
Expand Down
8 changes: 2 additions & 6 deletions src/posit/connect/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,7 @@ def __setitem__(self, key: str, value: Optional[str], /) -> None:
Examples
--------
>>> vars = EnvVars(params, content_guid)
>>> vars["DATABASE_URL"] = (
... "postgres://user:password@localhost:5432/database"
... )
>>> vars["DATABASE_URL"] = "postgres://user:password@localhost:5432/database"
"""
self.update({key: value})

Expand Down Expand Up @@ -153,9 +151,7 @@ def update(self, other=(), /, **kwargs: Optional[str]):
Examples
--------
Update using keyword arguments:
>>> update(
... DATABASE_URL="postgres://user:password@localhost:5432/database"
... )
>>> update(DATABASE_URL="postgres://user:password@localhost:5432/database")
Update using multiple keyword arguments:
>>> update(
Expand Down
12 changes: 3 additions & 9 deletions src/posit/connect/external/databricks.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,10 @@ def __init__(self, client: Client, user_session_token: str):
self._user_session_token = user_session_token

def __call__(self) -> Dict[str, str]:
credentials = self._client.oauth.get_credentials(
self._user_session_token
)
credentials = self._client.oauth.get_credentials(self._user_session_token)
access_token = credentials.get("access_token")
if access_token is None:
raise ValueError(
"Missing value for field 'access_token' in credentials."
)
raise ValueError("Missing value for field 'access_token' in credentials.")
return {"Authorization": f"Bearer {access_token}"}


Expand Down Expand Up @@ -96,9 +92,7 @@ def __call__(self, *args, **kwargs) -> CredentialsProvider:
# If the user-session-token wasn't provided and we're running on Connect then we raise an exception.
# user_session_token is required to impersonate the viewer.
if self._user_session_token is None:
raise ValueError(
"The user-session-token is required for viewer authentication."
)
raise ValueError("The user-session-token is required for viewer authentication.")

if self._client is None:
self._client = Client()
Expand Down
8 changes: 2 additions & 6 deletions src/posit/connect/external/snowflake.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,10 @@ def token(self) -> Optional[str]:
# If the user-session-token wasn't provided and we're running on Connect then we raise an exception.
# user_session_token is required to impersonate the viewer.
if self._user_session_token is None:
raise ValueError(
"The user-session-token is required for viewer authentication."
)
raise ValueError("The user-session-token is required for viewer authentication.")

if self._client is None:
self._client = Client()

credentials = self._client.oauth.get_credentials(
self._user_session_token
)
credentials = self._client.oauth.get_credentials(self._user_session_token)
return credentials.get("access_token")
4 changes: 1 addition & 3 deletions src/posit/connect/groups.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,8 +161,6 @@ def count(self) -> int:
"""
path = "v1/groups"
url = self.params.url + path
response: requests.Response = self.params.session.get(
url, params={"page_size": 1}
)
response: requests.Response = self.params.session.get(url, params={"page_size": 1})
result: dict = response.json()
return result["total"]
8 changes: 2 additions & 6 deletions src/posit/connect/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,14 @@ def handle_errors(response: Response, *args, **kwargs) -> Response:
payload = data.get("payload")
http_status = response.status_code
http_status_message = responses[http_status]
raise ClientError(
error_code, message, http_status, http_status_message, payload
)
raise ClientError(error_code, message, http_status, http_status_message, payload)
except JSONDecodeError:
# No JSON error message from Connect, so just raise
response.raise_for_status()
return response


def check_for_deprecation_header(
response: Response, *args, **kwargs
) -> Response:
def check_for_deprecation_header(response: Response, *args, **kwargs) -> Response:
"""
Check for deprecation warnings from the server.
Expand Down
16 changes: 4 additions & 12 deletions src/posit/connect/oauth/associations.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@ class Association(Resource):
class IntegrationAssociations(Resources):
"""IntegrationAssociations resource."""

def __init__(
self, params: ResourceParameters, integration_guid: str
) -> None:
def __init__(self, params: ResourceParameters, integration_guid: str) -> None:
super().__init__(params)
self.integration_guid = integration_guid

Expand Down Expand Up @@ -52,9 +50,7 @@ def find(self) -> List[Association]:
-------
List[Association]
"""
path = (
f"v1/content/{self.content_guid}/oauth/integrations/associations"
)
path = f"v1/content/{self.content_guid}/oauth/integrations/associations"
url = self.params.url + path
response = self.params.session.get(url)
return [
Expand All @@ -69,18 +65,14 @@ def delete(self) -> None:
"""Delete integration associations."""
data = []

path = (
f"v1/content/{self.content_guid}/oauth/integrations/associations"
)
path = f"v1/content/{self.content_guid}/oauth/integrations/associations"
url = self.params.url + path
self.params.session.put(url, json=data)

def update(self, integration_guid: str) -> None:
"""Set integration associations."""
data = [{"oauth_integration_guid": integration_guid}]

path = (
f"v1/content/{self.content_guid}/oauth/integrations/associations"
)
path = f"v1/content/{self.content_guid}/oauth/integrations/associations"
url = self.params.url + path
self.params.session.put(url, json=data)
4 changes: 1 addition & 3 deletions src/posit/connect/oauth/integrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@ class Integration(Resource):

@property
def associations(self) -> IntegrationAssociations:
return IntegrationAssociations(
self.params, integration_guid=self["guid"]
)
return IntegrationAssociations(self.params, integration_guid=self["guid"])

def delete(self) -> None:
"""Delete the OAuth integration."""
Expand Down
Loading

0 comments on commit 18f461d

Please sign in to comment.