python请求库:从附加路径获取响应的函数

时间:2018-08-16 20:36:05

标签: python python-3.x python-requests

我正在尝试在Thingworx平台上获取THING的价值。我有下面的代码可以达到目的。

from PyQt5 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets


class BookMarkToolBar(QtWidgets.QToolBar):
    bookmarkClicked = QtCore.pyqtSignal(QtCore.QUrl, str)

    def __init__(self, parent=None):
        super(BookMarkToolBar, self).__init__(parent)
        self.actionTriggered.connect(self.onActionTriggered)
        self.bookmark_list = []

    def setBoorkMarks(self, bookmarks):
        for bookmark in bookmarks:
            self.addBookMarkAction(bookmark["title"], bookmark["url"])

    def addBookMarkAction(self, title, url):
        bookmark = {"title": title, "url": url}
        fm = QtGui.QFontMetrics(self.font())
        if bookmark not in self.bookmark_list:
            text = fm.elidedText(title, QtCore.Qt.ElideRight, 150)
            action = self.addAction(text)
            action.setData(bookmark)
            self.bookmark_list.append(bookmark)

    @QtCore.pyqtSlot(QtWidgets.QAction)
    def onActionTriggered(self, action):
        bookmark = action.data()
        self.bookmarkClicked.emit(bookmark["url"], bookmark["title"])


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.defaultUrl = QtCore.QUrl()

        self.tabs = QtWidgets.QTabWidget()
        self.tabs.setTabsClosable(True)
        self.setCentralWidget(self.tabs)

        self.urlLe = QtWidgets.QLineEdit()
        self.urlLe.returnPressed.connect(self.onReturnPressed)
        self.favoriteButton = QtWidgets.QToolButton()
        self.favoriteButton.setIcon(QtGui.QIcon("images/star.png"))
        self.favoriteButton.clicked.connect(self.addFavoriteClicked)

        toolbar = self.addToolBar("")
        toolbar.addWidget(self.urlLe)
        toolbar.addWidget(self.favoriteButton)

        self.addToolBarBreak()
        self.bookmarkToolbar = BookMarkToolBar()
        self.bookmarkToolbar.bookmarkClicked.connect(self.add_new_tab)
        self.addToolBar(self.bookmarkToolbar)
        self.readSettings()

    def onReturnPressed(self):
        self.tabs.currentWidget().setUrl(QtCore.QUrl.fromUserInput(self.urlLe.text()))

    def addFavoriteClicked(self):
        loop = QtCore.QEventLoop()

        def callback(resp):
            setattr(self, "title", resp)
            loop.quit()

        web_browser = self.tabs.currentWidget()
        web_browser.page().runJavaScript("(function() { return document.title;})();", callback)
        url = web_browser.url()
        loop.exec_()
        self.bookmarkToolbar.addBookMarkAction(getattr(self, "title"), url)

    def add_new_tab(self, qurl=QtCore.QUrl(), label='Blank'):
        web_browser = QtWebEngineWidgets.QWebEngineView()
        web_browser.setUrl(qurl)
        web_browser.adjustSize()
        web_browser.urlChanged.connect(self.updateUlrLe)
        index = self.tabs.addTab(web_browser, label)
        self.tabs.setCurrentIndex(index)
        self.urlLe.setText(qurl.toString())

    def updateUlrLe(self, url):
        self.urlLe.setText(url.toDisplayString())

    def readSettings(self):
        setting = QtCore.QSettings()
        self.defaultUrl = setting.value("defaultUrl", QtCore.QUrl('http://www.google.com'))
        self.add_new_tab(self.defaultUrl, 'Home Page')
        self.bookmarkToolbar.setBoorkMarks(setting.value("bookmarks", []))

    def saveSettins(self):
        settings = QtCore.QSettings()
        settings.setValue("defaultUrl", self.defaultUrl)
        settings.setValue("bookmarks", self.bookmarkToolbar.bookmark_list)

    def closeEvent(self, event):
        self.saveSettins()
        super(MainWindow, self).closeEvent(event)


if __name__ == '__main__':
    import sys

    QtCore.QCoreApplication.setOrganizationName("eyllanesc.org")
    QtCore.QCoreApplication.setOrganizationDomain("www.eyllanesc.com")
    QtCore.QCoreApplication.setApplicationName("MyApp")
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

但是我试图将URL分解为基本URL,直到import json import requests url = 'https://academic.cloud.thingworx.com/Thingworx/Things/weatherrover1/Properties/battery' headers = {'appKey': 'fdb123fc-e369-483b-baa5-8445bd8746ee', 'Accept': 'application/json'} getreq = requests.get(url, headers=headers) 并为随后的内容定义变量并获得响应。但是失败了。下面是我尝试的代码。

'https://academic.cloud.thingworx.com/'

1 个答案:

答案 0 :(得分:3)

params参数完全是 ,用于定义查询参数,即网址中?之后的部分。

您在params中添加了 URL路径元素,但是您无法获得所需的URL,因为URL路径是之前 URL中的?。您可以使用string formatting来扩展路径。

字符串格式可以使用模板,因此URL可以是:

url_template = 'https://academic.cloud.thingworx.com/{platform}/{entity}/{entity_name}/Properties/{property}'

,然后可以从词典中获取每个{...}占位符名称:

url_parts = {
    'entity': 'Things',
    'platform': 'Thingworx',
    'entity': 'Things',
    'entity_name': 'weatherrover1',
    'property': 'battery'
}

url_template.format(**url_parts)

使用url_template.format(**url_parts)导致requests.get()通话:

response = requests.get(url_template.format(**url_parts), headers=headers)