[Asterisk-code-review] Changes required for Python 3 compatibility (starpy[1.1])

Michael Bradeen asteriskteam at digium.com
Wed Mar 16 14:29:36 CDT 2022


Michael Bradeen has uploaded this change for review. ( https://gerrit.asterisk.org/c/starpy/+/18244 )


Change subject: Changes required for Python 3 compatibility
......................................................................

Changes required for Python 3 compatibility

manager: Replace 'async' reference with 'nowait'.  This change breaks backwards
compatibility with previous versions of the testsuite, requiring a matching
change there.

manager and fastagi: twisted in general uses bytes for passing data back and
forth while internally we generally want to deal with strings.  This requires
converting between the two as we interact with the twisted library.

ASTERISK-26826

Change-Id: I2fab42abb5318a5db2af3bcd291fc2db95b87e15
---
M starpy/fastagi.py
M starpy/manager.py
2 files changed, 21 insertions(+), 19 deletions(-)



  git pull ssh://gerrit.asterisk.org:29418/starpy refs/changes/44/18244/1

diff --git a/starpy/fastagi.py b/starpy/fastagi.py
index 85de054..4e888ee 100644
--- a/starpy/fastagi.py
+++ b/starpy/fastagi.py
@@ -81,7 +81,7 @@
     """
     readingVariables = False
     lostConnectionDeferred = None
-    delimiter = '\n'
+    delimiter = b'\n'
 
     def __init__(self, *args, **named):
         """Initialise the AMIProtocol, arguments are ignored"""
@@ -117,17 +117,18 @@
 
     def lineReceived(self, line):
         """(Internal) Handle Twisted's report of an incoming line from AMI"""
-        log.debug('Line In: %r', line)
+        linestring = line.decode("utf-8")
+        log.debug('Line In: %r', linestring)
         if self.readingVariables:
-            if not line.strip():
+            if not linestring.strip():
                 self.readingVariables = False
                 self.factory.mainFunction(self)
             else:
                 try:
-                    key, value = line.split(':', 1)
+                    key, value = linestring.split(':', 1)
                     value = value[1:].rstrip('\n').rstrip('\r')
                 except ValueError as err:
-                    log.error("""Invalid variable line: %r""", line)
+                    log.error("""Invalid variable line: %r""", linestring)
                 else:
                     self.variables[key.lower()] = value
                     log.debug("""%s = %r""", key, value)
@@ -135,21 +136,21 @@
             try:
                 df = self.pendingMessages.pop(0)
             except IndexError as err:
-                log.warn("Line received without pending deferred: %r", line)
+                log.warn("Line received without pending deferred: %r", linestring)
             else:
-                if line.startswith('200'):
-                    line = line[4:]
-                    if line.lower().startswith('result='):
-                        line = line[7:]
-                    df.callback(line)
+                if linestring.startswith('200'):
+                    linestring = linestring[4:]
+                    if linestring.lower().startswith('result='):
+                        linestring = linestring[7:]
+                    df.callback(linestring)
                 else:
                     # XXX parse out the error code
                     try:
-                        errCode, line = line.split(' ', 1)
+                        errCode, linestring = linestring.split(' ', 1)
                         errCode = int(errCode)
                     except ValueError as err:
                         errCode = 500
-                    df.errback(error.AGICommandFailure(errCode, line))
+                    df.errback(error.AGICommandFailure(errCode, linestring))
 
     def sendCommand(self, commandString):
         """(Internal) Send the given command to the other side"""
@@ -157,7 +158,7 @@
         commandString = commandString.rstrip('\n').rstrip('\r')
         df = defer.Deferred()
         self.pendingMessages.append(df)
-        self.sendLine(commandString)
+        self.sendLine(bytes(commandString,"utf-8"))
         return df
 
     def checkFailure(self, result, failure='-1'):
diff --git a/starpy/manager.py b/starpy/manager.py
index 70c93b3..72d94ea 100644
--- a/starpy/manager.py
+++ b/starpy/manager.py
@@ -168,8 +168,9 @@
 
     def lineReceived(self, line):
         """Handle Twisted's report of an incoming line from the manager"""
-        log.debug('Line In: %r', line)
-        self.messageCache.append(line)
+        linestring = line.decode("utf-8")
+        log.debug('Line In: %r', linestring)
+        self.messageCache.append(linestring)
         if not line.strip():
             self.dispatchIncoming()  # does dispatch and clears cache
 
@@ -716,7 +717,7 @@
     def originate(
             self, channel, context=None, exten=None, priority=None,
             timeout=None, callerid=None, account=None, application=None,
-            data=None, variable={}, async=False, channelid=None,
+            data=None, variable={}, nowait=False, channelid=None,
             otherchannelid=None, codecs=None):
         """Originate call to connect channel to given context/exten/priority
 
@@ -730,7 +731,7 @@
         application -- alternate application to Dial to use for outbound dial
         data -- data to pass to application
         variable -- variables associated to the call
-        async -- make the origination asynchronous
+        nowait -- make the origination asynchronous
         """
         message = [(k, v) for (k, v) in (
             ('action', 'originate'),
@@ -742,7 +743,7 @@
             ('account', account),
             ('application', application),
             ('data', data),
-            ('async', str(async)),
+            ('async', str(nowait)),
             ('channelid', channelid),
             ('otherchannelid', otherchannelid),
             ('codecs', codecs),

-- 
To view, visit https://gerrit.asterisk.org/c/starpy/+/18244
To unsubscribe, or for help writing mail filters, visit https://gerrit.asterisk.org/settings

Gerrit-Project: starpy
Gerrit-Branch: 1.1
Gerrit-Change-Id: I2fab42abb5318a5db2af3bcd291fc2db95b87e15
Gerrit-Change-Number: 18244
Gerrit-PatchSet: 1
Gerrit-Owner: Michael Bradeen <mbradeen at sangoma.com>
Gerrit-MessageType: newchange
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.digium.com/pipermail/asterisk-code-review/attachments/20220316/6b133ebe/attachment.html>


More information about the asterisk-code-review mailing list