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 __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 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): 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 __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 __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, parent, root_path: str = './downloads', *args, **kwargs): super(_Downloader, self).__init__(parent, *args, **kwargs) self._manager = QtNetwork.QNetworkAccessManager(parent) self.root_path = Path(root_path) self._page_downloaded_dict = defaultdict(int) self._total_page_dict = {} self._called_download_manga_chapter = False self._processing_idrs = 0 self._pending_q = Queue() self.download_complete.connect(self._consume_pending_idr)
def __init__(self): super().__init__() #self.uploader = main.Uploader() #self.uploader.response.connect(self.updateTable) self.sig_updateList.connect(self.updateList) self.manager = QtNetwork.QNetworkAccessManager() self.manager.finished.connect(main.getList(self.sig_updateList)) self.text_medias = QtWidgets.QLabel("Files list:") self.text_upload = QtWidgets.QLabel("Upload list:") self.text_medias.setAlignment(QtCore.Qt.AlignCenter) self.container = QtWidgets.QVBoxLayout() self.titles = QtWidgets.QHBoxLayout() self.titles.addWidget(self.text_medias, 1, QtCore.Qt.AlignLeft) self.titles.addWidget(self.text_upload, 2) self.container.addLayout(self.titles) self.list_medias = QtWidgets.QListWidget() self.table_upload = QtWidgets.QTableWidget() self.table_upload.setColumnCount(5) self.table_upload.setHorizontalHeaderLabels( ['Name', 'Size', 'Progress', 'Estimated', 'Option']) self.lists = QtWidgets.QHBoxLayout() self.lists.addWidget(self.list_medias, 1, QtCore.Qt.AlignLeft) self.upload = QtWidgets.QVBoxLayout() self.upload.addWidget(self.table_upload) self.button_find = QtWidgets.QPushButton("Search File") self.button_find.clicked.connect(self.findFile) self.upload.addWidget(self.button_find) self.lists.addLayout(self.upload, 2) self.container.addLayout(self.lists) self.setLayout(self.container) main.requestList(self.manager) self.updateTable()
def __init__(self, parent=None): super(SendUpdateTab, self).__init__(parent=parent) main_layout = QtWidgets.QVBoxLayout(self) main_layout.setAlignment(QtCore.Qt.AlignTop) main_layout.setContentsMargins(0, 0, 0, 0) main_layout.setSpacing(0) form_layout = QtWidgets.QFormLayout() main_layout.addLayout(form_layout) self.channelNameField = QtWidgets.QLineEdit() form_layout.addRow('Channel Name:', self.channelNameField) self.assetNameField = QtWidgets.QLineEdit() form_layout.addRow('Asset Name:', self.assetNameField) notesLabel = QtWidgets.QLabel('Notes:') main_layout.addWidget(notesLabel) self.notesList = QtWidgets.QListWidget() main_layout.addWidget(self.notesList) self.notesList.doubleClicked.connect(self.loadSelectedNote) self.addNoteField = QtWidgets.QLineEdit() main_layout.addWidget(self.addNoteField) self.addNoteField.returnPressed.connect(self.addNewNote) h_layout = QtWidgets.QHBoxLayout() main_layout.addLayout(h_layout) self.attachFileButton = QtWidgets.QPushButton('Attach File') h_layout.addWidget(self.attachFileButton) self.uploadFilePath = QtWidgets.QLabel() h_layout.addWidget(self.uploadFilePath) self.button = QtWidgets.QPushButton('Send') self.button.clicked.connect(self.post) main_layout.addWidget(self.button) self.http = QtNetwork.QNetworkAccessManager() self.http.finished.connect(self.logResponse) self.response = None
def __init__(self) -> None: QtCore.QObject.__init__(self) # Initialize helper classes self.lastfm = LastfmApiWrapper() self.spotify_api = SpotifyApiWrapper() self.art_provider = ArtProvider(self.lastfm, self.spotify_api) self.is_logged_in = False self.is_offline = False # Store whether the app is in mini mode self.__is_in_mini_mode: bool = None # Create network request manager and expose it to all NetworkImage instances self.network_manager = QtNetwork.QNetworkAccessManager() NetworkImage.NETWORK_MANAGER = self.network_manager # Connect to SQLite db_helper.connect()
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)
def __init__(self, parent=None): super(RequestFeedbackTab, self).__init__(parent=parent) main_layout = QtWidgets.QVBoxLayout(self) main_layout.setAlignment(QtCore.Qt.AlignTop) main_layout.setContentsMargins(0, 0, 0, 0) main_layout.setSpacing(0) form_layout = QtWidgets.QFormLayout() main_layout.addLayout(form_layout) self.channelNameField = QtWidgets.QLineEdit() form_layout.addRow('Channel Name:', self.channelNameField) self.askQuestionField = QtWidgets.QLineEdit() form_layout.addRow('Ask:', self.askQuestionField) optionsLabel = QtWidgets.QLabel('Feedback:') main_layout.addWidget(optionsLabel) self.feedbackList = QtWidgets.QListWidget() main_layout.addWidget(self.feedbackList) h_layout = QtWidgets.QHBoxLayout() main_layout.addLayout(h_layout) self.attachFileButton = QtWidgets.QPushButton('Attach File') h_layout.addWidget(self.attachFileButton) self.uploadFilePath = QtWidgets.QLabel() h_layout.addWidget(self.uploadFilePath) self.button = QtWidgets.QPushButton('Send') self.button.clicked.connect(self.post) main_layout.addWidget(self.button) self.http = QtNetwork.QNetworkAccessManager() self.http.finished.connect(self.logResponse) self.response = None
def run(self): """Do not call directly: use start() to begin the event loop on a new thread.""" # Create the QNAM on this thread: self.thread = QtCore.QThread.currentThread() self.QNAM = QtNetwork.QNetworkAccessManager() self.QNAM.proxyAuthenticationRequired.connect( self.__authenticate_proxy) self.QNAM.authenticationRequired.connect( self.__authenticate_resource) # A helper connection for our blocking interface self.completed.connect(self.__synchronous_process_completion) # Set up the proxy, if necesssary: noProxyCheck = True systemProxyCheck = False userProxyCheck = False proxy_string = "" if HAVE_FREECAD: pref = FreeCAD.ParamGet( "User parameter:BaseApp/Preferences/Addons") noProxyCheck = pref.GetBool("NoProxyCheck", noProxyCheck) systemProxyCheck = pref.GetBool("SystemProxyCheck", systemProxyCheck) userProxyCheck = pref.GetBool("UserProxyCheck", userProxyCheck) proxy_string = pref.GetString("ProxyUrl", "") else: print("Please select a proxy type:") print("1) No proxy") print("2) Use system proxy settings") print("3) Custom proxy settings") result = input("Choice: ") if result == "1": pass elif result == "2": noProxyCheck = False systemProxyCheck = True elif result == "3": noProxyCheck = False userProxyCheck = True proxy_string = input( "Enter your proxy server (host:port): ") else: print(f"Got {result}, expected 1, 2, or 3.") app.quit() if noProxyCheck: pass elif systemProxyCheck: query = QtNetwork.QNetworkProxyQuery( QtCore.QUrl("https://github.com/FreeCAD/FreeCAD")) proxy = QtNetwork.QNetworkProxyFactory.systemProxyForQuery( query) if proxy and proxy[0]: self.QNAM.setProxy( proxy[0]) # This may still be QNetworkProxy.NoProxy elif userProxyCheck: host, _, port_string = proxy_string.rpartition(":") port = 0 if not port_string else int(port_string) # For now assume an HttpProxy, but eventually this should be a parameter proxy = QtNetwork.QNetworkProxy( QtNetwork.QNetworkProxy.HttpProxy, host, port) self.QNAM.setProxy(proxy) qnam_cache = QtCore.QStandardPaths.writableLocation( QtCore.QStandardPaths.CacheLocation) os.makedirs(qnam_cache, exist_ok=True) diskCache = QtNetwork.QNetworkDiskCache() diskCache.setCacheDirectory(qnam_cache) self.QNAM.setCache(diskCache) # Start an event loop while True: if QtCore.QThread.currentThread().isInterruptionRequested(): # Support shutting down the entire thread, but this should be very rarely used. # Callers should generally just call abort() on each network call they want to # terminate, using requestInterruption() will terminate ALL network requests. if not HAVE_FREECAD: print("Shutting down all active network requests...", flush=True) self.abort_all() self.queue.join() if not HAVE_FREECAD: print("All requests terminated.", flush=True) return try: item = self.queue.get_nowait() if item: if item.index in self.__abort_when_found: self.__abort_when_found.remove(item.index) continue # Do not do anything with this item, it's been aborted... reply = self.QNAM.get(item.request) self.__last_started_index = item.index reply.finished.connect( lambda i=item: self.__reply_finished(i)) reply.redirected.connect( lambda url, r=reply: self.__on_redirect(r, url)) reply.sslErrors.connect(self.__on_ssl_error) if item.track_progress: reply.readyRead.connect( lambda i=item.index: self.__data_incoming(i)) reply.downloadProgress.connect( lambda a, b, i=item.index: self.progress_made. emit(i, a, b)) self.replies[item.index] = reply except queue.Empty: pass QtCore.QCoreApplication.processEvents()
def manager(self) -> QtNetwork.QNetworkAccessManager: return QtNetwork.QNetworkAccessManager(self)
def create(self, parent: QtCore.QObject): nam = QtNetwork.QNetworkAccessManager() disk_cache = QMLNetworkDiskCache(nam) nam.setCache(disk_cache) return nam
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 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) # Set up the proxy, if necesssary: noProxyCheck = True systemProxyCheck = False userProxyCheck = False proxy_string = "" if HAVE_FREECAD: pref = FreeCAD.ParamGet( "User parameter:BaseApp/Preferences/Addons") noProxyCheck = pref.GetBool("NoProxyCheck", noProxyCheck) systemProxyCheck = pref.GetBool("SystemProxyCheck", systemProxyCheck) userProxyCheck = pref.GetBool("UserProxyCheck", userProxyCheck) proxy_string = pref.GetString("ProxyUrl", "") # Add some error checking to the proxy setup, since for historical reasons they # are indepdendent booleans, rather than an enumeration: count = [noProxyCheck, systemProxyCheck, userProxyCheck].count(True) if count != 1: FreeCAD.Console.PrintWarning( translate( "AddonsInstaller", "Parameter error: mutually exclusive proxy options set. Resetting to default.", ) + "\n") noProxyCheck = True systemProxyCheck = False userProxyCheck = False pref.SetBool("NoProxyCheck", noProxyCheck) pref.SetBool("SystemProxyCheck", systemProxyCheck) pref.SetBool("UserProxyCheck", userProxyCheck) if userProxyCheck and not proxy_string: FreeCAD.Console.PrintWarning( translate( "AddonsInstaller", "Parameter error: user proxy indicated, but no proxy provided. Resetting to default.", ) + "\n") noProxyCheck = True userProxyCheck = False pref.SetBool("NoProxyCheck", noProxyCheck) pref.SetBool("UserProxyCheck", userProxyCheck) else: print("Please select a proxy type:") print("1) No proxy") print("2) Use system proxy settings") print("3) Custom proxy settings") result = input("Choice: ") if result == "1": pass elif result == "2": noProxyCheck = False systemProxyCheck = True elif result == "3": noProxyCheck = False userProxyCheck = True proxy_string = input( "Enter your proxy server (host:port): ") else: print(f"Got {result}, expected 1, 2, or 3.") app.quit() if noProxyCheck: pass elif systemProxyCheck: query = QtNetwork.QNetworkProxyQuery( QtCore.QUrl("https://github.com/FreeCAD/FreeCAD")) proxy = QtNetwork.QNetworkProxyFactory.systemProxyForQuery( query) if proxy and proxy[0]: self.QNAM.setProxy( proxy[0]) # This may still be QNetworkProxy.NoProxy elif userProxyCheck: host, _, port_string = proxy_string.rpartition(":") port = 0 if not port_string else int(port_string) # For now assume an HttpProxy, but eventually this should be a parameter proxy = QtNetwork.QNetworkProxy( QtNetwork.QNetworkProxy.HttpProxy, host, port) self.QNAM.setProxy(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)
def __init__(self): super(UpdateManager, self).__init__() self._net_mgr = QtNetwork.QNetworkAccessManager(self) self._net_mgr.finished.connect(self._request_finished)