From 2c772eed6a350aaa57fc230791a35d233fd5dc34 Mon Sep 17 00:00:00 2001 From: fasiondog Date: Wed, 12 May 2021 01:54:24 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B0=81=E8=A3=85session=E5=AF=B9restful=20api?= =?UTF-8?q?=E6=96=B9=E6=B3=95=EF=BC=9B=E5=AE=9E=E6=97=B6=E5=88=B7=E6=96=B0?= =?UTF-8?q?qtreewidget=E7=95=8C=E9=9D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hikyuu/admin/ServerApi/__init__.py | 2 +- hikyuu/admin/ServerApi/assist.py | 11 ++---- hikyuu/admin/ServerApi/restful.py | 37 ++++++++++++++++++ hikyuu/admin/ServerApi/user.py | 16 ++------ hikyuu/admin/data/model.py | 4 +- hikyuu/admin/dialog/HkuEditSessionDialog.py | 17 ++++---- hikyuu/admin/language/zh_CN.qm | Bin 4551 -> 4547 bytes hikyuu/admin/language/zh_CN.ts | 2 +- .../widget/HkuCheckServerStatusThread.py | 15 ++++--- hikyuu/admin/widget/HkuSessionViewWidget.py | 2 + 10 files changed, 69 insertions(+), 37 deletions(-) diff --git a/hikyuu/admin/ServerApi/__init__.py b/hikyuu/admin/ServerApi/__init__.py index f2681e58..b17c6c46 100644 --- a/hikyuu/admin/ServerApi/__init__.py +++ b/hikyuu/admin/ServerApi/__init__.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- +from .restful import login from .assist import getServerStatus -from .user import login __all__ = ['login', 'getServerStatus'] diff --git a/hikyuu/admin/ServerApi/assist.py b/hikyuu/admin/ServerApi/assist.py index 9640d32a..12c02761 100644 --- a/hikyuu/admin/ServerApi/assist.py +++ b/hikyuu/admin/ServerApi/assist.py @@ -2,24 +2,19 @@ import logging import logging -from .config import getServerApiUrl, defaultRequestHeader -from .restful import get -from .user import update_token +from .restful import get, session_get from data import SessionModel from translate import _translate def getServerStatus(session: SessionModel): - url = getServerApiUrl(session.host, session.port, "assist", "status") - headers = defaultRequestHeader() - headers["hku_token"] = session.token try: - r = get(url, headers=headers) - update_token(r, session) + r = session_get(session, "assist", "status") if r["result"]: return "running", _translate("ServerApi", "running") else: return "stop", _translate("ServerApi", "failed! {}").format(r["errmsg"]) except Exception as e: + logging.info("{}: {}".format(e.__class__.__name__, e)) return "stop", _translate("ServerApi", "failed connect!") diff --git a/hikyuu/admin/ServerApi/restful.py b/hikyuu/admin/ServerApi/restful.py index 2ecf606e..a352db00 100644 --- a/hikyuu/admin/ServerApi/restful.py +++ b/hikyuu/admin/ServerApi/restful.py @@ -2,6 +2,8 @@ import requests import functools +from .config import getServerApiUrl, defaultRequestHeader +from data import SessionModel class HttpStatusError(Exception): @@ -63,3 +65,38 @@ def patch(url, data=None, **kwargs): @wrap_restful def put(url, data=None, **kwargs): return requests.put(url, data, **kwargs) + + +class RestErrorCode: + INVALID_ENUM_VALUE = 10000 + MISS_TOKEN = 10001 + UNAUTHORIZED = 10002 + AUTHORIZE_EXPIRED = 10003 + + +def login(session: SessionModel): + url = getServerApiUrl(session.host, session.port, "user", "login") + headers = defaultRequestHeader() + res = post(url, headers=headers, json={"user": session.user, "password": session.password}) + session.token = res["token"] + session.userid = res["userid"] + return session + + +def session_get(session: SessionModel, service, api, params=None, **kwargs): + def inner_get(session: SessionModel, service, api, params, **kwargs): + url = getServerApiUrl(session.host, session.port, service, api) + headers = defaultRequestHeader() + headers["hku_token"] = session.token + r = get(url, headers=headers, params=params, **kwargs) + if "update_token" in r: + session.token = r["update_token"] + return r + if not session.token: + session = login(session) + res = inner_get(session, service, api, params, **kwargs) + if not res["result"] and res['errcode'] == RestErrorCode.AUTHORIZE_EXPIRED: + session = login(session) + res = inner_get(session, service, api, params, **kwargs) + return res + diff --git a/hikyuu/admin/ServerApi/user.py b/hikyuu/admin/ServerApi/user.py index a16c6dc2..69d7c8de 100644 --- a/hikyuu/admin/ServerApi/user.py +++ b/hikyuu/admin/ServerApi/user.py @@ -7,20 +7,12 @@ from .restful import post from data import SessionModel -def login(session: SessionModel): - url = getServerApiUrl(session.host, session.port, "user", "login") - headers = defaultRequestHeader() - return post(url, headers=headers, json={"user": session.user, "password": session.password}) +# def login(session: SessionModel): +# url = getServerApiUrl(session.host, session.port, "user", "login") +# headers = defaultRequestHeader() +# return post(url, headers=headers, json={"user": session.user, "password": session.password}) -def update_token(res, session: SessionModel): - """ 如果响应中包含 "update_token, 则更新相应的session中的token - - :param SessionModel session: 会话 - :param res: 已经加码json的请求响应数据 - """ - if "update_token" in res: - session.token = res["update_token"] if __name__ == "__main__": diff --git a/hikyuu/admin/data/model.py b/hikyuu/admin/data/model.py index 4c272562..4897eeb5 100644 --- a/hikyuu/admin/data/model.py +++ b/hikyuu/admin/data/model.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- import os -from sqlalchemy import Column, Integer, String +from sqlalchemy import Column, Integer, String, BigInteger from .LocalDatabase import get_local_db db = get_local_db() @@ -17,6 +17,7 @@ class SessionModel(db.model): password = Column(String(64)) remark = Column(String(1024)) token = Column(String(256)) + userid = Column(BigInteger) def __init__(self): self.name = '' @@ -25,6 +26,7 @@ class SessionModel(db.model): self.user = '' self.password = '' self.remark = '' + self.userid = None def __str__(self): return 'SessionModel(id={}, name="{}", host="{}", port={}, user="{}", password="******")'.format( diff --git a/hikyuu/admin/dialog/HkuEditSessionDialog.py b/hikyuu/admin/dialog/HkuEditSessionDialog.py index a119ec1f..3010ae6c 100644 --- a/hikyuu/admin/dialog/HkuEditSessionDialog.py +++ b/hikyuu/admin/dialog/HkuEditSessionDialog.py @@ -6,7 +6,7 @@ import ServerApi import sqlalchemy from PyQt5 import QtWidgets, QtCore, QtGui from .Ui_HkuEditSessionDialog import Ui_HkuEditSessionDialog -from .HkuWaitingDialog import HkuWaitingDialog +from data import SessionModel _translate = QtCore.QCoreApplication.translate @@ -52,6 +52,8 @@ class HkuEditSessionDialog(QtWidgets.QDialog, Ui_HkuEditSessionDialog): self.remark_textEdit.setText(session_model.remark) def getData(self): + if self.session_model is None: + self.session_model = SessionModel() self.session_model.name = self.name self.session_model.host = self.host self.session_model.port = self.port @@ -98,14 +100,11 @@ class HkuEditSessionDialog(QtWidgets.QDialog, Ui_HkuEditSessionDialog): @QtCore.pyqtSlot() def on_test_pushButton_clicked(self): try: - r = ServerApi.login(self.getData()) - if r["result"]: - QtWidgets.QMessageBox.about( - self, _translate("HkuEditSessionDialog", "success"), - _translate("HkuEditSessionDialog", "Connect successfully!") - ) - else: - QtWidgets.QMessageBox.about(self, _translate("HkuEditSessionDialog", "Failed"), ret["errmsg"]) + ServerApi.login(self.getData()) + QtWidgets.QMessageBox.about( + self, _translate("HkuEditSessionDialog", "success"), + _translate("HkuEditSessionDialog", "Connect successfully!") + ) except Exception as e: QtWidgets.QMessageBox.about( self, _translate("HkuEditSessionDialog", "Failed"), diff --git a/hikyuu/admin/language/zh_CN.qm b/hikyuu/admin/language/zh_CN.qm index d51a189d38745d3b92cf9b0310a9931b5e287cba..54bd49509f127ad295c2353c04659cbf4091e12c 100644 GIT binary patch delta 426 zcmX@Ed{}vcTD=VeyN4+Q14|i$b`J{!16vq_`?Mnr4BYGtJ~NXT7#Qv_gfw?CFfg$* zglAR(>0*YMIZ+G@%vlV%%*H@{JPf%14M$+ujA@?TljH-|GYOk65iU(VW7(g(DmgVfTa!i0uxWc}w`!LW*5su*RK=sU09Ff~s z0F5@}Nb4*G(i=DqckBW>c{#^XwS5c>>}H%fiC=(Dn!-6RoR5KlSBUdyfH(s~Js&fW zVGgwL4CmF*I-tY}&a3VJfeL?f{%Q#VI_wA+*JO}iZ*i@&`vo-6nrr8r%RmbkaO>!X z0@b^4*MSUVljbQ|nFG{!l;_WUOQ40!yi9ePKnHH+O)GB%dW?a$a28Mt{#c0g{ delta 430 zcmX@Cd|Y{gTD=1UyN4+Q14|Wyb`J{!16ve>`?Mnr4BXrdJ~NXT7#Qv_gfw?CFfeg5 zglAR(>2ijcIZ+G@%y|sC%*H@{0t~rFHUnuFhMGB(85mf-8S3R!85sDQnO46(1T@E( zX(NL!0|Wm&=E7NeK>1qc$+ujA@;_PDH-|GYOk65iU(MQ6(g(DV-3&>meuUDa!i0uxWT@v`!LW*369|JK=sUW9Ff~s z0F5@~Nb4*G(pxwVckBW>c{RsTwS5c>>{gsPiC=(Dn!!0QoR5KlSB&#$fH(s~Js&%e zVGgwL0_WAxI-tZE&a3VJfeQa~{%Q#VI_v}&*JO}i?{TfO`vo-6o@?iv%Rmd4aO>!X z0@ZtP*MSUVljkW}nFG{!lIPESOQ419yi9ePKnL#RO)GB%dW?a$a28M Failed connect! Please check the host/ip and port %s - 连接失败!请检查主机/IP地址或端口号\n %s + 连接失败!请检查主机/IP地址或端口号 %s diff --git a/hikyuu/admin/widget/HkuCheckServerStatusThread.py b/hikyuu/admin/widget/HkuCheckServerStatusThread.py index 331dbb93..dc7c5cd6 100644 --- a/hikyuu/admin/widget/HkuCheckServerStatusThread.py +++ b/hikyuu/admin/widget/HkuCheckServerStatusThread.py @@ -3,17 +3,15 @@ import resource import ServerApi -from PyQt5 import QtCore, QtGui +from PyQt5 import QtCore, QtGui, QtWidgets class HkuCheckServerStatusThread(QtCore.QThread): - """定时检测服务器状态""" - status_changed = QtCore.pyqtSignal(list) - def __init__(self, session_widget): super(HkuCheckServerStatusThread, self).__init__() self.session_widget = session_widget self.working = True + self.first = True self.icons = { "running": QtGui.QIcon(":/icon/circular_green.png"), "stop": QtGui.QIcon(":/icon/circular_yellow.png") @@ -26,7 +24,10 @@ class HkuCheckServerStatusThread(QtCore.QThread): except Exception as e: print(e) pass - self.sleep(5) + if self.first: + self.sleep(1) + else: + self.sleep(30) def _run(self): items = [self.session_widget.tree.topLevelItem(i) for i in range(self.session_widget.tree.topLevelItemCount())] @@ -35,3 +36,7 @@ class HkuCheckServerStatusThread(QtCore.QThread): status, msg = ServerApi.getServerStatus(session) item.setText(1, msg) item.setIcon(1, self.icons[status]) + if items: + # 刷新 treewidget 显示界面 + self.session_widget.tree.viewport().update() + self.first = False diff --git a/hikyuu/admin/widget/HkuSessionViewWidget.py b/hikyuu/admin/widget/HkuSessionViewWidget.py index df6cc8d8..e0c4c0af 100644 --- a/hikyuu/admin/widget/HkuSessionViewWidget.py +++ b/hikyuu/admin/widget/HkuSessionViewWidget.py @@ -8,6 +8,8 @@ _translate = QtCore.QCoreApplication.translate class HkuSessionViewWidget(QtWidgets.QDockWidget): + status_changed = QtCore.pyqtSignal() + def __init__(self, parent=None): super(HkuSessionViewWidget, self).__init__(parent) self.setObjectName("HKUServerViewWidget")