Browse Source

use urllib instead of curl for synchronous requests

Thomas Buck 3 years ago
parent
commit
7d2db72df4
1 changed files with 19 additions and 15 deletions
  1. 19
    15
      octotray

+ 19
- 15
octotray View File

@@ -4,19 +4,17 @@
4 4
 #
5 5
 # depends on:
6 6
 # - python-pyqt5
7
-# - curl
8 7
 #
9 8
 # see also:
10 9
 # https://doc.qt.io/qt-5/qtwidgets-widgets-imageviewer-example.html
11 10
 # https://stackoverflow.com/a/22618496
12 11
 
13 12
 import json
14
-import subprocess
15 13
 import sys
16 14
 import os
17
-import threading
18 15
 import time
19 16
 import urllib.parse
17
+import urllib.request
20 18
 from PyQt5 import QtWidgets, QtGui, QtCore, QtNetwork
21 19
 from PyQt5.QtWidgets import QSystemTrayIcon, QAction, QMenu, QMessageBox, QWidget, QLabel, QVBoxLayout, QHBoxLayout, QDesktopWidget, QSizePolicy, QSlider, QLayout
22 20
 from PyQt5.QtGui import QIcon, QPixmap, QImageReader, QDesktopServices
@@ -307,25 +305,31 @@ class OctoTray():
307 305
             return False
308 306
 
309 307
     def sendRequest(self, host, headers, path, content = None):
310
-        cmdline = 'curl -s -m 1'
311
-        for h in headers:
312
-            cmdline += " -H \"" + h + "\""
308
+        url = "http://" + host + "/api/" + path
313 309
         if content == None:
314
-            cmdline += " -X GET"
310
+            request = urllib.request.Request(url, None, headers)
315 311
         else:
316
-            cmdline += " -X POST"
317
-            cmdline += " -d '" + content + "'"
318
-        cmdline += " http://" + host + "/api/" + path
319
-        r = subprocess.run(cmdline, shell=True, capture_output=True, timeout=10, text=True)
320
-        return r.stdout
312
+            data = content.encode('ascii')
313
+            request = urllib.request.Request(url, data, headers)
314
+        try:
315
+            with urllib.request.urlopen(request, None, 1.0) as response:
316
+                text = response.read()
317
+                return text
318
+        except urllib.error.HTTPError:
319
+            pass
320
+        return ""
321 321
 
322 322
     def sendPostRequest(self, host, key, path, content):
323
-        headers = [ "Content-Type: application/json",
324
-                   "X-Api-Key: " + key ]
323
+        headers = {
324
+            "Content-Type": "application/json",
325
+            "X-Api-Key": key
326
+        }
325 327
         return self.sendRequest(host, headers, path, content)
326 328
 
327 329
     def sendGetRequest(self, host, key, path):
328
-        headers = [ "X-Api-Key: " + key ]
330
+        headers = {
331
+            "X-Api-Key": key
332
+        }
329 333
         return self.sendRequest(host, headers, path)
330 334
 
331 335
     def getTemperatureString(self, host, key):

Loading…
Cancel
Save