def __init__(self): QtWidgets.QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.sports = [] self.ui.add_btn.clicked.connect(self._newForm) self.ui.item1 = QtWidgets.QListWidgetItem("Events") self.ui.main_list.addItem(self.ui.item1) self.ui.item2 = QtWidgets.QListWidgetItem("Results") self.ui.main_list.addItem(self.ui.item2) self.ui.main_list.itemClicked.connect(self._mainClicked) self.manager = QtNetwork.QNetworkAccessManager() self.sport_req = QtNetwork.QNetworkRequest(QtCore.QUrl("API URL")) self.sport_reply = self.manager.get(self.sport_req) self.sport_reply.finished.connect(self._sportsReply) self.ui.sport_combo.activated.connect(self._mainReq) self.ui.subClass_list.itemClicked.connect(self._loadForm) self.sport_dic = {} self.loaded = [] self.resizeTimer = QtCore.QTimer() self.resizeTimer.setSingleShot(True) self.resizeTimer.timeout.connect(self.tryResize)
def _lookup(self): url = self.ui.url.text().strip() if not url: return print('\nLooking up "%s" ...' % url) self._t0 = time.time() self._chunks = 0 self._canceled = False if self._manager is None: self._manager = QtNetwork.QNetworkAccessManager(self) request = QtNetwork.QNetworkRequest(QtCore.QUrl(url)) request.setRawHeader(b'User-Agent', b'MyOwnBrowser 1.0') reply = self._manager.get(request) reply.finished.connect(self._on_finish) reply.downloadProgress.connect(self._on_progress) reply.error[QtNetwork.QNetworkReply.NetworkError].connect( self._on_error) reply.sslErrors.connect(self._on_error) reply.readyRead.connect(self._on_ready_read) self._error_connected = False self._try_error_connection(reply)
def sendUpload(row): upload = UploadList.uploads[row] upload['uploading'] = True filename = upload['name'].split('/')[-1] multiPart = QtNetwork.QHttpMultiPart( QtNetwork.QHttpMultiPart.ContentType.RelatedType) filedata = QtNetwork.QHttpPart() filedata.setHeader(QtNetwork.QNetworkRequest.ContentTypeHeader, "image/jpeg") filedata.setHeader(QtNetwork.QNetworkRequest.ContentDispositionHeader, "form-data; name=media;") file = QtCore.QFile(upload['name']) file.open(QtCore.QIODevice.ReadOnly) file.setParent(multiPart) upload['stream'] = file filedata.setBodyDevice(file) multiPart.append(filedata) upload['multiPart'] = multiPart url = QtCore.QUrl('http://127.0.0.1:8000/medias') request = QtNetwork.QNetworkRequest() request.setUrl(url) request.setRawHeader('Authorization'.encode(), ('Bearer ' + Login.token).encode()) request.setRawHeader('FILENAME'.encode(), filename.encode()) upload['manager'] = QtNetwork.QNetworkAccessManager() try: upload['reply'] = upload['manager'].post(request, upload['multiPart']) upload['manager'].setParent(upload['reply']) upload['reply'].uploadProgress.connect(updateProgress(upload, row)) except Exception as e: print(e)
def __init__(self, username): super().__init__() self.username = username self.socket = qtn.QUdpSocket() self.socket.bind(qtn.QHostAddress(qtn.QHostAddress.Any), self.port) self.socket.readyRead.connect(self.process_datagrams) self.socket.error.connect(self.on_error)
def construct_multipart(files): multiPart = QtNetwork.QHttpMultiPart(QtNetwork.QHttpMultiPart.FormDataType) for key, file in files.items(): imagePart = QtNetwork.QHttpPart() fileName = QtCore.QFileInfo(file.fileName()).fileName() imagePart.setHeader( QtNetwork.QNetworkRequest.ContentDispositionHeader, "form-data; name=\"%s\"; filename=\"%s\"" % (key, fileName)) imagePart.setBodyDevice(file) multiPart.append(imagePart) return multiPart
def __init__(self): super(Requests, self).__init__() # use qt for http requests, type has to be set to application/json self.request = QtNetwork.QNetworkRequest() self.request.setHeader(QtNetwork.QNetworkRequest.ContentTypeHeader, "application/json") self.manager = QtNetwork.QNetworkAccessManager() # grab dictionary template self.render = ReplayApiData.render self.playback = ReplayApiData.playback self.fov = ReplayApiData.fov
def __init__(self, ip, port, rip, rport, ui, parent=None): QtCore.QObject.__init__(self, parent) self.socket = QtNetwork.QUdpSocket(self) self.remoteIp = rip self.remotePort = rport if self.socket.bind(QtNetwork.QHostAddress(ip), port): ui.infoBrowser.append(f"Socket bond to UDP port {port}") else: ui.infoBrowser.append(f"Failed to bind UDP port {port}") self.socket.readyRead.connect(self.readPendingDatagrams) self.dgramCount = 0
def set_this_device(self): addresses = QtNetwork.QNetworkInterface.allAddresses() for address in addresses: if not (address.isLinkLocal() or address.isBroadcast() or address.isMulticast() or address.isLoopback() or address.protocol() == QtNetwork.QAbstractSocket.IPv6Protocol): self._ip_address = address info = QtNetwork.QHostInfo() self._name = info.localHostName() self._server = QtNetwork.QTcpServer() self._server.setSocketDescriptor(self._socket.socketDescriptor()) self._server.listen(self._ip_address, Setup().get_port()) self._server.newConnection.connect(self.receive)
def createRequest(url): url = QtCore.QUrl(url) request = QtNetwork.QNetworkRequest(url) request.setHeader(QtNetwork.QNetworkRequest.ContentTypeHeader, 'application/json') return request
def requestList(manager): url = QtCore.QUrl('http://127.0.0.1:8000/medias') request = QtNetwork.QNetworkRequest() request.setUrl(url) request.setRawHeader('Authorization'.encode(), ('Bearer ' + Login.token).encode()) manager.get(request)
def __init__(self): super().__init__() self.stage = Stage(self) self.view = QtWidgets.QGraphicsView(self.stage) self.status_bar = QtWidgets.QStatusBar(self) self.setWindowTitle('Orchstr8 Workbench') self.setCentralWidget(self.view) self.setStatusBar(self.status_bar) self.block_height = self.make_status_label('Height: -- ') self.user_balance = self.make_status_label('User Balance: -- ') self.mining_balance = self.make_status_label('Mining Balance: -- ') self.wallet_log = LoggingOutput('Wallet', self) self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.wallet_log) self.spv_log = LoggingOutput('SPV Server', self) self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.spv_log) self.blockchain_log = LoggingOutput('Blockchain', self) self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.blockchain_log) self.blockchain_controls = BlockchainControls(self) self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.blockchain_controls) self.network = QtNetwork.QNetworkAccessManager(self) self.socket = QtWebSockets.QWebSocket() self.socket.connected.connect(lambda: self.run_command('start')) self.socket.error.connect(lambda e: print(f'errored: {e}')) self.socket.textMessageReceived.connect(self.on_message) self.socket.open('ws://localhost:7954/log')
def send_broadcast(self): broadcast_addresses = self.get_broadcast_addresses() for address in broadcast_addresses: datagram = self.this_device.get_name() self._socket.writeDatagram( QtCore.QByteArray(bytes(datagram, "ascii")), QtNetwork.QHostAddress(address), 45454)
def get_updates(self): url = settings.get( SettingType.CHECK_UPDATE_URL, 'https://api.github.com/repos/juliendz/imagius/releases/latest') qurl = QtCore.QUrl(url) LOGGER.info("Checking for updates....") self._net_mgr.get(QtNetwork.QNetworkRequest(qurl))
def set_source(self, value): # Don't do anything if source is changed to the same value if not NetworkImage.NETWORK_MANAGER or value == self.__source: return if not value: return self.__source = value if self.__should_blank_on_new_source: self.__has_image = False self.has_image_changed.emit() # Cancel previous ongoing request if exists if self.__reply: self.__reply.abort() if self.__source in NetworkImage.RAM_IMAGE_CACHE: # Immediately set image to cached version if exists self.update_image(NetworkImage.RAM_IMAGE_CACHE[self.__source]) else: # If cached image doesn't exist, tell network manager to request from source self.__reply = NetworkImage.NETWORK_MANAGER.get( QtNetwork.QNetworkRequest(self.__source)) self.__reply.finished.connect(self.handle_reply)
def __init__(self, parent=None): super(Sender, self).__init__(parent) self.statusLabel = QtGui.QLabel( "Ready to broadcast datagrams on port 45454") self.startButton = QtGui.QPushButton("&Start") quitButton = QtGui.QPushButton("&Quit") buttonBox = QtGui.QDialogButtonBox() buttonBox.addButton(self.startButton, QtGui.QDialogButtonBox.ActionRole) buttonBox.addButton(quitButton, QtGui.QDialogButtonBox.RejectRole) self.timer = QtCore.QTimer(self) self.udpSocket = QtNetwork.QUdpSocket(self) self.messageNo = 1 self.startButton.clicked.connect(self.startBroadcasting) quitButton.clicked.connect(self.close) self.timer.timeout.connect(self.broadcastDatagramm) mainLayout = QtGui.QVBoxLayout() mainLayout.addWidget(self.statusLabel) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) self.setWindowTitle("Broadcast Sender")
def __init__(self, host: str, port: int, parent: Optional[QtCore.QObject] = None): """Initialise a new instance of the class.""" super().__init__(parent) self.host: str = host self.port: int = port self.__accounts: Dict[int, CompetitorAccount] = dict() self.__now: float = 0.0 self.__order_books: List[OrderBook] = list( OrderBook(i, 0.0, 0.0) for i in Instrument) self.__orders: Dict[int, Dict[int, Order]] = {0: dict()} self.__stop_later: bool = False self.__teams: Dict[int, str] = {0: ""} self.__ask_prices: List[int] = [0] * TOP_LEVEL_COUNT self.__ask_volumes: List[int] = [0] * TOP_LEVEL_COUNT self.__bid_prices: List[int] = [0] * TOP_LEVEL_COUNT self.__bid_volumes: List[int] = [0] * TOP_LEVEL_COUNT self.__socket = QtNetwork.QTcpSocket(self) self.__socket.connected.connect(self.on_connected) self.__socket.disconnected.connect(self.on_disconnected) self.__socket.errorOccurred.connect(self.on_error_occurred) self.__socket.readyRead.connect(self.on_data_received) self.__stream = QtCore.QDataStream(self.__socket)
def __init__(self, url): self.url = url self.app = QtWidgets.QApplication(sys.argv) self.timer = QtCore.QTimer(self.app) self.timer.setInterval(1000) self.timer.timeout.connect(self._tick) self.manager = QtNetwork.QNetworkAccessManager(self.app) self.request = None
def broadcastDatagramm(self): self.statusLabel.setText("Now broadcasting datagram %d" % self.messageNo) datagram = "Broadcast message %d" % self.messageNo self.udpSocket.writeDatagram( datagram, QtNetwork.QHostAddress(QtNetwork.QHostAddress.Broadcast), 45454) self.messageNo += 1
def run_command(self, command, **kwargs): request = QtNetwork.QNetworkRequest( QtCore.QUrl('http://localhost:7954/' + command)) request.setHeader(QtNetwork.QNetworkRequest.ContentTypeHeader, "application/x-www-form-urlencoded") reply = self.network.post(request, dict_to_post_data(kwargs)) # reply.finished.connect(cb) reply.error.connect(self.on_command_error)
def time_by_city(self, city: str) -> None: url = QUrl(WeatherDate.BASE_URL) query = QUrlQuery() query.addQueryItem("q", city) query.addQueryItem("appid", self.api_key) url.setQuery(query) request = QtNetwork.QNetworkRequest(url) reply: QtNetwork.QNetworkReply = self.manager.get(request) reply.finished.connect(self.tim)
def __init__(self, port, directory_tree, parent=None): super().__init__(parent) self.port = int(port) self.directory_tree = directory_tree self.server = QtNetwork.QTcpServer(self) self.server.newConnection.connect(self._handle_new_connection) self.server.acceptError.connect(self._handle_accept_error) vstreamer_utils.log_info("Initialized communication server")
def __init__(self, parent=None): QtGui.QDialog.__init__(self, parent) self.urlLineEdit = QtGui.QLineEdit( "http://www.ietf.org/iesg/1rfc_index.txt") self.urlLabel = QtGui.QLabel(self.tr("&URL:")) self.urlLabel.setBuddy(self.urlLineEdit) self.statusLabel = QtGui.QLabel( self.tr("Please enter the URL of a file " "you want to download.")) self.quitButton = QtGui.QPushButton(self.tr("Quit")) self.downloadButton = QtGui.QPushButton(self.tr("Download")) self.downloadButton.setDefault(True) self.progressDialog = QtGui.QProgressDialog(self) self.http = QtNetwork.QHttp(self) self.outFile = None self.httpGetId = 0 self.httpRequestAborted = False self.connect(self.urlLineEdit, QtCore.SIGNAL("textChanged(QString &)"), self.enableDownloadButton) self.connect(self.http, QtCore.SIGNAL("requestFinished(int, bool)"), self.httpRequestFinished) self.connect(self.http, QtCore.SIGNAL("dataReadProgress(int, int)"), self.updateDataReadProgress) self.connect( self.http, QtCore.SIGNAL("responseHeaderReceived(QHttpResponseHeader &)"), self.readResponseHeader) self.connect(self.progressDialog, QtCore.SIGNAL("canceled()"), self.cancelDownload) self.connect(self.downloadButton, QtCore.SIGNAL("clicked()"), self.downloadFile) self.connect(self.quitButton, QtCore.SIGNAL("clicked()"), self, QtCore.SLOT("close()")) topLayout = QtGui.QHBoxLayout() topLayout.addWidget(self.urlLabel) topLayout.addWidget(self.urlLineEdit) buttonLayout = QtGui.QHBoxLayout() buttonLayout.addStretch(1) buttonLayout.addWidget(self.downloadButton) buttonLayout.addWidget(self.quitButton) mainLayout = QtGui.QVBoxLayout() mainLayout.addLayout(topLayout) mainLayout.addWidget(self.statusLabel) mainLayout.addLayout(buttonLayout) self.setLayout(mainLayout) self.setWindowTitle(self.tr("HTTP")) self.urlLineEdit.setFocus()
def __init__(self): super(TclInterfaceHandler, self).__init__() self.operation = Operation.NONE self.frame_address = "00000000" self.frames = "1" self.tcpClientSocket = QtNetwork.QTcpSocket() self.tcpClientSocketStatus = SocketStatus.DISCONNECTED self.startVivado() return
def send_message(self, message, callback=None): """ Attempt to send a message to the previously running instance of the application. Returns True if the message is sent successfully, or False otherwise. Alternatively, if a callback is provided the function will return immediately and the boolean will be sent to the callback instead. """ message = json.dumps(message) message = struct.pack("!I", len(message)).decode() + message # Create a socket. sock = QtNetwork.QLocalSocket(self) # Build our helper functions. def error(*_args): """ Return False to the callback. """ callback(False) def connected(): """ Send our message. """ sock.writeData(message, len(message)) def bytesWritten(*_args): """ If we've written everything, close and return True. """ if not sock.bytesToWrite(): sock.close() callback(True) if callback: sock.error.connect(error) sock.connect.connect(connected) sock.bytesWritten.connect(bytesWritten) # Now connect. sock.connectToServer(self._app_id) if not callback: # Do things synchronously. connected = sock.waitForConnected(5000) if not connected: return False # Write it. sock.writeData(message, len(message)) # Wait until we've written everything. while sock.bytesToWrite(): success = sock.waitForBytesWritten(5000) if not success: sock.close() return False sock.close() return True
def __init__(self): self._other_devices = set() self._socket = QtNetwork.QUdpSocket() self._broadcast_port = 45454 self._socket.bind(self._broadcast_port) self._socket.readyRead.connect(self.process_broadcast) self._timer = QtCore.QTimer() self._timer.timeout.connect(self.send_broadcast) self.this_device = Device() self.this_device.set_this_device()
def metaData(self, qurl): """ Qt request a previously stored metadata for url """ DBG('DiskCache: metaData() for "{}"'.format(qurl.url())) cache_path = utils.cache_path_for_url(qurl.url()) meta = QtNetwork.QNetworkCacheMetaData() if os.path.exists(cache_path): meta.setUrl(qurl) # TODO !!!! meta.setExpirationDate(QtCore.QDateTime(2050, 1, 1, 0, 0, 0)) return meta
def __init__(self, parent=None): super(TalkMainWindow, self).__init__(parent) self.ui = Ui_TalkWindow() self.ui.setupUi(self) self.ui.connectButton.clicked.connect(self.connect) self.socket = QtNetwork.QTcpSocket(self) self.socket.readyRead.connect(self.readData) self.socket.error.connect(self.displayError) self.connectState = False
def on_accept(self): selected_item = self.table_view_receivers.selectedItems() if len(selected_item) == 0: return else: self.selected_device = Device() self.selected_device.set_name(selected_item[0].text()) self.selected_device.set_ip_address( QtNetwork.QHostAddress(selected_item[1].text())) self.accept()
def connectOrDisconnect(self): if self.ftp: self.ftp.abort() self.ftp.deleteLater() self.ftp = None self.fileList.setEnabled(False) self.cdToParentButton.setEnabled(False) self.downloadButton.setEnabled(False) self.connectButton.setEnabled(True) self.connectButton.setText("Connect") self.setCursor(QtCore.Qt.ArrowCursor) return self.setCursor(QtCore.Qt.WaitCursor) self.ftp = QtNetwork.QFtp(self) self.ftp.commandFinished.connect(self.ftpCommandFinished) self.ftp.listInfo.connect(self.addToList) self.ftp.dataTransferProgress.connect(self.updateDataTransferProgress) self.fileList.clear() self.currentPath = '' self.isDirectory.clear() url = QtCore.QUrl(self.ftpServerLineEdit.text()) if not url.isValid() or url.scheme().lower() != 'ftp': self.ftp.connectToHost(self.ftpServerLineEdit.text(), 21) self.ftp.login() else: self.ftp.connectToHost(url.host(), url.port(21)) user_name = url.userName() if user_name: try: # Python v3. user_name = bytes(user_name, encoding='latin1') except: # Python v2. pass self.ftp.login(QtCore.QUrl.fromPercentEncoding(user_name), url.password()) else: self.ftp.login() if url.path(): self.ftp.cd(url.path()) self.fileList.setEnabled(True) self.connectButton.setEnabled(False) self.connectButton.setText("Disconnect") self.statusLabel.setText("Connecting to FTP server %s..." % self.ftpServerLineEdit.text())
def __init__(self): super().__init__() self.counting_iterator = itertools.count() self.queue = queue.Queue() self.__last_started_index = 0 self.__abort_when_found: List[int] = [] self.replies: Dict[int, QtNetwork.QNetworkReply] = {} self.file_buffers = {} # We support an arbitrary number of threads using synchronous GET calls: self.synchronous_lock = threading.Lock() self.synchronous_complete: Dict[int, bool] = {} self.synchronous_result_data: Dict[int, QtCore.QByteArray] = {} # Make sure we exit nicely on quit if QtCore.QCoreApplication.instance() is not None: QtCore.QCoreApplication.instance().aboutToQuit.connect( self.__aboutToQuit) # Create the QNAM on this thread: self.QNAM = QtNetwork.QNetworkAccessManager() self.QNAM.proxyAuthenticationRequired.connect( self.__authenticate_proxy) self.QNAM.authenticationRequired.connect( self.__authenticate_resource) qnam_cache = QtCore.QStandardPaths.writableLocation( QtCore.QStandardPaths.CacheLocation) os.makedirs(qnam_cache, exist_ok=True) self.diskCache = QtNetwork.QNetworkDiskCache() self.diskCache.setCacheDirectory(qnam_cache) self.QNAM.setCache(self.diskCache) self.monitored_connections: List[int] = [] self._setup_proxy() # A helper connection for our blocking interface self.completed.connect(self.__synchronous_process_completion) # Set up our worker connection self.__request_queued.connect(self.__setup_network_request)