本文整理汇总了Python中connection.Connection类的典型用法代码示例。如果您正苦于以下问题:Python Connection类的具体用法?Python Connection怎么用?Python Connection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Connection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: render_DELETE
def render_DELETE(self, request):
connection_id = self.pop_connection_id()
connection = Connection(self, request, connection_id)
try:
(channel_id, format) = connection.get_channel_id_and_format()
except ValueError, e:
return connection.error(-1, str(e))
示例2: establish
def establish(self, timeout=None):
"""
Tries to establish a client connection.
Args:
timeout: the timeout in seconds
Returns:
True if the connection was established, and False if it wasn't.
"""
Connection.establish(self, timeout)
# Create and configure the endpoint
if (not self._useSSL) :
endpoint = TCP4ClientEndpoint(reactor, self.__host, self._port, timeout, None)
else :
keyPath = self._certificatesDirectory + "/" + "server.key"
certificatePath = self._certificatesDirectory + "/" + "server.crt"
try :
endpoint = SSL4ClientEndpoint(reactor, self.__host, self._port,
ssl.DefaultOpenSSLContextFactory(keyPath, certificatePath), timeout)
except Exception:
raise ConnectionException("The key, the certificate or both were not found")
# Establish the connection
self._deferred = endpoint.connect(self._factory)
self.__working = True
def _handleError(error):
self.__working = False
self._setError(Connection._prettyPrintTwistedError(error))
def _handleConnection(error):
self.__working = False
self._deferred.addCallback(_handleConnection)
self._deferred.addErrback(_handleError)
# Wait until it's ready
while(self.__working) :
sleep(0.1)
return self._error == None
示例3: render_POST
def render_POST(self, request):
connection_id = self.pop_connection_id()
connection = Connection(self, request, connection_id)
try:
format = connection.get_format(self.config.clients_uri_path)
except ValueError, e:
return connection.error(-1, str(e))
示例4: InfiniteQuestWindow
class InfiniteQuestWindow(QMainWindow):
# ----------------------------------------------------------------------
def __init__(self):
""""""
super(InfiniteQuestWindow, self).__init__()
self.setWindowTitle("Infinite Quest")
self.mapview = MapView()
# self.mapview = QGraphicsView()
# self.sc = MapScene()
# self.mapview.setScene(self.sc)
self.mapview.installEventFilter(self)
self.setCentralWidget(self.mapview)
self.minimap = MiniMapView(self.mapview)
minimap_dw = QDockWidget()
minimap_dw.setWidget(self.minimap)
self.addDockWidget(Qt.LeftDockWidgetArea, minimap_dw)
self.statushero = StatusHeroWidget()
statushero_dw = QDockWidget()
statushero_dw.setWidget(self.statushero)
self.addDockWidget(Qt.LeftDockWidgetArea, statushero_dw)
# self.mapview.setSizePolicy(QSizePolicy(QSizePolicy.MinimumExpanding,QSizePolicy.MinimumExpanding))
self.world = World()
self.hero = Hero(self.world.map(), *self.world.map().find_passable_landscape_coords())
self.connection = Connection(self.hero, self.world)
self.game_state_update()
# ----------------------------------------------------------------------
def game_state_update(self):
""""""
st = self.connection.get_world_state()
self.mapview.scene.mapstate_update(st["map_state"])
# ----------------------------------------------------------------------
def eventFilter(self, obj, ev):
""""""
if ev.type() == QEvent.KeyPress:
try:
self.connection.action(
{
Qt.Key_Up: "move_up",
Qt.Key_Down: "move_down",
Qt.Key_Right: "move_right",
Qt.Key_Left: "move_left",
}[ev.key()]
)
self.game_state_update()
return True
except KeyError:
pass
else:
pass
return super(InfiniteQuestWindow, self).eventFilter(obj, ev)
示例5: establish
def establish(self, timeout):
"""
Establishes a server connection.
Args:
timeout: this parameter will be ignored.
Returns:
Nothing
"""
Connection.establish(self, timeout)
# Create and configure the endpoint
if (not self._useSSL) :
endpoint = TCP4ServerEndpoint(reactor, self._port)
else :
keyPath = self._certificatesDirectory + "/" + "server.key"
certificatePath = self._certificatesDirectory + "/" + "server.crt"
try :
endpoint = SSL4ServerEndpoint(reactor, self._port, ssl.DefaultOpenSSLContextFactory(keyPath, certificatePath))
except Exception:
raise ConnectionException("The key, the certificate or both were not found")
# Establish the connection
def _registerListeningPort(port):
self.__listenningPort = port
def _onError(error):
self._setError(Connection._prettyPrintTwistedError(error))
self._deferred = endpoint.listen(self._factory)
# Configure the deferred object
self._deferred.addCallback(_registerListeningPort)
self._deferred.addErrback(_onError)
示例6: run
def run(self):
logging.debug('Connecting to {}'.format(self.destination))
self._connect()
if not shared.shutting_down and self.success:
c = Connection(self.destination, 'i2p', self.s, 'i2p', False, self.destination)
c.start()
shared.connections.add(c)
示例7: readBroadcastDatagram
def readBroadcastDatagram(self):
while self.broadcastSocket.hasPendingDatagrams():
senderIp = QHostAddress()
senderPort = 0;
datagram = QByteArray()
#datagram.resize(self.broadcastSocket.pendingDatagramSize())
#if self.broadcastSocket.readDatagram(datagram.data(), datagram.size(), senderIp, senderPort) == -1:
# continue
datagram, host, port = self.broadcastSocket.readDatagram(self.broadcastSocket.pendingDatagramSize())
try:
# Python v3.
datagram = str(datagram, encoding='ascii')
except TypeError:
# Python v2.
pass
senderIp = host.toString()
senderPort = port
templist = list()
templist = datagram.split('@')
if len(templist) != 2:
continue
senderServerPort = int(templist[1])
if self.isLocalHostAddress(senderIp) and senderServerPort == self.serverPort:
continue
senderPort = -1
if not self.client.hasConnection(senderIp, senderPort):
connection = Connection(self)
self.newconnection_signal.emit(connection)
connection.connectToHost(senderIp, senderServerPort)
示例8: dialog_handler
def dialog_handler(ns):
"""Show the dialog window."""
verb = verbose_print(ns.verbose)
conn = Connection(verb, ssh=False)
verb('Show dialog window')
io.show_dialog_header(conn)
conn.init_dialog_window()
示例9: main
def main():
server_port = 30000
client_port = 30001
protocol_id= 0x99887766
delta_time = 0.25
send_rate = 0.25
time_out = 10
connection = Connection(protocol_id, time_out)
if not connection.start(server_port):
print("Could not start connection on port {}".format(server_port))
return 1
connection.listen()
while 1:
if connection.is_connected():
print('server sending packet')
packet = [c for c in "server to client"]
connection.send_packet(packet)
while 1:
bytes_read, pack = connection.receive_packet(256)
if bytes_read == 0:
break
print("Received packet from client")
connection.update(delta_time)
time.sleep(delta_time)
示例10: on_message
def on_message(self, message):
if not message:
return
# print(message)
if message == "request_code":
letters = [b for b in [random.choice(string.ascii_uppercase)
for a in range(5)]]
code = ""
for letter in letters:
code += letter
self.ws.send("code %s" % code)
elif message[:6] == "hello ":
command, session, role = message.split()
session = session.upper()
con = Connection.get_connection(session)
if role == "controller":
if con.connected("display"):
con.connect(role, self.ws)
con.display.send("controller_connected")
con.controller.send("connect_succesful")
else:
self.ws.send("connect_failed")
elif role == "display":
con.connect(role, self.ws)
else:
print("Error: unknown role: %s" % role)
else:
con = Connection.get_connection_ws(self.ws)
destination_ws = con.another_ws(self.ws)
if destination_ws is not None:
destination_ws.send(message)
示例11: get_new_con
def get_new_con(self, server=None, port=None, auth=None,
register_events=False,
**kwargs):
'''
Return a new esl connection to the specified FS server and optionally
subscribe to any events actively handled by this listener
Parameters
----------
server : string
fs server ip
port : string
port to connect on
auth : string
authorization username
register_events : bool
indicates whether or not the connection should be subscribed
to receive all default events declared by the listener's
'default_handlers' map
kwargs : same as for .connection.Connection
Returns
-------
con : Connection
'''
con = Connection(server or self.server, port or self.port,
auth or self.auth, **kwargs)
if register_events:
con.subscribe(self._handlers)
return con
示例12: main
def main():
with open("swift_xauth.conf", "w+") as swift_open:
get_connection = Connection(sys.argv[1], sys.argv[2])
auth_token = get_connection.get_xauthtoken()
xstorageurl = get_connection.get_storage_url()
swift_open.write(auth_token + "\n")
swift_open.write(xstorageurl)
示例13: sync_description
def sync_description(self):
""" Salva a descrição da coluna no banco de dados """
try:
if self.description is not None:
Connection.execute(
u"""COMMENT ON COLUMN "{0}"."{1}"."{2}" IS %s"""
.format(self.schema, self.table, self.name,),
(self.description,)
)
else:
Connection.execute(
u"""COMMENT ON COLUMN "{0}"."{1}"."{2}" IS NULL"""
.format(self.schema, self.table, self.name,)
)
except Exception, e:
warnings.warn(
"Erro ao sincronizar a coluna {0}.{1}.{2}: {3}"
.format(self.schema, self.table, self.name, e),
RuntimeWarning
)
示例14: __init__
def __init__(self, urlOrCfg, project=None, certificate=None, privateKey=None, caChain=None):
'''Initialize resource.
This is done either by specifying all components or by only giving the
first parameter pointing to a resource daemon configuration file.
Instead of a resource daemon configuration file, it can also point to a
tarball containing LGI.cfg as resource daemon configuration file and
certificates.
@type urlOrCfg str
@param urlOrCfg location of configuration file, or LGI project server url
@type project str
@param project LGI project to work with
@type certificate str
@param certificate location of user certificate file
@type privateKey str
@param privateKey location of user private key file
@type caChain str
@param caChain location of CA chain to validate LGI project server with
'''
self._apps = None
self._sessionId = None
self._tmpdir = None
if project:
Connection.__init__(self, urlOrCfg, project, certificate, privateKey, caChain)
else:
Connection.__init__(self, None, None, None, None, None)
if tarfile.is_tarfile(urlOrCfg):
self.parseTarball(urlOrCfg)
else:
self.parseConfig(urlOrCfg)
示例15: __init__
class Client:
def __init__(self, socket, address, port):
print 'Init Client'
ee = EventEmitter()
self._packet_sender = PacketSender(socket, address, port)
self._connection = Connection(self._packet_sender)
@self._connection.ee.on('data')
def on_data(data):
ee.emit('data', data)
def on_message(message, rinfo):
if rinfo.address is not address or rinfo.port is not port:
return
packet = Packet(message)
if packet.getIsFinish():
socket.close()
return
self._connection.receive(packet)
#socket.on('message', on_message)
def send(self, data):
self._connection.send(data)
def close(self):
self._packet_sender.send(Packet.createFinishPacket())