Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .audit/bblommers_chore-apply-ruff-up.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
- [x] I did **not** use any AI-assistance tools to help create this pull request.
- [ ] I **did** use AI-assistance tools to *help* create this pull request.
- [x] I have read, understood and followed the projects' [AI Policy](https://github.com/crossbario/autobahn-python/blob/main/AI_POLICY.md) when creating code, documentation etc. for this pull request.

Submitted by: @bblommers
Date: 2026-01-09
Related issue(s): #1841
Branch: bblommers:chore-apply-ruff-up
20 changes: 9 additions & 11 deletions src/autobahn/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ def do_call(reactor, session, options):
call_kwargs = {k: v for k, v in options.keyword}

results = yield session.call(options.uri, *call_args, **call_kwargs)
print("result: {}".format(results))
print(f"result: {results}")


@inlineCallbacks
Expand Down Expand Up @@ -260,11 +260,11 @@ def do_register(reactor, session, options):

@inlineCallbacks
def called(*args, **kw):
print("called: args={}, kwargs={}".format(args, kw), file=sys.stderr)
print(f"called: args={args}, kwargs={kw}", file=sys.stderr)
env = copy(os.environ)
env["WAMP_ARGS"] = " ".join(args)
env["WAMP_ARGS_JSON"] = json.dumps(args)
env["WAMP_KWARGS"] = " ".join("{}={}".format(k, v) for k, v in kw.items())
env["WAMP_KWARGS"] = " ".join(f"{k}={v}" for k, v in kw.items())
env["WAMP_KWARGS_JSON"] = json.dumps(kw)

exe = os.path.abspath(options.command[0])
Expand All @@ -286,7 +286,7 @@ def processExited(self, reason):
code = yield done

if code != 0:
print("Failed with exit-code {}".format(code))
print(f"Failed with exit-code {code}")
if countdown[0]:
countdown[0] -= 1
if countdown[0] <= 0:
Expand Down Expand Up @@ -350,12 +350,12 @@ def _real_main(reactor):
exe = options.command[0]
if not os.path.isabs(exe):
print(
"Full path to the executable required. Found: {}".format(exe),
f"Full path to the executable required. Found: {exe}",
file=sys.stderr,
)
sys.exit(1)
if not os.path.exists(exe):
print("Executable not found: {}".format(exe), file=sys.stderr)
print(f"Executable not found: {exe}", file=sys.stderr)
sys.exit(1)

subcommands = {
Expand All @@ -372,9 +372,7 @@ def _real_main(reactor):
@inlineCallbacks
def _(session, details):
print(
"connected: authrole={} authmethod={}".format(
details.authrole, details.authmethod
),
f"connected: authrole={details.authrole} authmethod={details.authmethod}",
file=sys.stderr,
)
try:
Expand All @@ -388,10 +386,10 @@ def _(session, details):

@component.on_connectfailure
def _(comp, fail):
print("connect failure: {}".format(fail))
print(f"connect failure: {fail}")
failures.append(fail)
if options.max_failures > 0 and len(failures) > options.max_failures:
print("Too many failures ({}). Exiting".format(len(failures)))
print(f"Too many failures ({len(failures)}). Exiting")
reactor.stop()

yield component.start(reactor)
Expand Down
3 changes: 1 addition & 2 deletions src/autobahn/_flatc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@
import subprocess
import sys
from pathlib import Path
from typing import List, Optional


def get_flatc_path() -> Path:
Expand All @@ -79,7 +78,7 @@ def get_flatc_path() -> Path:
return flatc_path


def run_flatc(args: List[str], cwd: Optional[str] = None) -> int:
def run_flatc(args: list[str], cwd: str | None = None) -> int:
"""
Run the bundled flatc with the given arguments.

Expand Down
13 changes: 2 additions & 11 deletions src/autobahn/asyncio/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,18 +52,9 @@
if USES_NVX:
import cffi

__ident__ = "Autobahn/{}-NVXCFFI/{}-asyncio-{}/{}".format(
autobahn.__version__,
cffi.__version__,
platform.python_implementation(),
platform.python_version(),
)
__ident__ = f"Autobahn/{autobahn.__version__}-NVXCFFI/{cffi.__version__}-asyncio-{platform.python_implementation()}/{platform.python_version()}"
else:
__ident__ = "Autobahn/{}-asyncio-{}/{}".format(
autobahn.__version__,
platform.python_implementation(),
platform.python_version(),
)
__ident__ = f"Autobahn/{autobahn.__version__}-asyncio-{platform.python_implementation()}/{platform.python_version()}"

"""
Identification string for the Autobahn|Python asyncio backend.
Expand Down
34 changes: 10 additions & 24 deletions src/autobahn/asyncio/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def _create_transport_factory(loop, transport, session_factory):
factory.setProtocolOptions(**{_camel_case_from_snake_case(k): v})
except (TypeError, KeyError):
raise ValueError(
"Unknown {} transport option: {}={}".format(transport.type, k, v)
f"Unknown {transport.type} transport option: {k}={v}"
)
return factory

Expand Down Expand Up @@ -120,7 +120,7 @@ def _check_native_endpoint(self, endpoint):
if isinstance(endpoint, dict):
if "tls" in endpoint:
tls = endpoint["tls"]
if isinstance(tls, (dict, bool)):
if isinstance(tls, dict | bool):
pass
elif isinstance(tls, ssl.SSLContext):
pass
Expand Down Expand Up @@ -149,9 +149,7 @@ def _connect_transport(self, loop, transport, session_factory, done):
timeout = transport.endpoint.get("timeout", 10) # in seconds
if type(timeout) != int:
raise ValueError(
"invalid type {} for timeout in client endpoint configuration".format(
type(timeout)
)
f"invalid type {type(timeout)} for timeout in client endpoint configuration"
)
# do we support HTTPS proxies?

Expand All @@ -167,33 +165,25 @@ def _connect_transport(self, loop, transport, session_factory, done):
version = transport.endpoint.get("version", 4)
if version not in [4, 6]:
raise ValueError(
"invalid IP version {} in client endpoint configuration".format(
version
)
f"invalid IP version {version} in client endpoint configuration"
)

host = transport.endpoint["host"]
if type(host) != str:
raise ValueError(
"invalid type {} for host in client endpoint configuration".format(
type(host)
)
f"invalid type {type(host)} for host in client endpoint configuration"
)

port = transport.endpoint["port"]
if type(port) != int:
raise ValueError(
"invalid type {} for port in client endpoint configuration".format(
type(port)
)
f"invalid type {type(port)} for port in client endpoint configuration"
)

timeout = transport.endpoint.get("timeout", 10) # in seconds
if type(timeout) != int:
raise ValueError(
"invalid type {} for timeout in client endpoint configuration".format(
type(timeout)
)
f"invalid type {type(timeout)} for timeout in client endpoint configuration"
)

tls = transport.endpoint.get("tls", None)
Expand All @@ -205,14 +195,12 @@ def _connect_transport(self, loop, transport, session_factory, done):
for k in tls.keys():
if k not in ["hostname", "trust_root"]:
raise ValueError(
"Invalid key '{}' in 'tls' config".format(k)
f"Invalid key '{k}' in 'tls' config"
)
hostname = tls.get("hostname", host)
if type(hostname) != str:
raise ValueError(
"invalid type {} for hostname in TLS client endpoint configuration".format(
hostname
)
f"invalid type {hostname} for hostname in TLS client endpoint configuration"
)
cert_fname = tls.get("trust_root", None)

Expand All @@ -234,9 +222,7 @@ def _connect_transport(self, loop, transport, session_factory, done):

else:
raise RuntimeError(
'unknown type {} for "tls" configuration in transport'.format(
type(tls)
)
f'unknown type {type(tls)} for "tls" configuration in transport'
)

f = loop.create_connection(
Expand Down
26 changes: 11 additions & 15 deletions src/autobahn/asyncio/rawsocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,11 @@ class PrefixProtocol(asyncio.Protocol):
max_length = 16 * 1024 * 1024
max_length_send = max_length
log = txaio.make_logger() # @UndefinedVariable
peer: Optional[str] = None
is_server: Optional[bool] = None
peer: str | None = None
is_server: bool | None = None

@property
def transport_details(self) -> Optional[TransportDetails]:
def transport_details(self) -> TransportDetails | None:
"""
Implements :func:`autobahn.wamp.interfaces.ITransport.transport_details`
"""
Expand Down Expand Up @@ -221,7 +221,7 @@ def data_received(self, data):
try:
self.process_handshake()
except HandshakeError as e:
self.protocol_error("Handshake error : {err}".format(err=e))
self.protocol_error(f"Handshake error : {e}")
return
self._handshake_done = True
self._on_handshake_complete()
Expand All @@ -244,7 +244,7 @@ def data_received(self, data):

class HandshakeError(Exception):
def __init__(self, msg, code=0):
Exception.__init__(self, msg if not code else msg + " : %s" % ERRMAP.get(code))
Exception.__init__(self, msg if not code else msg + f" : {ERRMAP.get(code)}")


class RawSocketClientProtocol(RawSocketProtocol):
Expand All @@ -259,9 +259,7 @@ def process_handshake(self):
raise HandshakeError("Server returned handshake error", err)
if self.serializer_id != ser_id:
raise HandshakeError(
"Server returned different serializer {0} then requested {1}".format(
ser_id, self.serializer_id
)
f"Server returned different serializer {ser_id} then requested {self.serializer_id}"
)

@property
Expand Down Expand Up @@ -293,13 +291,13 @@ def send_response(lexp, ser_id):
if not self.supports_serializer(ser_id):
send_response(ERR_SERIALIZER_UNSUPPORTED, 0)
raise HandshakeError(
"Serializer unsupported : {ser_id}".format(ser_id=ser_id)
f"Serializer unsupported : {ser_id}"
)
send_response(self._length_exp, ser_id)


# this is transport independent part of WAMP protocol
class WampRawSocketMixinGeneral(object):
class WampRawSocketMixinGeneral:
def _on_handshake_complete(self):
self.log.debug("WampRawSocketProtocol: Handshake complete")
# RawSocket connection established. Now let the user WAMP session factory
Expand Down Expand Up @@ -364,9 +362,7 @@ def send(self, msg):
except Exception as e:
# all exceptions raised from above should be serialization errors ..
raise SerializationError(
"WampRawSocketProtocol: unable to serialize WAMP application payload ({0})".format(
e
)
f"WampRawSocketProtocol: unable to serialize WAMP application payload ({e})"
)
else:
self.sendString(payload)
Expand All @@ -385,7 +381,7 @@ def isOpen(self):


# this is asyncio dependent part of WAMP protocol
class WampRawSocketMixinAsyncio(object):
class WampRawSocketMixinAsyncio:
"""
Base class for asyncio-based WAMP-over-RawSocket protocols.
"""
Expand Down Expand Up @@ -474,7 +470,7 @@ def serializer_id(self):
return self._serializer.RAWSOCKET_SERIALIZER_ID


class WampRawSocketFactory(object):
class WampRawSocketFactory:
"""
Adapter class for asyncio-based WebSocket client and server factories.def dataReceived(self, data):
"""
Expand Down
14 changes: 7 additions & 7 deletions src/autobahn/asyncio/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@


def transport_channel_id(
transport, is_server: bool, channel_id_type: Optional[str] = None
transport, is_server: bool, channel_id_type: str | None = None
) -> bytes:
"""
Application-layer user authentication protocols are vulnerable to generic
Expand All @@ -63,7 +63,7 @@ def transport_channel_id(

# ssl.CHANNEL_BINDING_TYPES
if channel_id_type not in ["tls-unique"]:
raise Exception("invalid channel ID type {}".format(channel_id_type))
raise Exception(f"invalid channel ID type {channel_id_type}")

ssl_obj = transport.get_extra_info("ssl_object")
if ssl_obj is None:
Expand Down Expand Up @@ -96,24 +96,24 @@ def peer2str(transport: asyncio.transports.BaseTransport) -> str:
peer = transport.get_extra_info("peername")
if isinstance(peer, tuple):
ip_ver = 4 if len(peer) == 2 else 6
return "tcp{2}:{0}:{1}".format(peer[0], peer[1], ip_ver)
return f"tcp{ip_ver}:{peer[0]}:{peer[1]}"
elif isinstance(peer, str):
return "unix:{0}".format(peer)
return f"unix:{peer}"
else:
return "?:{0}".format(peer)
return f"?:{peer}"
except:
pass

try:
proc: Popen = transport.get_extra_info("subprocess")
# return 'process:{}'.format(transport.pid)
return "process:{}".format(proc.pid)
return f"process:{proc.pid}"
except:
pass

try:
pipe = transport.get_extra_info("pipe")
return "pipe:{}".format(pipe)
return f"pipe:{pipe}"
except:
pass

Expand Down
7 changes: 3 additions & 4 deletions src/autobahn/asyncio/wamp.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ class ApplicationSessionFactory(protocol.ApplicationSessionFactory):


@public
class ApplicationRunner(object):
class ApplicationRunner:
"""
This class is a convenience tool mainly for development and quick hosting
of WAMP application components.
Expand Down Expand Up @@ -179,7 +179,7 @@ def create():
session = make(cfg)
except Exception as e:
self.log.error(
"ApplicationSession could not be instantiated: {}".format(e)
f"ApplicationSession could not be instantiated: {e}"
)
loop = asyncio.get_event_loop()
if loop.is_running():
Expand Down Expand Up @@ -249,9 +249,8 @@ def accept(response):
else:
if self.ssl and not isSecure:
raise RuntimeError(
'ssl argument value passed to %s conflicts with the "ws:" '
f'ssl argument value passed to {self.__class__.__name__} conflicts with the "ws:" '
'prefix of the url argument. Did you mean to use "wss:"?'
% self.__class__.__name__
)
ssl = self.ssl

Expand Down
6 changes: 3 additions & 3 deletions src/autobahn/asyncio/websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,8 @@ class WebSocketAdapterProtocol(asyncio.Protocol):

log = txaio.make_logger()

peer: Optional[str] = None
is_server: Optional[bool] = None
peer: str | None = None
is_server: bool | None = None

def connection_made(self, transport):
# asyncio networking framework entry point, called by asyncio
Expand Down Expand Up @@ -240,7 +240,7 @@ def startTLS(self):
raise Exception("WSS over explicit proxies not implemented")


class WebSocketAdapterFactory(object):
class WebSocketAdapterFactory:
"""
Adapter class for asyncio-based WebSocket client and server factories.
"""
Expand Down
Loading