update type hinting

This commit is contained in:
dries.k
2023-05-13 18:45:03 +02:00
parent 7d47c79898
commit 0ca78ad8d9
8 changed files with 39 additions and 42 deletions

View File

@@ -1,5 +1,5 @@
import logging import logging
from typing import Callable, List, Optional, Union from typing import Callable
import requests import requests
@@ -22,7 +22,7 @@ class GotifySession(object):
self.session = requests.Session() self.session = requests.Session()
self.update_auth(url.rstrip("/"), token) self.update_auth(url.rstrip("/"), token)
def update_auth(self, url: str = None, token: str = None): def update_auth(self, url: str | None = None, token: str | None = None):
if url: if url:
self.url = url self.url = url
if token: if token:
@@ -50,8 +50,8 @@ class GotifyApplication(GotifySession):
super(GotifyApplication, self).__init__(url, application_token) super(GotifyApplication, self).__init__(url, application_token)
def push( def push(
self, title: str = "", message: str = "", priority: int = 0, extras: dict = None self, title: str = "", message: str = "", priority: int = 0, extras: dict | None = None
) -> Union[GotifyMessageModel, GotifyErrorModel]: ) -> GotifyMessageModel | GotifyErrorModel:
response = self._post( response = self._post(
"/message", "/message",
json={ json={
@@ -77,7 +77,7 @@ class GotifyClient(GotifySession):
Application Application
""" """
def get_applications(self) -> Union[List[GotifyApplicationModel], GotifyErrorModel]: def get_applications(self) -> list[GotifyApplicationModel] | GotifyErrorModel:
response = self._get("/application") response = self._get("/application")
return ( return (
[GotifyApplicationModel(x) for x in response.json()] [GotifyApplicationModel(x) for x in response.json()]
@@ -87,7 +87,7 @@ class GotifyClient(GotifySession):
def create_application( def create_application(
self, name: str, description: str = "" self, name: str, description: str = ""
) -> Union[GotifyApplicationModel, GotifyErrorModel]: ) -> GotifyApplicationModel | GotifyErrorModel:
response = self._post( response = self._post(
"/application", json={"name": name, "description": description} "/application", json={"name": name, "description": description}
) )
@@ -99,7 +99,7 @@ class GotifyClient(GotifySession):
def update_application( def update_application(
self, application_id: int, name: str, description: str = "" self, application_id: int, name: str, description: str = ""
) -> Union[GotifyApplicationModel, GotifyErrorModel]: ) -> GotifyApplicationModel | GotifyErrorModel:
response = self._put( response = self._put(
f"/application/{application_id}", f"/application/{application_id}",
json={"name": name, "description": description}, json={"name": name, "description": description},
@@ -115,7 +115,7 @@ class GotifyClient(GotifySession):
def upload_application_image( def upload_application_image(
self, application_id: int, img_path: str self, application_id: int, img_path: str
) -> Optional[Union[GotifyApplicationModel, GotifyErrorModel]]: ) -> GotifyApplicationModel | GotifyErrorModel | None:
try: try:
with open(img_path, "rb") as f: with open(img_path, "rb") as f:
response = self._post( response = self._post(
@@ -137,8 +137,8 @@ class GotifyClient(GotifySession):
""" """
def get_application_messages( def get_application_messages(
self, application_id: int, limit: int = 100, since: int = None self, application_id: int, limit: int = 100, since: int | None = None
) -> Union[GotifyPagedMessagesModel, GotifyErrorModel]: ) -> GotifyPagedMessagesModel | GotifyErrorModel:
response = self._get( response = self._get(
f"/application/{application_id}/message", f"/application/{application_id}/message",
params={"limit": limit, "since": since}, params={"limit": limit, "since": since},
@@ -155,8 +155,8 @@ class GotifyClient(GotifySession):
return self._delete(f"/application/{application_id}/message").ok return self._delete(f"/application/{application_id}/message").ok
def get_messages( def get_messages(
self, limit: int = 100, since: int = None self, limit: int = 100, since: int | None = None
) -> Union[GotifyPagedMessagesModel, GotifyErrorModel]: ) -> GotifyPagedMessagesModel | GotifyErrorModel:
response = self._get("/message", params={"limit": limit, "since": since}) response = self._get("/message", params={"limit": limit, "since": since})
if not response.ok: if not response.ok:
return GotifyErrorModel(response) return GotifyErrorModel(response)
@@ -174,10 +174,10 @@ class GotifyClient(GotifySession):
def listen( def listen(
self, self,
opened_callback: Callable[[], None] = None, opened_callback: (Callable[[], None]) | None = None,
closed_callback: Callable[[int, str], None] = None, closed_callback: Callable[[int, str], None] | None = None,
new_message_callback: Callable[[GotifyMessageModel], None] = None, new_message_callback: Callable[[GotifyMessageModel], None] | None = None,
error_callback: Callable[[Exception], None] = None, error_callback: Callable[[Exception], None] | None = None,
): ):
def dummy(*args): def dummy(*args):
... ...
@@ -189,7 +189,7 @@ class GotifyClient(GotifySession):
self.listener.error.connect(error_callback or dummy) self.listener.error.connect(error_callback or dummy)
self.listener.start() self.listener.start()
def opened_callback(self, user_callback: Callable[[], None] = None): def opened_callback(self, user_callback: Callable[[], None] | None = None):
self.reset_wait_time() self.reset_wait_time()
if user_callback: if user_callback:
user_callback() user_callback()
@@ -222,7 +222,7 @@ class GotifyClient(GotifySession):
Health Health
""" """
def health(self) -> Union[GotifyHealthModel, GotifyErrorModel]: def health(self) -> GotifyHealthModel | GotifyErrorModel:
response = self._get("/health") response = self._get("/health")
return ( return (
GotifyHealthModel(response.json()) GotifyHealthModel(response.json())
@@ -234,7 +234,7 @@ class GotifyClient(GotifySession):
Version Version
""" """
def version(self) -> Union[GotifyVersionModel, GotifyErrorModel]: def version(self) -> GotifyVersionModel | GotifyErrorModel:
response = self._get("/version") response = self._get("/version")
return ( return (
GotifyVersionModel(response.json()) GotifyVersionModel(response.json())

View File

@@ -1,7 +1,6 @@
import datetime import datetime
from dateutil.parser import isoparse from dateutil.parser import isoparse
import logging import logging
from typing import List, Optional
import requests import requests
@@ -33,7 +32,7 @@ class GotifyApplicationModel(AttributeDict):
class GotifyPagingModel(AttributeDict): class GotifyPagingModel(AttributeDict):
limit: int limit: int
next: Optional[str] = None next: str | None = None
since: int since: int
size: int size: int
@@ -41,11 +40,11 @@ class GotifyPagingModel(AttributeDict):
class GotifyMessageModel(AttributeDict): class GotifyMessageModel(AttributeDict):
appid: int appid: int
date: datetime.datetime date: datetime.datetime
extras: Optional[dict] = None extras: dict | None = None
id: int id: int
message: str message: str
priority: Optional[int] = None priority: int | None = None
title: Optional[str] = None title: str | None = None
def __init__(self, d: dict, *args, **kwargs): def __init__(self, d: dict, *args, **kwargs):
d.update( d.update(
@@ -55,7 +54,7 @@ class GotifyMessageModel(AttributeDict):
class GotifyPagedMessagesModel(AttributeDict): class GotifyPagedMessagesModel(AttributeDict):
messages: List[GotifyMessageModel] messages: list[GotifyMessageModel]
paging: GotifyPagingModel paging: GotifyPagingModel

View File

@@ -4,7 +4,6 @@ import os
import platform import platform
import sys import sys
import tempfile import tempfile
from typing import List, Union
from gotify_tray import gotify from gotify_tray import gotify
from gotify_tray.__version__ import __title__ from gotify_tray.__version__ import __title__
@@ -87,9 +86,9 @@ class MainApplication(QtWidgets.QApplication):
self.first_connect = True self.first_connect = True
self.gotify_client.listen( self.gotify_client.listen(
new_message_callback=self.new_message_callback,
opened_callback=self.listener_opened_callback, opened_callback=self.listener_opened_callback,
closed_callback=self.listener_closed_callback, closed_callback=self.listener_closed_callback,
new_message_callback=self.new_message_callback,
error_callback=self.listener_error_callback, error_callback=self.listener_error_callback,
) )
@@ -119,7 +118,7 @@ class MainApplication(QtWidgets.QApplication):
self.get_applications_task.start() self.get_applications_task.start()
def get_applications_success_callback( def get_applications_success_callback(
self, applications: List[gotify.GotifyApplicationModel], self, applications: list[gotify.GotifyApplicationModel],
): ):
for i, application in enumerate(applications): for i, application in enumerate(applications):
icon = QtGui.QIcon( icon = QtGui.QIcon(
@@ -184,7 +183,7 @@ class MainApplication(QtWidgets.QApplication):
self.gotify_client.stop(reset_wait=True) self.gotify_client.stop(reset_wait=True)
def application_selection_changed_callback( def application_selection_changed_callback(
self, item: Union[ApplicationModelItem, ApplicationAllMessagesItem] self, item: ApplicationModelItem | ApplicationAllMessagesItem
): ):
self.messages_model.clear() self.messages_model.clear()
@@ -270,7 +269,7 @@ class MainApplication(QtWidgets.QApplication):
self.delete_message_task.start() self.delete_message_task.start()
def delete_all_messages_callback( def delete_all_messages_callback(
self, item: Union[ApplicationModelItem, ApplicationAllMessagesItem] self, item: ApplicationModelItem | ApplicationAllMessagesItem
): ):
if isinstance(item, ApplicationModelItem): if isinstance(item, ApplicationModelItem):
self.delete_application_messages_task = DeleteApplicationMessagesTask( self.delete_application_messages_task = DeleteApplicationMessagesTask(
@@ -374,7 +373,7 @@ class MainApplication(QtWidgets.QApplication):
self.messages_model.rowsInserted.connect(self.main_window.display_message_widgets) self.messages_model.rowsInserted.connect(self.main_window.display_message_widgets)
self.watchdog.closed.connect(lambda: self.listener_closed_callback(None, None)) self.watchdog.closed.connect(lambda: self.listener_closed_callback(0, 0))
def init_shortcuts(self): def init_shortcuts(self):
self.shortcut_quit = QtGui.QShortcut( self.shortcut_quit = QtGui.QShortcut(

View File

@@ -1,6 +1,5 @@
import enum import enum
from typing import Optional, Union
from PyQt6 import QtCore, QtGui from PyQt6 import QtCore, QtGui
from gotify_tray import gotify from gotify_tray import gotify
from gotify_tray.database import Settings from gotify_tray.database import Settings
@@ -18,7 +17,7 @@ class ApplicationModelItem(QtGui.QStandardItem):
def __init__( def __init__(
self, self,
application: gotify.GotifyApplicationModel, application: gotify.GotifyApplicationModel,
icon: Optional[QtGui.QIcon] = None, icon: QtGui.QIcon | None = None,
*args, *args,
**kwargs, **kwargs,
): ):
@@ -63,16 +62,16 @@ class ApplicationModel(QtGui.QStandardItemModel):
self, self,
row: int, row: int,
column: int, column: int,
item: Union[ApplicationModelItem, ApplicationAllMessagesItem], item: ApplicationModelItem | ApplicationAllMessagesItem,
) -> None: ) -> None:
super(ApplicationModel, self).setItem(row, column, item) super(ApplicationModel, self).setItem(row, column, item)
def itemFromIndex( def itemFromIndex(
self, index: QtCore.QModelIndex self, index: QtCore.QModelIndex
) -> Union[ApplicationModelItem, ApplicationAllMessagesItem]: ) -> ApplicationModelItem | ApplicationAllMessagesItem:
return super(ApplicationModel, self).itemFromIndex(index) return super(ApplicationModel, self).itemFromIndex(index)
def itemFromId(self, appid: int) -> Optional[ApplicationModelItem]: def itemFromId(self, appid: int) -> ApplicationModelItem | None:
for row in range(self.rowCount()): for row in range(self.rowCount()):
item = self.item(row, 0) item = self.item(row, 0)
if not isinstance(item, ApplicationModelItem): if not isinstance(item, ApplicationModelItem):

View File

@@ -45,7 +45,7 @@ def set_theme(app: QtWidgets.QApplication, theme: str = "automatic"):
app.setStyleSheet(stylesheet) app.setStyleSheet(stylesheet)
def get_theme_file(app: QtWidgets.QApplication, file: str, theme: str = None) -> str: def get_theme_file(app: QtWidgets.QApplication, file: str, theme: str | None = None) -> str:
theme = settings.value("theme", type=str) if not theme else theme theme = settings.value("theme", type=str) if not theme else theme
if not is_valid_theme(theme): if not is_valid_theme(theme):

View File

@@ -8,7 +8,7 @@ settings = Settings("gotify-tray")
class ImagePopup(QtWidgets.QLabel): class ImagePopup(QtWidgets.QLabel):
def __init__(self, filename: str, pos: QtCore.QPoint, link: str = None): def __init__(self, filename: str, pos: QtCore.QPoint, link: str | None = None):
"""Create and show a pop-up image under the cursor """Create and show a pop-up image under the cursor
Args: Args:

View File

@@ -23,7 +23,7 @@ class MessageWidget(QtWidgets.QWidget, Ui_Form):
app: QtWidgets.QApplication, app: QtWidgets.QApplication,
parent: QtWidgets.QWidget, parent: QtWidgets.QWidget,
message_item: MessagesModelItem, message_item: MessagesModelItem,
icon: QtGui.QIcon = None, icon: QtGui.QIcon | None = None,
): ):
super(MessageWidget, self).__init__(parent) super(MessageWidget, self).__init__(parent)
self.app = app self.app = app

View File

@@ -4,7 +4,7 @@ import re
import subprocess import subprocess
from pathlib import Path from pathlib import Path
from typing import Iterator, List, Optional from typing import Iterator
from gotify_tray import gotify from gotify_tray import gotify
from gotify_tray.database import Downloader from gotify_tray.database import Downloader
@@ -31,7 +31,7 @@ def verify_server(force_new: bool = False, enable_import: bool = True) -> bool:
return True return True
def process_messages(messages: List[gotify.GotifyMessageModel]) -> Iterator[gotify.GotifyMessageModel]: def process_messages(messages: list[gotify.GotifyMessageModel]) -> Iterator[gotify.GotifyMessageModel]:
downloader = Downloader() downloader = Downloader()
for message in messages: for message in messages:
if image_url := get_image(message.message): if image_url := get_image(message.message):
@@ -56,7 +56,7 @@ def convert_links(text):
return _link.sub(replace, text) return _link.sub(replace, text)
def get_image(s: str) -> Optional[str]: def get_image(s: str) -> str | None:
"""If `s` contains only an image URL, this function returns that URL. """If `s` contains only an image URL, this function returns that URL.
This function also extracts a URL in the `![](<url>)` markdown image format. This function also extracts a URL in the `![](<url>)` markdown image format.
""" """