def __getReply(self, params): url = QUrl('http://ws.audioscrobbler.com/2.0/') url.addQueryItem('api_key', self.__last_fm_key) for key, value in params.iteritems(): url.addQueryItem(key, value) request = QNetworkRequest(url) return self.__networkManager.get(request)
def query(self, query): """ Perform a nominatim query @param query: Query to execute @type query: str @raise NetWorkErrorException @return: the result of the query @rtype: str """ url_query = QUrl(self.__url) query = QUrl.toPercentEncoding(query) url_query.addEncodedQueryItem('q', query) url_query.addQueryItem('info', 'QgisQuickOSMPlugin') request = QNetworkRequest(url_query) request.setRawHeader("User-Agent", "QuickOSM") self.network_reply = self.network.get(request) self.loop = QEventLoop() self.network.finished.connect(self._end_of_request) self.loop.exec_() if self.network_reply.error() == QNetworkReply.NoError: return json.loads(self.data) else: raise NetWorkErrorException(suffix="Nominatim API")
def __init__(self, parent=None): QDialog.__init__(self, parent) self.setupUi(self) # self.title.setText( name() + version() ) # self.description.setText( description() ) text = self.txt.toHtml() text = text.replace("$PLUGIN_NAME$", name()) text = text.replace("$PLUGIN_VERSION$", version()) subject = "Help: %s" % name() body = """\n\n -------- Plugin name: %s Plugin version: %s Python version: %s Platform: %s - %s -------- """ % (name(), version(), platform.python_version(), platform.system(), platform.version()) mail = QUrl("mailto:[email protected]") mail.addQueryItem("subject", subject) mail.addQueryItem("body", body) text = text.replace("$MAIL_SUBJECT$", unicode(mail.encodedQueryItemValue("subject"))) text = text.replace("$MAIL_BODY$", unicode(mail.encodedQueryItemValue("body"))) self.txt.setHtml(text)
def __init__(self, parent=None): QDialog.__init__(self, parent) self.setupUi(self) # self.title.setText( name() + version() ) # self.description.setText( description() ) text = self.txt.toHtml() text = text.replace("$PLUGIN_NAME$", name()) text = text.replace("$PLUGIN_VERSION$", version()) subject = "Help: %s" % name() body = """\n\n -------- Plugin name: %s Plugin version: %s Python version: %s Platform: %s - %s -------- """ % (name(), version(), platform.python_version(), platform.system(), platform.version()) mail = QUrl("mailto:[email protected]") mail.addQueryItem("subject", subject) mail.addQueryItem("body", body) text = text.replace("$MAIL_SUBJECT$", unicode(mail.encodedQueryItemValue("subject"))) text = text.replace("$MAIL_BODY$", unicode(mail.encodedQueryItemValue("body"))) self.txt.setHtml(text)
def exchange_authorization_code(self, authorization_code, scopes, callback): log.debug( "OAuth: exchanging authorization_code %s for an access_token", authorization_code) host, port = config.setting['server_host'], config.setting[ 'server_port'] path = "/oauth2/token" url = QUrl() url.addQueryItem("grant_type", "authorization_code") url.addQueryItem("code", authorization_code) url.addQueryItem("client_id", MUSICBRAINZ_OAUTH_CLIENT_ID) url.addQueryItem("client_secret", MUSICBRAINZ_OAUTH_CLIENT_SECRET) url.addQueryItem("redirect_uri", "urn:ietf:wg:oauth:2.0:oob") data = str(url.encodedQuery()) self.xmlws.post(host, port, path, data, partial(self.on_exchange_authorization_code_finished, scopes, callback), xml=False, mblogin=True, priority=True, important=True)
def query(self, query): """ Perform a nominatim query @param query: Query to execute @type query: str @raise NetWorkErrorException @return: the result of the query @rtype: str """ url_query = QUrl(self.__url) query = QUrl.toPercentEncoding(query) url_query.addEncodedQueryItem('q', query) url_query.addQueryItem('info', 'QgisQuickOSMPlugin') url_query.setPort(80) proxy = get_proxy() if proxy: self.network.setProxy(proxy) request = QNetworkRequest(url_query) request.setRawHeader("User-Agent", "QuickOSM") self.network_reply = self.network.get(request) self.loop = QEventLoop() self.network.finished.connect(self._end_of_request) self.loop.exec_() if self.network_reply.error() == QNetworkReply.NoError: return json.loads(self.data) else: raise NetWorkErrorException(suffix="Nominatim API")
def load_account_page(self, account, tab=None, task=None): self.tab = tab self.task = task self.account = account url = QUrl(account.server.settings_url) for name, value in self.query_items: url.addQueryItem(name, value) self.load(url)
def email(subject, body): """Opens the e-mail composer with the given subject and body, with version information added to it.""" subject = "[{0} {1}] {2}".format(appinfo.appname, appinfo.version, subject) body = "{0}\n\n{1}\n\n".format(debuginfo.version_info_string(' -- '), body) url = QUrl("mailto:" + appinfo.maintainer_email) url.addQueryItem("subject", subject) url.addQueryItem("body", body) helpers.openUrl(url, "email")
def email(subject, body): """Opens the e-mail composer with the given subject and body, with version information added to it.""" subject = "[{0} {1}] {2}".format(appinfo.appname, appinfo.version, subject) body = "{0}\n\n{1}\n\n".format(debuginfo.version_info_string(' -- '), body) url = QUrl("mailto:" + appinfo.maintainer_email) url.addQueryItem("subject", subject) url.addQueryItem("body", body) helpers.openUrl(url, "email")
def load_account_page(self, account, tab=None, task=None): self.tab = tab self.task = task self.account = account url = QUrl(account.server.settings_url) for name, value in self.query_items: url.addQueryItem(name, value) self.load(url)
def _sendRequest(self, url, params): if self.asynchonous: url = QUrl(url) for key, value in params.iteritems(): url.addQueryItem(key, value) request = QNetworkRequest(url) self.reply = self.manager.get(request) else: response = urllib2.urlopen(self.url + '?' + urllib.urlencode(params)) data = json.load(response) self.loadData(data)
def query(self, query): """ Make a query to the overpass @param query:Query to execute @type query:str @raise OverpassBadRequestException,NetWorkErrorException, OverpassTimeoutException @return: the result of the query @rtype: str """ url_query = QUrl(self.__url + 'interpreter') # The output format can be forced (JSON or XML) if self.__output: query = re.sub( r'output="[a-z]*"', 'output="' + self.__output + '"', query) query = re.sub( r'\[out:[a-z]*', '[out:' + self.__output, query) # noinspection PyCallByClass encoded_query = QUrl.toPercentEncoding(query) url_query.addEncodedQueryItem('data', encoded_query) url_query.addQueryItem('info', 'QgisQuickOSMPlugin') url_query.setPort(80) proxy = get_proxy() if proxy: self.network.setProxy(proxy) request = QNetworkRequest(url_query) request.setRawHeader("User-Agent", "QuickOSM") self.network_reply = self.network.get(request) self.loop = QEventLoop() self.network.finished.connect(self._end_of_request) self.loop.exec_() if self.network_reply.error() == QNetworkReply.NoError: timeout = '<remark> runtime error: Query timed out in "[a-z]+" ' \ 'at line [\d]+ after ([\d]+) seconds. </remark>' if re.search(timeout, self.data): raise OverpassTimeoutException else: return self.data elif self.network_reply.error() == QNetworkReply.UnknownContentError: raise OverpassBadRequestException else: raise NetWorkErrorException(suffix="Overpass API")
def query(self, query): """ Make a query to the overpass @param query:Query to execute @type query:str @raise OverpassBadRequestException,NetWorkErrorException, OverpassTimeoutException @return: the result of the query @rtype: str """ url_query = QUrl(self.__url + 'interpreter') # The output format can be forced (JSON or XML) if self.__output: query = re.sub(r'output="[a-z]*"', 'output="' + self.__output + '"', query) query = re.sub(r'\[out:[a-z]*', '[out:' + self.__output, query) # noinspection PyCallByClass encoded_query = QUrl.toPercentEncoding(query) url_query.addEncodedQueryItem('data', encoded_query) url_query.addQueryItem('info', 'QgisQuickOSMPlugin') url_query.setPort(80) proxy = get_proxy() if proxy: self.network.setProxy(proxy) request = QNetworkRequest(url_query) request.setRawHeader("User-Agent", "QuickOSM") self.network_reply = self.network.get(request) self.loop = QEventLoop() self.network.finished.connect(self._end_of_request) self.loop.exec_() if self.network_reply.error() == QNetworkReply.NoError: timeout = '<remark> runtime error: Query timed out in "[a-z]+" ' \ 'at line [\d]+ after ([\d]+) seconds. </remark>' if re.search(timeout, self.data): raise OverpassTimeoutException else: return self.data elif self.network_reply.error() == QNetworkReply.UnknownContentError: raise OverpassBadRequestException else: raise NetWorkErrorException(suffix="Overpass API")
def exchange_authorization_code(self, authorization_code, scopes, callback): log.debug("OAuth: exchanging authorization_code %s for an access_token", authorization_code) host, port = config.setting['server_host'], config.setting['server_port'] path = "/oauth2/token" url = QUrl() url.addQueryItem("grant_type", "authorization_code") url.addQueryItem("code", authorization_code) url.addQueryItem("client_id", MUSICBRAINZ_OAUTH_CLIENT_ID) url.addQueryItem("client_secret", MUSICBRAINZ_OAUTH_CLIENT_SECRET) url.addQueryItem("redirect_uri", "urn:ietf:wg:oauth:2.0:oob") data = str(url.encodedQuery()) self.xmlws.post(host, port, path, data, partial(self.on_exchange_authorization_code_finished, scopes, callback), xml=False, mblogin=True, priority=True, important=True)
def _checkUpload(self): if self._aborted: return log.debug('Sending upload status request (%s)', self.upload_id) url = QUrl(self.UPLOAD_STATUS.format(id=self.upload_id)) url.addQueryItem('token', self.auth_token) req = QNetworkRequest(url) self.reply = self.network_manager.get(req) self.reply.finished.connect(self._onUploadStatus)
def __init__(self, url, parent=None): super().__init__(parent) self.access_manager = FullscreenCSSFixer(QUrl('file://' + CSS_PATH)) self.page().setNetworkAccessManager(self.access_manager) self.page().mainFrame().initialLayoutCompleted.connect(self.extend_window) self.titleChanged.connect(self.setWindowTitle) if urlparse(url).scheme in ('', 'file'): url = p.realpath(url) qurl = QUrl(VIEWER_PATH) qurl.addQueryItem('file', url) # TODO: fix http urls self.load(qurl) self.page().setLinkDelegationPolicy(self.page().DelegateAllLinks) self.linkClicked.connect(self.link_clicked)
def prerun(self, text, options, path, router_success, router_error): """Load Google Translate w/ language/text to capture audio.""" if len(text) > LIMIT: raise IOError("Google Translate is limited to %d characters. " "Consider using a different service if you need " "playback for long phrases." % LIMIT) elif self._cb: raise SocketError("Google Translate does not allow concurrent " "runs. If you need to playback multiple " "phrases at the same time, please consider " "using a different service.") if not self._frame: self._prerun_setup() self._netops += 30 state = {} # using a dict to workaround lack of `nonlocal` keyword def okay(stream): if 'resolved' not in state: state['resolved'] = True self._cb = None router_success(stream) def fail(message): if 'resolved' not in state: state['resolved'] = True self._cb = None router_error(SocketError(message)) self._cb = dict(okay=okay, fail=fail) url = QUrl('https://translate.google.com/') url.addQueryItem('sl', options['voice']) url.addQueryItem('q', text) self._frame.load(url) def timeout(): fail("Request timed out") QTimer.singleShot(15000, timeout)
def decode(self, coord): url = QUrl("http://nominatim.openstreetmap.org/reverse") url.addQueryItem("format", "json") url.addQueryItem("lat", str(coord[0])) url.addQueryItem("lon", str(coord[1])) url.addQueryItem("zoom", "18") url.addQueryItem("addressdetails", "1") request = QNetworkRequest(url) reply = self.get(request) while reply.isRunning() : QApplication.processEvents() reply.deleteLater() self.deleteLater() return json.loads(unicode(reply.readAll(), 'UTF-8'))
def refresh_access_token(self, callback): refresh_token = config.persist["oauth_refresh_token"] log.debug("OAuth: refreshing access_token with a refresh_token %s", refresh_token) host, port = config.setting['server_host'], config.setting['server_port'] path = "/oauth2/token" url = QUrl() url.addQueryItem("grant_type", "refresh_token") url.addQueryItem("refresh_token", refresh_token) url.addQueryItem("client_id", MUSICBRAINZ_OAUTH_CLIENT_ID) url.addQueryItem("client_secret", MUSICBRAINZ_OAUTH_CLIENT_SECRET) data = str(url.encodedQuery()) self.xmlws.post(host, port, path, data, partial(self.on_refresh_access_token_finished, callback), xml=False, mblogin=True, priority=True, important=True)
def _render_header(title, mode, phrase, filters): r = [] r.append(ADV_HEADER) r.append('<h1>{0}</h1>'.format(title)) r.append('<ul class="nav">\n') modes = [(name, spec) for (name, spec) in MODE_DICT.items()] modes.sort(key=itemgetter(0)) for (name, spec) in modes: href = QUrl('search:///') if phrase: href.addQueryItem('phrase', phrase) if filters: href.addQueryItem('filters', filters) href.addQueryItem('mode', name) if name != mode: r.append('<li><a href="{href}">{title}</a></li>\n'.format( href=href.toEncoded(), title=spec['title'])) else: r.append('<li><span class="sel">{title}<span></li>\n'.format( href=href.toEncoded(), title=spec['title'])) r.append('</ul>\n') return ''.join(r)
def _render_header(title, mode, phrase, filters): r = [] r.append(ADV_HEADER) r.append('<h1>{0}</h1>'.format(title)) r.append('<ul class="nav">\n') modes = [(name, spec) for (name, spec) in MODE_DICT.items()] modes.sort(key=itemgetter(0)) for (name, spec) in modes: href = QUrl('search:///') if phrase: href.addQueryItem('phrase', phrase) if filters: href.addQueryItem('filters', filters) href.addQueryItem('mode', name) if name != mode: r.append( '<li><a href="{href}">{title}</a></li>\n'.format( href=href.toEncoded(), title=spec['title'])) else: r.append( '<li><span class="sel">{title}<span></li>\n'.format( href=href.toEncoded(), title=spec['title'])) r.append('</ul>\n') return ''.join(r)
def __init__(self, parent=None): QDialog.__init__(self, parent) self.setupUi(self) config = ConfigParser.ConfigParser() config.read(os.path.join(os.path.dirname(__file__), 'metadata.txt')) name = config.get('general', 'name') description = config.get('general', 'description') version = config.get('general', 'version') # self.title.setText( name ) # self.description.setText( description ) text = self.txt.toHtml() text = text.replace("$PLUGIN_NAME$", name) text = text.replace("$PLUGIN_VERSION$", version) subject = "Help: %s" % name body = """\n\n -------- Plugin name: %s Plugin version: %s Python version: %s Platform: %s - %s -------- """ % (name, version, platform.python_version(), platform.system(), platform.version()) mail = QUrl("mailto:[email protected]") mail.addQueryItem("subject", subject) mail.addQueryItem("body", body) text = text.replace("$MAIL_SUBJECT$", unicode(mail.encodedQueryItemValue("subject"))) text = text.replace("$MAIL_BODY$", unicode(mail.encodedQueryItemValue("body"))) self.txt.setHtml(text)
def _sendRequest(self, url, params, headers={}): if self.asynchonous: if self.reply is not None: self.reply.finished.disconnect(self.replyFinished) self.reply.abort() self.reply = None url = QUrl(url) for key, value in params.iteritems(): url.addQueryItem(key, value) QgsLogger.debug('Request: {}'.format(url.toEncoded())) request = QNetworkRequest(url) for key, value in headers.iteritems(): request.setRawHeader(key, value) self.reply = QgsNetworkAccessManager.instance().get(request) self.reply.finished.connect(self.replyFinished) else: response = urllib2.urlopen(self.url + '?' + urllib.urlencode(params)) data = json.load(response) self.loadData(data)
def get_authorization_url(self, scopes): host, port = config.setting['server_host'], config.setting['server_port'] url = QUrl() if (host in MUSICBRAINZ_SERVERS and port == 80) or port == 443: url.setScheme("https") else: url.setScheme("http") if port != 80: url.setPort(port) url.setHost(host) url.setPath("/oauth2/authorize") url.addQueryItem("response_type", "code") url.addQueryItem("client_id", MUSICBRAINZ_OAUTH_CLIENT_ID) url.addQueryItem("redirect_uri", "urn:ietf:wg:oauth:2.0:oob") url.addQueryItem("scope", scopes) return str(url.toEncoded())
def _sendRequest(self, url, params, headers={}): if self.asynchonous: if self.reply is not None: self.reply.finished.disconnect(self.replyFinished) self.reply.abort() self.reply = None url = QUrl(url) for key, value in params.iteritems(): url.addQueryItem(key, value) QgsLogger.debug('Request: {}'.format(url.toEncoded())) request = QNetworkRequest(url) for key, value in headers.iteritems(): request.setRawHeader(key, value) self.reply = QgsNetworkAccessManager.instance().get(request) self.reply.finished.connect(self.replyFinished) else: response = urllib2.urlopen(self.url + '?' + urllib.urlencode(params)) data = json.load(response) self.loadData(data)
def __init__(self, parent=None): QDialog.__init__(self, parent) self.setupUi(self) config = ConfigParser.ConfigParser() config.read(os.path.join(os.path.dirname(__file__), 'metadata.txt')) name = config.get('general', 'name') description = config.get('general', 'description') version = config.get('general', 'version') # self.title.setText( name ) # self.description.setText( description ) text = self.txt.toHtml() text = text.replace("$PLUGIN_NAME$", name) text = text.replace("$PLUGIN_VERSION$", version) subject = "Help: %s" % name body = """\n\n -------- Plugin name: %s Plugin version: %s Python version: %s Platform: %s - %s -------- """ % (name, version, platform.python_version(), platform.system(), platform.version()) mail = QUrl("mailto:[email protected]") mail.addQueryItem("subject", subject) mail.addQueryItem("body", body) text = text.replace("$MAIL_SUBJECT$", unicode(mail.encodedQueryItemValue("subject"))) text = text.replace("$MAIL_BODY$", unicode(mail.encodedQueryItemValue("body"))) self.txt.setHtml(text)
def build_papercdcase_url(artist, album, tracks): url = QUrl(PAPERCDCASE_URL) # papercdcase.com does not deal well with unicode characters :( url.addQueryItem('artist', textencoding.asciipunct(artist)) url.addQueryItem('title', textencoding.asciipunct(album)) i = 1 for track in tracks: url.addQueryItem('track' + str(i), textencoding.asciipunct(track)) i += 1 return url.toString()
def capabilitiesUrl(url): _url = QUrl(url) _url.addQueryItem("Service", "SOS") _url.addQueryItem("AcceptVersions", "2.0.0") _url.addQueryItem("Request", "GetCapabilities") return _url
def _urlencode_post_data(self, post_data): post_params = QUrl() for (key, value) in post_data.items(): post_params.addQueryItem(key, unicode(value)) return post_params.encodedQuery()
def capabilitiesUrl(url): _url = QUrl (url) _url.addQueryItem("Service", "SOS") _url.addQueryItem("AcceptVersions", "1.0.0") _url.addQueryItem("Request","GetCapabilities") return _url
# data[x] = wxResult # x += 1 print json.dumps(data) return if __name__ == '__main__': app = QApplication(sys.argv) type = 1 keyword = u"搞笑" page = 1 view = Browser() url = QUrl('http://weixin.sogou.com/weixin') # 搜索微信文章 test if 1 == type: url.addQueryItem('type', '1') url.addQueryItem('query', keyword) url.addQueryItem('page', '1') elif 2 == type: url.addQueryItem('type', '2') url.addQueryItem('query', keyword) url.addQueryItem('page', '2') # view.searchWxArticle('http://weixin.sogou.com/weixin?type=2&query=%E6%90%9E%E7%AC%91') # test 微信号 # view.searchWxService(url) # view.parseWxNumberHome(QUrl('http://mp.weixin.qq.com/profile?src=3×tamp=1477755435&ver=1&signature=GDDyd1Y3OVTxCrGuGZzQsertKX0LF9yULQwm0kn-rPXRb2dAerVWw06uawCkQqU4etpYmqWLmuKhjfW2QQw1qg==')) view.parseWxArticle( QUrl( 'http://mp.weixin.qq.com/s?timestamp=1477759661&src=3&ver=1&signature=ZYVg-oqTE86YJjL2ahRhJae54Yap4I5MAG7B3s*M5h9iG75B8vyjflchYvJgxfkqbmjT4dVJgGXx9Qf6OOefYfi3GeiY9SRRjlgdRf8tmm91MgjfAQmk5*pye-5ZkkOLo*kIEO724rsWk0i1wP1dvDUXNapv*bWZBO1VpHWNKic=' )) # view.page().userAgentForUrl = u'Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.23 Mobile Safari/537.36'