-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
338 lines (286 loc) · 12.1 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
from ui.ui_postman import Ui_MainWindow
from ui.ui_dialogEditor import Ui_dialogEditor
import json
import urllib.request
import urllib.parse
import gzip
class PostMan(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.init()
def init(self):
self.setup_table()
self.ui.btnAdd.clicked.connect(self.handle_add)
self.ui.btnRemove.clicked.connect(self.handle_remove)
self.ui.textURL.returnPressed.connect(self.handle_send)
self.ui.btnSend.clicked.connect(self.handle_send)
self.ui.btnClear.clicked.connect(self.handle_clear)
self.ui.textURL.setText("http://localhost:3000/")
def setup_table(self):
self.tModel = QStandardItemModel()
self.tModel.setHorizontalHeaderLabels(['启用', '字段', '值'])
self.tModel.itemChanged.connect(self.on_model_change)
self.ui.table.setModel(self.tModel)
self.tHeader = CheckBoxHeader([0], parent=self.ui.table)
self.tHeader.clicked.connect(self.on_header_click)
self.ui.table.setHorizontalHeader(self.tHeader)
self.ui.table.setItemDelegateForColumn(
0, ReadOnlyDelegate(self.ui.table))
self.ui.table.setItemDelegateForColumn(
1, LineEditDelegate(self.ui.table))
self.ui.table.setItemDelegateForColumn(
2, ReadOnlyDelegate(self.ui.table))
self.ui.table.horizontalHeader().setStretchLastSection(True)
self.ui.table.doubleClicked.connect(self.handle_edit)
data = self.read_default_headers()
for index, (key, value) in enumerate(data):
item0 = QStandardItem()
item0.setCheckable(True)
item0.setCheckState(Qt.Checked)
self.tModel.appendRow(
[item0, QStandardItem(key), QStandardItem(value)])
self.on_model_change() # 手动触发一次表头更新,使其显示为全选状态
def read_default_headers(self):
file = open('default_headers.json', 'r')
data = json.loads(file.read())
return data.items()
def handle_edit(self, index: QModelIndex):
if(index.column() == 2):
self.dEditor = DialogEditor()
self.dEditor.show()
key_index = QModelIndex(index.model().index(index.row(), 1))
value_index = QModelIndex(index.model().index(index.row(), 2))
key = index.model().data(key_index)
value = index.model().data(value_index)
self.dEditor.key_index = key_index
self.dEditor.value_index = value_index
self.dEditor.setValue(key, value)
self.dEditor.accept_signal.connect(self.handle_accept)
self.dEditor.exec_()
def handle_accept(self, key, value):
if(self.dEditor.newItem):
item0 = QStandardItem()
item0.setCheckable(True)
item0.setCheckState(Qt.Checked)
self.tModel.appendRow(
[item0, QStandardItem(key), QStandardItem(value)])
else:
self.tModel.setData(self.dEditor.key_index, key)
self.tModel.setData(self.dEditor.value_index, value)
def handle_remove(self):
selected = self.ui.table.selectedIndexes()
indexes = list(set(map(lambda x: x.row(), selected)))
indexes.reverse()
for index in indexes:
self.tModel.removeRow(index)
def handle_add(self):
self.dEditor = DialogEditor()
self.dEditor.newItem = True
self.dEditor.accept_signal.connect(self.handle_accept)
self.dEditor.show()
self.dEditor.exec_()
def handle_send(self):
url = self.ui.textURL.text().strip()
if not url:
return
if not url.startswith('http://') and not url.startswith('https://'):
QMessageBox.warning(self, '错误', '请输入正确的协议名称')
return
method = self.ui.comboMethod.currentText()
self.ui.textResp.insertPlainText("%s %s\n" % (method, url))
headers = {}
for i in range(self.tModel.rowCount()):
if self.tModel.item(i, 0).checkState() == Qt.Checked:
key = self.tModel.item(i, 1).text().strip()
value = self.tModel.item(i, 2).text().strip()
headers[key] = value
try:
req = urllib.request.Request(url, method=method, headers=headers)
res = urllib.request.urlopen(req)
raw_headers = res.getheaders()
headers = {}
for (key, value) in raw_headers:
headers[key] = value
self.ui.textResp.insertPlainText(
"Response Headers:\n%s\n" % json.dumps(headers, indent=4))
content = res.read()
if 'Content-Encoding' in headers:
self.ui.textResp.insertPlainText(
"Content return in %s\n" % headers['Content-Encoding'])
if headers['Content-Encoding'] == 'gzip':
content = gzip.decompress(content)
else:
raise Exception('Unknown Content-Encoding')
charset = res.headers.get_content_charset()
self.ui.textResp.insertPlainText(
"Content charset is %s\n" % charset)
body = content.decode(charset)
self.ui.textResp.insertPlainText("Response Body:\n%s" % body)
except Exception as e:
self.ui.textResp.insertPlainText(str(e) + '\n')
finally:
self.ui.textResp.moveCursor(QTextCursor.End)
def handle_clear(self):
self.ui.textResp.clear()
def on_model_change(self):
for i in range(self.tModel.columnCount()):
checked = 0
unchecked = 0
for j in range(self.tModel.rowCount()):
if self.tModel.item(j, i).checkState() == Qt.Checked:
checked += 1
elif self.tModel.item(j, i).checkState() == Qt.Unchecked:
unchecked += 1
if checked and unchecked:
self.tHeader.updateCheckState(i, 2)
elif checked:
self.tHeader.updateCheckState(i, 1)
else:
self.tHeader.updateCheckState(i, 0)
def on_header_click(self, index, state):
for i in range(self.ui.table.model().rowCount()):
item = self.tModel.item(i, index)
item.setCheckState(Qt.Checked if state else Qt.Unchecked)
class DialogEditor(QDialog):
accept_signal = Signal(str, str)
def __init__(self):
super().__init__()
self.newItem = False
self.key_index: QModelIndex = None
self.value_index: QModelIndex = None
self.ui = Ui_dialogEditor()
self.ui.setupUi(self)
def accept(self):
key = self.ui.keyEdit.text().strip()
value = self.ui.valueEdit.toPlainText().strip()
if(not key):
QMessageBox.warning(self, '警告', '字段名不能为空')
else:
if(key.isascii() and value.isascii()):
self.accept_signal.emit(key, value)
return super().accept()
else:
QMessageBox.warning(self, '警告', '字段名和字段值只能是ASCII字符')
def reject(self):
return super().reject()
def setValue(self, key, value):
self.ui.keyEdit.setText(key)
self.ui.valueEdit.setText(value)
class ReadOnlyDelegate(QItemDelegate):
def __init__(self, parent):
super(ReadOnlyDelegate, self).__init__(parent)
def createEditor(self, parent, option, index):
return None
class LineEditDelegate(QItemDelegate):
def __init__(self, parent):
super(LineEditDelegate, self).__init__(parent)
def createEditor(self, parent, option, index):
LineEdit = QLineEdit(parent)
return LineEdit
def setEditorData(self, editor, index):
self.oText = index.model().data(index)
editor.setText(self.oText)
def setModelData(self, editor, model, index):
key = editor.text().strip()
if(not key):
QMessageBox.warning(self.parent(), '警告', '字段不能为空')
model.setData(index, self.oText)
else:
if(not key.isascii()):
QMessageBox.warning(self.parent(), '警告', '字段只能是ASCII字符')
model.setData(index, self.oText)
else:
model.setData(index, key)
class SpinBoxDelegate(QItemDelegate):
def __init__(self, parent, uint):
QItemDelegate.__init__(self, parent)
self.suffix = uint
# 创建控件并设置控件的最大和最小输入值及后缀
def createEditor(self, parent, option, index):
spinbox = QSpinBox(parent)
spinbox.setMaximum(999)
spinbox.setMinimum(0)
spinbox.setSuffix(self.suffix)
return spinbox
# 设置控件数值
def setEditorData(self, editor, index):
if(index.model().data(index) == ''):
editor.setValue(0)
else:
text = index.model().data(index).split(' ')[0]
editor.setValue(float(text))
# 设置更改数值后,单元格的数值
def setModelData(self, editor, model, index):
model.setData(index, str(editor.value()) + str(' ') + self.suffix)
class CheckBoxHeader(QHeaderView):
"""自定义表头类"""
# 自定义 复选框全选信号
clicked = Signal(int, bool)
# 这4个变量控制列头复选框的样式,位置以及大小
_x_offset = 3
_y_offset = 0
_width = 20
_height = 20
def __init__(self, column_index, orientation=Qt.Horizontal, parent=None):
super(CheckBoxHeader, self).__init__(orientation, parent)
self.setSectionsClickable(True)
if isinstance(column_index, list) or isinstance(column_index, tuple):
self.column_index = column_index
elif isinstance(column_index, int):
self.column_index = [column_index]
else:
raise RuntimeError('column_index must be a list, tuple or integer')
self.isChecked = {}
for column in self.column_index:
self.isChecked[column] = 0
def paintSection(self, painter, rect, logicalIndex):
painter.save()
super(CheckBoxHeader, self).paintSection(painter, rect, logicalIndex)
painter.restore()
self._y_offset = int((rect.height() - self._width) / 2.)
if logicalIndex in self.column_index:
option = QStyleOptionButton()
option.rect = QRect(
rect.x() + self._x_offset, rect.y() + self._y_offset, self._width, self._height)
option.state = QStyle.State_Enabled | QStyle.State_Active
if self.isChecked[logicalIndex] == 2:
option.state |= QStyle.State_NoChange
elif self.isChecked[logicalIndex]:
option.state |= QStyle.State_On
else:
option.state |= QStyle.State_Off
self.style().drawControl(QStyle.CE_CheckBox, option, painter)
def updateCheckState(self, index, state):
'''
记录每个点击checkbox 状态及序号存入dict
:param index:
:param state:
:return:
'''
self.isChecked[index] = state
self.viewport().update()
def mousePressEvent(self, event):
index = self.logicalIndexAt(event.pos())
if 0 <= index < self.count():
x = self.sectionPosition(index)
if x + self._x_offset < event.pos().x() < x + self._x_offset + self._width and self._y_offset < event.pos().y() < self._y_offset + self._height:
if self.isChecked[index] == 1:
self.isChecked[index] = 0
else:
self.isChecked[index] = 1
self.clicked.emit(index, self.isChecked[index])
self.viewport().update()
else:
super(CheckBoxHeader, self).mousePressEvent(event)
else:
super(CheckBoxHeader, self).mousePressEvent(event)
if __name__ == "__main__":
app = QApplication([])
window = PostMan()
window.show()
app.exec_()