python-3.xaiortc

Is there a way to set a global variable to be used with aiortc?


I'm trying to have a python RTC client use a global variable so that I can reuse it for multiple functions.

I'm using this for a RTC project I¨ve been working on, I have a functioning js Client, but the functions work differently from python. The functions on the server and js client side are my own, and do not have have parameters, and I hope to avoid having to use them on the python client I'm making.

I've been using the aiortc Cli.py from their github as a basis for how my python clien should work. But I don't run it asynchronous, because I am trying to learn and control when events happen. the source code can be found here, I am referring to the codes in line 71-72 https://github.com/aiortc/aiortc/blob/master/examples/datachannel-cli/cli.py

this is the code I'm trying to run properly

I've only inserted the code relevant to my current issue


import argparse
import asyncio
import logging
import time

from aiortc import RTCIceCandidate, RTCPeerConnection, RTCSessionDescription
from aiortc.contrib.signaling import add_signaling_arguments, create_signaling

pc = None
channel = None

def createRTCPeer():
    print("starting RTC Peer")
    pc = RTCPeerConnection()
    print("created Peer", pc)
    return pc

def pythonCreateDataChannel():
    print("creating datachannel")
    channel = pc.CreateDataChannel("chat")

the createRTCPeer function works as intended, with it creating an RTC Object, but my pythonCreateDataChannel reports an error, if I have it set to "None" before using it

AttributeError: 'NoneType' object has no attribute 'CreateDataChannel'

and it will report

NameError: name 'channel' is not defined

same goes for pc if I don't set it in the global scope before hand


Solution

  • Have you tried this:

    import argparse
    import asyncio
    import logging
    import time
    
    from aiortc import RTCIceCandidate, RTCPeerConnection, RTCSessionDescription
    from aiortc.contrib.signaling import add_signaling_arguments, create_signaling
    
    pc = None
    channel = None
    
    def createRTCPeer():
        print("starting RTC Peer")
        global pc
        pc = RTCPeerConnection()
        print("created Peer", pc)
    
    def pythonCreateDataChannel():
        print("creating datachannel")
        global channel
        channel = pc.CreateDataChannel("chat")