def CreateRequest(search_string, batch_size, page): # url = "http://doi.org/" + search_string url = "https://api.crossref.org/works/" + search_string + "/transform/application/x-bibtex" request = QNetworkRequest(QUrl(url)) request.setRawHeader(b"Accept", b"application/x-bibtex") return request
def ask_login_status(self): app_setting_file = os.path.join(BASE_DIR, "classini/app.ini") app_settings = QSettings(app_setting_file, QSettings.IniFormat) token = "Bearer " + app_settings.value("TOKEN/token") print(token) app = QApplication.instance() network_manager = getattr(app, "_network") url = SERVER + "token_login/" request = QNetworkRequest(QUrl(url)) request.setRawHeader("Authorization".encode("utf-8"), token.encode("utf-8")) reply = network_manager.get(request) reply.finished.connect(self.is_logged_reply)
def build_initial_request_list(self): # The initial request is a custom job. url = QUrl(self.camera_description.location) request = QNetworkRequest(url) request.setRawHeader(QByteArray(b"User-Agent"), QByteArray(b"Panasonic Android/1 DM-CP")) self.initial_requests.put(request) r = self.build_request({ "mode": "accctrl", "type": "req_acc", "value": "4D454930-0100-1000-8000-D453835D5F48", "value2": "LG-SP320" }) self.initial_requests.put(r) r = self.build_request({"mode": "getinfo", "type": "capability"}) self.initial_requests.put(r) r = self.build_request({"mode": "getinfo", "type": "allmenu"}) self.initial_requests.put(r) r = self.build_request({"mode": "getinfo", "type": "curmenu"}) self.initial_requests.put(r)
def prepareRequest(self): request = QNetworkRequest() request.setUrl(self.urlServer) request.setRawHeader(QByteArray(b"content-type"), QByteArray(b"application/json")) request.setRawHeader(QByteArray(b"charset"), QByteArray(b"utf-8")) if self.mpid != "open@": tokenStr = self.usuario + ":" + str(int( self.token[0])) + ":" + str( self.token[1]) if self.token != [] else "" tokenByte = QByteArray(tokenStr.encode()) tokenByteComplete = QByteArray(b"Session ") + tokenByte.toBase64() request.setRawHeader(QByteArray(b"authorization"), tokenByteComplete) return request
class CameraController: PING_RATE_MS = 1000 STATUS_MAP = { "Battery": "./state/batt", "Mode": "./state/cammode", "Remaining Capacity": "./state/remaincapacity", "Wifi Strength": "./state/wifiradio", "Temperature": "./state/temperature" } def __init__(self, main_controller: "MainController", camera_description: CamDesc, mdi_area: QtWidgets.QMdiArea): self.main_controller = main_controller self.camera_description = camera_description self.address_str = camera_description.host.toString() self.sub_window = sub_window = MdiSubWindowCloser() sub_window.setWindowTitle(self.address_str) sub_window.setAttribute(Qt.WA_DeleteOnClose) sub_window.closed.connect(self.window_closed) camera_control = CameraControl(parent=sub_window) self.status = camera_control.status for cmd in ZOOM_COMMANDS: control = getattr(camera_control, cmd) cmd_name = cmd.replace("_", "-") control.pressed.connect( partial(self.zoom_command_pressed, cmd_name)) control.released.connect(self.zoom_command_released) sub_window.setWidget(camera_control) mdi_area.addSubWindow(sub_window) sub_window.show() self.base_url = QUrl(f"http://{self.address_str}/cam.cgi") self.base_request = QNetworkRequest() self.base_request.setRawHeader(QByteArray(b"Connection"), QByteArray(b"Keep-Alive")) self.base_request.setRawHeader(QByteArray(b"User-Agent"), QByteArray(b"Apache-HttpClient")) self.status_query_request = self.build_request({"mode": "getstate"}) self.stop_zoom_request = self.build_request({ "mode": "camcmd", "value": "zoomstop" }) self.ping_timer = QTimer(self.sub_window) self.ping_timer.timeout.connect(self.request_device_state) self.initial_requests = Queue() self.build_initial_request_list() request = self.get_next_request() self.query(request) def query(self, request: QNetworkRequest, ping_count=0, next_request=True, close_on_fail=True): reply = self.main_controller.network_access_manager.get(request) reply.finished.connect(lambda: self.query_response( reply, request, ping_count, next_request, close_on_fail)) def query_response(self, reply: QNetworkReply, original_request, ping_count, next_request, close_on_fail): if reply.error() != QNetworkReply.NoError: print(f"Error query response: {reply.errorString()}") if ping_count < 2: print(f"Failed {ping_count+1} times. Trying again.") self.query(original_request, ping_count + 1) else: print(f"Failed {ping_count} times. Giving up.") if close_on_fail: self.sub_window.close() next_request = False reply.deleteLater() if not next_request: return request = self.get_next_request() if request is not None: self.query(request) else: self.ping_timer.start(CameraController.PING_RATE_MS) def build_request(self, query_items): query = QUrlQuery() for k, v in query_items.items(): query.addQueryItem(k, v) url = QUrl(self.base_url) url.setQuery(query) request = QNetworkRequest(self.base_request) request.setUrl(url) return request def build_initial_request_list(self): # The initial request is a custom job. url = QUrl(self.camera_description.location) request = QNetworkRequest(url) request.setRawHeader(QByteArray(b"User-Agent"), QByteArray(b"Panasonic Android/1 DM-CP")) self.initial_requests.put(request) r = self.build_request({ "mode": "accctrl", "type": "req_acc", "value": "4D454930-0100-1000-8000-D453835D5F48", "value2": "LG-SP320" }) self.initial_requests.put(r) r = self.build_request({"mode": "getinfo", "type": "capability"}) self.initial_requests.put(r) r = self.build_request({"mode": "getinfo", "type": "allmenu"}) self.initial_requests.put(r) r = self.build_request({"mode": "getinfo", "type": "curmenu"}) self.initial_requests.put(r) def get_next_request(self): request = None with contextlib.suppress(Empty): request = self.initial_requests.get_nowait() return request def zoom_command_pressed(self, cmd): print(f"Executing {cmd}") r = self.build_request({"mode": "camcmd", "value": cmd}) self.query(r, next_request=False, close_on_fail=False) def zoom_command_released(self): print(f"Stopping Zoom") self.query(self.stop_zoom_request, next_request=False, close_on_fail=False) def window_closed(self): print("Window closed") self.main_controller.controller_closed(self.address_str) def request_device_state(self): reply = self.main_controller.network_access_manager.get( self.status_query_request) reply.finished.connect( lambda: self.handle_device_state_response(reply)) def handle_device_state_response(self, reply: QNetworkReply): if reply.error() != QNetworkReply.NoError: print(f"Error device state response: {reply.errorString()}") self.status.setText(reply.errorString()) else: self.status.clear() data = reply.readAll() root = ET.fromstring(data) result_list = [] for label, path in CameraController.STATUS_MAP.items(): r = root.findall(path) result = "ERROR" if len(r) > 0: result = r[0].text result_list.append(f"{label}: {result}") self.status.setText("\n".join(result_list)) reply.deleteLater()
def open( self, address, method='get', headers={}, auth=None, body=None, default_popup_response=None, wait=True, timeout=None, encode_url=True, user_agent=None, ): """Opens a web page. :param address: The resource URL. :param method: The Http method. :param headers: An optional dict of extra request headers. :param auth: An optional tuple of HTTP auth (username, password). :param body: An optional string containing a payload. :param default_popup_response: the default response for any confirm/ alert/prompt popup from the Javascript (replaces the need for the with blocks) :param wait: If set to True (which is the default), this method call waits for the page load to complete before returning. Otherwise, it just starts the page load task and it is the caller's responsibilty to wait for the load to finish by other means (e.g. by calling wait_for_page_loaded()). :param timeout: An optional timeout. "key_path" both paths corresponding to the certificate and key files :param encode_url Set to true if the url have to be encoded :param user_agent An option user agent string. :return: Page resource, and all loaded resources, unless wait is False, in which case it returns None. """ self.logger.info('Opening %s', address) body = body or QByteArray() try: method = getattr(QNetworkAccessManager, "%sOperation" % method.capitalize()) except AttributeError: raise Error("Invalid http method %s" % method) if user_agent is not None: self.page.set_user_agent(user_agent) if encode_url: request = QNetworkRequest(QUrl(address)) else: request = QNetworkRequest(QUrl.fromEncoded(address)) request.CacheLoadControl(0) for header in headers: request.setRawHeader(header, headers[header]) self._auth = auth self._auth_attempt = 0 # Avoids reccursion self.main_frame.load(request, method, body) self.loaded = False if default_popup_response is not None: self._prompt_expected = default_popup_response self._confirm_expected = default_popup_response if wait: return self.wait_for_page_loaded(timeout=timeout)
class SlippyMap(QObject): updated = Signal(QRect) def __init__(self, parent=None): """ :param parent: """ super(SlippyMap, self).__init__(parent) self._offset = QPoint() self._tiles_rectangle = QRect() self._tile_pixmaps = {} # Point(x, y) to QPixmap mapping self._manager = QNetworkAccessManager() self._url = QUrl() # public vars self.width = 400 self.height = 300 self.zoom = 4 self.latitude = 59.9138204 self.longitude = 10.7387413 self._emptyTile = QPixmap(TDIM, TDIM) self._emptyTile.fill(Qt.lightGray) self.request = QNetworkRequest() self.cache = QNetworkDiskCache() self.cache.setCacheDirectory( QStandardPaths.writableLocation(QStandardPaths.CacheLocation)) self._manager.setCache(self.cache) self._manager.finished.connect(self.handle_network_data) def invalidate(self): """ :return: """ if self.width <= 0 or self.height <= 0: return ct = tile_for_coordinate(self.latitude, self.longitude, self.zoom) tx = ct.x() ty = ct.y() # top-left corner of the center tile xp = int(self.width / 2 - (tx - math.floor(tx)) * TDIM) yp = int(self.height / 2 - (ty - math.floor(ty)) * TDIM) # first tile vertical and horizontal xa = (xp + TDIM - 1) / TDIM ya = (yp + TDIM - 1) / TDIM xs = int(tx) - xa ys = int(ty) - ya # offset for top-left tile self._offset = QPoint(int(xp - xa * TDIM), int(yp - ya * TDIM)) # last tile vertical and horizontal xe = int(tx) + (self.width - xp - 1) / TDIM ye = int(ty) + (self.height - yp - 1) / TDIM # build a rect self._tiles_rectangle = QRect(int(xs), int(ys), int(xe - xs + 1), int(ye - ys + 1)) if self._url.isEmpty(): self.download() self.updated.emit(QRect(0, 0, self.width, self.height)) def render(self, p: QPainter, rect: QRect): """ Render a tile :param p: QPainter instance, place where to pain the tiles :param rect: QRect instance, dimensions of the painter (the window that renders the tiles) :return: Nothing """ rx = range(self._tiles_rectangle.width()) ry = range(self._tiles_rectangle.height()) for x, y in product(rx, ry): tp = Point(x + self._tiles_rectangle.left(), y + self._tiles_rectangle.top()) box = self.tile_rectangle(tp) if rect.intersects(box): p.drawPixmap(box, self._tile_pixmaps.get(tp, self._emptyTile)) def pan(self, delta: QPoint): """ Move the map :param delta: x, y delta as a QPoint instance :return: Nothing """ dx = QPointF(delta) / float(TDIM) center = tile_for_coordinate(self.latitude, self.longitude, self.zoom) - dx self.latitude = latitude_from_tile(center.y(), self.zoom) self.longitude = longitude_from_tile(center.x(), self.zoom) self.invalidate() # slots def handle_network_data(self, reply: QNetworkReply): """ This function is called automatically by a QNetworkAccessManager object (self._manager) :param reply: QNetworkReply instance :return: Nothing """ img = QImage() tp = Point(reply.request().attribute(QNetworkRequest.User)) url = reply.url() if not reply.error(): # if there was no url error... if img.load(reply, None): # if the image loading went well... self._tile_pixmaps[tp] = QPixmap.fromImage( img) # store the image in the tiles dictionary reply.deleteLater() self.updated.emit(self.tile_rectangle(tp)) # purge unused tiles bound = self._tiles_rectangle.adjusted(-2, -2, 2, 2) for tp in list(self._tile_pixmaps.keys()): if not bound.contains(tp): del self._tile_pixmaps[tp] self.download() def download(self): """ Download tile :return: Nothing """ grab = None rx = range(self._tiles_rectangle.width()) ry = range(self._tiles_rectangle.height()) for x, y in product(rx, ry): tp = Point(self._tiles_rectangle.topLeft() + QPoint(x, y)) if tp not in self._tile_pixmaps: grab = QPoint(tp) break if grab is None: self._url = QUrl() return path = 'http://tile.openstreetmap.org/%d/%d/%d.png' % ( self.zoom, grab.x(), grab.y()) self._url = QUrl(path) self.request = QNetworkRequest() self.request.setUrl(self._url) self.request.setRawHeader(b'User-Agent', b'Nokia (PyQt) Graphics Dojo 1.0') self.request.setAttribute(QNetworkRequest.User, grab) self._manager.get(self.request) print('downloading z:', self.zoom, 'x:', grab.x(), 'y:', grab.y()) def tile_rectangle(self, tp: Point): """ Get tile rectangle :param tp: Tile point :return: QRect instance """ t = tp - self._tiles_rectangle.topLeft() x = t.x() * TDIM + self._offset.x() y = t.y() * TDIM + self._offset.y() return QRect(x, y, TDIM, TDIM)
class SlippyMap(QObject): updated = Signal(QRect) def __init__(self, parent=None): super(SlippyMap, self).__init__(parent) self._offset = QPoint() self._tilesRect = QRect() self._tilePixmaps = {} # Point(x, y) to QPixmap mapping self._manager = QNetworkAccessManager() self._url = QUrl() # public vars self.width = 400 self.height = 300 self.zoom = 15 self.latitude = 59.9138204 self.longitude = 10.7387413 self._emptyTile = QPixmap(TDIM, TDIM) self._emptyTile.fill(Qt.lightGray) self.request = QNetworkRequest() self.cache = QNetworkDiskCache() self.cache.setCacheDirectory( QStandardPaths.writableLocation(QStandardPaths.CacheLocation)) self._manager.setCache(self.cache) self._manager.finished.connect(self.handleNetworkData) def invalidate(self): if self.width <= 0 or self.height <= 0: return ct = tileForCoordinate(self.latitude, self.longitude, self.zoom) tx = ct.x() ty = ct.y() # top-left corner of the center tile xp = int(self.width / 2 - (tx - math.floor(tx)) * TDIM) yp = int(self.height / 2 - (ty - math.floor(ty)) * TDIM) # first tile vertical and horizontal xa = (xp + TDIM - 1) / TDIM ya = (yp + TDIM - 1) / TDIM xs = int(tx) - xa ys = int(ty) - ya # offset for top-left tile self._offset = QPoint(xp - xa * TDIM, yp - ya * TDIM) # last tile vertical and horizontal xe = int(tx) + (self.width - xp - 1) / TDIM ye = int(ty) + (self.height - yp - 1) / TDIM # build a rect self._tilesRect = QRect(xs, ys, xe - xs + 1, ye - ys + 1) if self._url.isEmpty(): self.download() self.updated.emit(QRect(0, 0, self.width, self.height)) def render(self, p, rect): for x in range(self._tilesRect.width()): for y in range(self._tilesRect.height()): tp = Point(x + self._tilesRect.left(), y + self._tilesRect.top()) box = self.tileRect(tp) if rect.intersects(box): p.drawPixmap(box, self._tilePixmaps.get(tp, self._emptyTile)) def pan(self, delta): dx = QPointF(delta) / float(TDIM) center = tileForCoordinate(self.latitude, self.longitude, self.zoom) - dx self.latitude = latitudeFromTile(center.y(), self.zoom) self.longitude = longitudeFromTile(center.x(), self.zoom) self.invalidate() # slots def handleNetworkData(self, reply): img = QImage() tp = Point(reply.request().attribute(QNetworkRequest.User)) url = reply.url() if not reply.error(): if img.load(reply, None): self._tilePixmaps[tp] = QPixmap.fromImage(img) reply.deleteLater() self.updated.emit(self.tileRect(tp)) # purge unused tiles bound = self._tilesRect.adjusted(-2, -2, 2, 2) for tp in list(self._tilePixmaps.keys()): if not bound.contains(tp): del self._tilePixmaps[tp] self.download() def download(self): grab = None for x in range(self._tilesRect.width()): for y in range(self._tilesRect.height()): tp = Point(self._tilesRect.topLeft() + QPoint(x, y)) if tp not in self._tilePixmaps: grab = QPoint(tp) break if grab is None: self._url = QUrl() return path = 'http://tile.openstreetmap.org/%d/%d/%d.png' % ( self.zoom, grab.x(), grab.y()) self._url = QUrl(path) self.request = QNetworkRequest() self.request.setUrl(self._url) self.request.setRawHeader(b'User-Agent', b'Nokia (PyQt) Graphics Dojo 1.0') self.request.setAttribute(QNetworkRequest.User, grab) self._manager.get(self.request) def tileRect(self, tp): t = tp - self._tilesRect.topLeft() x = t.x() * TDIM + self._offset.x() y = t.y() * TDIM + self._offset.y() return QRect(x, y, TDIM, TDIM)