Commit d286cb0a authored by wanli's avatar wanli

update

parent 65402844
......@@ -54,6 +54,7 @@ backend/backupData.json
config.ini
*.epk
tools/build_out/
tools/build_out/logs
tools/build_out/logs/*
......
'''
Author: your name
Date: 2021-04-14 14:12:18
LastEditTime: 2021-06-30 22:50:10
LastEditors: your name
Description: In User Settings Edit
FilePath: \evm-store\backend\app\setting.py
'''
#!/usr/bin/env python
# -*- coding: utf_8 -*-
......@@ -9,7 +17,7 @@ conf.read(os.path.join(os.getcwd(), "config.ini"))
config = dict(
NAME='evm_store',
DEBUG=False,
DEBUG=True,
HOST=conf.get('application', 'host'),
PORT=int(conf.get('application', 'port')),
LOGIN_DISABLED=False,
......
#!/usr/bin/env python
# -*- coding: utf_8 -*-
import copy
import time
import types
import json
import logging
import traceback
from datetime import datetime
from pony.orm import *
from flask import request
from model import fullStackDB
from model.menu import Menu
from model.user import User
from utils import sql_filter
logger = logging.getLogger("MenuManager")
class MenuManager(object):
def __init__(self):
super(MenuManager, self).__init__()
def add(self, data):
editor = User.get(id=request.current_user.get("id"))
if not editor:
return False, "current user is not exists"
result = Menu.get(path=data.get("path"))
if result:
return False, "menu path has been exists."
data.update({
'create_by': editor,
'create_at': datetime.now(),
'update_by': editor,
'update_at': datetime.now(),
})
result = fullStackDB.add(Menu, **data)
return result, "add menu {}.".format("success" if result else "fail")
def delete(self, uuid):
editor = User.get(id=request.current_user.get("id"))
if not editor:
return False, "current user is not exists"
result = fullStackDB.update(Menu, { 'uuid': uuid }, is_delete=True, delete_at=datetime.now(), delete_by=editor)
return result, "delete menu {}.".format("success" if result else "fail")
def get(self, data):
result = Menu.get(**data)
if result:
result = result.to_dict(only=["uuid", "name", "create_at", "update_at"])
return result, "get menu {}.".format("success" if result else "no data")
def getList(self, data):
if not data or len(data) <= 0:
return False, 0, "parameters can not be null."
temp = copy.deepcopy(data)
if 'pagenum' in temp:
temp.pop('pagenum')
if 'pagesize' in temp:
temp.pop('pagesize')
if 'scope_type' in temp:
temp.pop('scope_type')
if 'props' in temp:
temp.pop('props')
temp.setdefault("is_delete", False)
if "scope_type" in data and data.get("scope_type") == "list":
result = Menu.select().where(**temp).order_by(desc(Menu.create_at))
temp = []
fields = ["uuid", "name"]
if "props" in data and isinstance(data.get("props"), list):
fields = data.get("props")
for item in result:
temp.append(item.to_dict(only=fields))
return temp, len(temp), "get menu {}.".format("success" if temp else "fail")
result = fullStackDB.pagination(Menu, Menu.create_at, pagenum=data.get("pagenum", 1), pagesize=data.get("pagesize", 10), **temp)
count = fullStackDB.count(Menu, **temp)
if result and len(result):
temp = []
for item in result:
t = item.to_dict(with_collections=True, related_objects=True)
t.update({ "create_at": item.create_at.strftime("%Y-%m-%d %H:%M:%S") })
t.update({ "update_at": item.update_at.strftime("%Y-%m-%d %H:%M:%S") })
t.update({ "create_by": item.create_by.to_dict(only=["uuid", "username"]) })
t.update({ "update_by": item.update_by.to_dict(only=["uuid", "username"]) })
temp.append(t)
result = temp
return result, count, "get menu {}.".format("success" if result else "no data")
def update(self, uuid, data):
# 当参数为空时,直接返回错误
if len(data) <= 0 or (len(data.keys()) == 1 and "id" in data):
return False, "parameters can not be null."
# 查询请求者是否存在
editor = User.get(id=request.current_user.get("id"))
if not editor:
return False, "current user is not exists"
result = fullStackDB.update(Menu, { 'uuid': uuid }, update_at=datetime.now(), update_by=editor, **data)
return result, "update menu {}.".format("success" if result else "fail")
menuManager = MenuManager()
'''
Author: your name
Date: 2021-06-29 19:24:32
LastEditTime: 2021-06-29 19:28:16
LastEditTime: 2021-07-01 10:01:48
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \evm-store\backend\controller\monitor.py
......@@ -115,19 +115,94 @@ def insert_data(msg):
if msg.get("system"):
msg.get("system").update({ "watch": watch_id })
res = systemResource.post(msg.get("system"))
print("!!!!!!", res)
systemResource.post(msg.get("system"))
if msg.get("lvgl"):
msg.get("lvgl").update({ "watch": watch_id })
res = lvglResource.post(msg.get("lvgl"))
print("@@@@@@", res)
lvglResource.post(msg.get("lvgl"))
if msg.get("evm"):
msg.get("evm").update({ "watch": watch_id })
res = evmResource.post(msg.get("evm"))
print("######", res)
evmResource.post(msg.get("evm"))
if msg.get("image"):
res = imageResource.post_array(msg.get("image"), watch_id)
print("$$$$$$", res)
\ No newline at end of file
imageResource.post_array(msg.get("image"), watch_id)
def get_watch_list():
result = session.query(Watch).all()
tmp = []
for item in result:
tmp.append({
'id': item.id,
'imei': item.imei
})
return tmp
def evm_data(watch, start, end):
filters = [Evm.watch==watch]
if start:
filters.append(Evm.timestamp >= start)
if end:
filters.append(Evm.timestamp <= end)
result = session.query(Evm).filter(*filters).order_by(Evm.timestamp).all()
temp = []
for item in result:
t = item.to_dict()
if t.get("timestamp"):
t.update({ 'timestamp': t.get("timestamp").strftime("%Y-%m-%d %H:%M:%S") })
temp.append(t)
return temp
def lvgl_data(watch, start, end):
filters = [Lvgl.watch==watch]
if start:
filters.append(Lvgl.timestamp>=start)
if end:
filters.append(Lvgl.timestamp<=end)
result = session.query(Lvgl).filter(*filters).order_by(Lvgl.timestamp).all()
temp = []
for item in result:
t = item.to_dict()
if t.get("timestamp"):
t.update({ 'timestamp': t.get("timestamp").strftime("%Y-%m-%d %H:%M:%S") })
temp.append(t)
return temp
def image_data(watch, start, end):
filters = [Image.watch==watch]
if start:
filters.append(Image.timestamp>=start)
if end:
filters.append(Image.timestamp<=end)
result = session.query(Image).filter(*filters).order_by(Image.timestamp).all()
temp = []
for item in result:
t = item.to_dict()
if t.get("timestamp"):
t.update({ 'timestamp': t.get("timestamp").strftime("%Y-%m-%d %H:%M:%S") })
temp.append(t)
return temp
def get_monitor_list(watch, category, start, end):
# 判断watch是否存在
w = session.query(Watch).filter(Watch.id==watch).first()
if not w:
return []
if category == "system":
return []
elif category == "image":
return image_data(watch, start, end)
elif category == "lvgl":
return lvgl_data(watch, start, end)
elif category == "evm":
return evm_data(watch, start, end)
else:
return {
'evm': evm_data(watch, start, end),
'lvgl': lvgl_data(watch, start, end),
'image': image_data(watch, start, end)
}
'''
Author: your name
Date: 2021-04-14 14:12:18
LastEditTime: 2021-06-29 19:58:57
LastEditTime: 2021-06-30 23:52:39
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \evm-store\backend\model\monitor.py
......@@ -9,25 +9,40 @@ FilePath: \evm-store\backend\model\monitor.py
#!/usr/bin/env python
# -*- coding: utf_8 -*-
import json
from app.setting import config
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String, Float
from sqlalchemy import func, Column, Integer, String, Float, DateTime, Numeric
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import sessionmaker, class_mapper, object_mapper
engine = create_engine('sqlite:///{}?check_same_thread=False'.format(config.get("DATABASE")), echo=True)
engine = create_engine('sqlite:///{}?check_same_thread=False'.format(config.get("DATABASE")), echo=False)
Base = declarative_base()
def get_current_datetime():
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
return datetime.now()
def object_to_dict(obj):
columns = [column.key for column in class_mapper(obj.__class__).columns]
get_key_value = lambda c: (c, getattr(obj, c).isoformat()) if isinstance(getattr(obj, c), datetime) else (c, getattr(obj, c))
return dict(map(get_key_value, columns))
class WatchTest(Base):
__tablename__ = 'monitor_watch_test'
id = Column(Integer, primary_key=True, autoincrement=True)
imei = Column(String)
create_at = Column(DateTime(timezone=True), default=get_current_datetime, server_default=func.now(), onupdate=func.now())
class Watch(Base):
__tablename__ = 'monitor_watch'
id = Column(Integer, primary_key=True, autoincrement=True)
imei = Column(String)
create_at = Column(String, default=get_current_datetime)
create_at = Column(DateTime(timezone=True), default=get_current_datetime, server_default=func.now(), onupdate=func.now())
def to_dict(self):
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
class Request(Base):
__tablename__ = 'monitor_request'
......@@ -36,7 +51,10 @@ class Request(Base):
host = Column(String)
path = Column(String)
protocol = Column(String)
create_at = Column(String, default=get_current_datetime)
create_at = Column(DateTime(timezone=True), default=get_current_datetime, server_default=func.now(), onupdate=func.now())
def to_dict(self):
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
class System(Base):
__tablename__ = 'monitor_system'
......@@ -44,7 +62,10 @@ class System(Base):
id = Column(Integer, primary_key=True, autoincrement=True)
watch = Column(Integer) # 手表ID
free_size = Column(Integer) # 单位:字节
timestamp = Column(String(50), default=get_current_datetime)
timestamp = Column(DateTime(timezone=True), default=get_current_datetime, server_default=func.now(), onupdate=func.now())
def to_dict(self):
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
class Lvgl(Base):
__tablename__ = 'monitor_lvgl'
......@@ -58,7 +79,10 @@ class Lvgl(Base):
used_cnt = Column(Integer)
used_pct = Column(Integer)
frag_pct = Column(Integer)
timestamp = Column(String(50), default=get_current_datetime)
timestamp = Column(DateTime(timezone=True), default=get_current_datetime, server_default=func.now(), onupdate=func.now())
def to_dict(self):
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
class Evm(Base):
__tablename__ = 'monitor_evm'
......@@ -73,7 +97,29 @@ class Evm(Base):
heap_used_size = Column(Integer)
stack_total_size = Column(Integer)
stack_used_size = Column(Integer)
timestamp = Column(String(50), default=get_current_datetime)
timestamp = Column(DateTime(timezone=True), default=get_current_datetime, server_default=func.now(), onupdate=func.now())
def to_dict(self):
# def convert_datetime(value):
# if value:
# return value.strftime("%Y-%m-%d %H:%M:%S")
# else:
# return ""
# for col in self.__table__.columns:
# if isinstance(col.type, DateTime):
# value = convert_datetime(getattr(self, col.name))
# elif isinstance(col.type, Numeric):
# value = float(getattr(self, col.name))
# else:
# value = getattr(self, col.name)
# yield {col.name: value}
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
def to_json(self):
d = dict(self.__todict__())
return json.dumps(d)
class Image(Base):
__tablename__ = 'monitor_image'
......@@ -85,7 +131,10 @@ class Image(Base):
png_uncompressed_size = Column(Integer)
png_total_count = Column(Integer)
png_file_size = Column(Integer)
timestamp = Column(String(50), default=get_current_datetime)
timestamp = Column(DateTime(timezone=True), default=get_current_datetime, server_default=func.now(), onupdate=func.now())
def to_dict(self):
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
Base.metadata.create_all(engine, checkfirst=True)
......
{
"count": 84
}
\ No newline at end of file
'''
Author: your name
Date: 2021-04-14 14:12:18
LastEditTime: 2021-06-29 20:22:42
LastEditTime: 2021-07-01 00:06:01
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \evm-store\backend\start.py
......@@ -11,14 +11,14 @@ FilePath: \evm-store\backend\start.py
import sys
import os
import signal
from datetime import datetime
# import tornado.autoreload
from tornado.wsgi import WSGIContainer
from tornado.web import Application, RequestHandler, FallbackHandler
from tornado.ioloop import IOLoop
from tornado.autoreload import watch
from fullstack.log import logger
from view import app
from view.monitor import DeviceMessageHandler, NotifyHandler
from view.monitor import DeviceMessageHandler, NotifyHandler, WatchHandler
from app import config
class GracefulExit(SystemExit):
......@@ -48,6 +48,7 @@ def start():
(r'/', VueHandler),
(r'/index', VueHandler),
(r"/api/v1/evm_store/monitor", DeviceMessageHandler),
(r"/api/v1/evm_store/watch", WatchHandler),
(r"/ws/v1/notify", NotifyHandler),
(r'.*', FallbackHandler, dict(fallback=wsgi_app))
], **settings)
......@@ -66,6 +67,9 @@ def start():
signal.signal(signal.SIGINT, raise_graceful_exit)
signal.signal(signal.SIGTERM, raise_graceful_exit)
# instance = tornado.ioloop.IOLoop.instance()
# tornado.autoreload.start(instance)
# instance.start()
IOLoop.instance().start()
if __name__ == '__main__':
......
'''
Author: your name
Date: 2021-06-29 19:33:41
LastEditTime: 2021-06-29 19:55:22
LastEditTime: 2021-07-01 04:03:21
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \evm-store\backend\view\monitor.py
......@@ -12,13 +12,21 @@ from tornado.web import RequestHandler, StaticFileHandler
from tornado.websocket import WebSocketHandler, WebSocketClosedError
import json
import signal
import time
import logging
import pprint
from datetime import datetime
from controller.monitor import insert_data
import traceback
from datetime import datetime, timedelta
from controller.monitor import insert_data, get_monitor_list, get_watch_list
logger = logging.getLogger(__name__)
def datetime2secs(mydate):
return time.mktime(mydate.timetuple())
def secs2datetime(ts):
return datetime.fromtimestamp(ts)
class ObjectDict(dict):
"""Makes a dictionary behave like an object, with attribute-style access.
"""
......@@ -131,25 +139,81 @@ class MainHandler(BaseHandler):
print(self.request.method) # 请求方法
print(self.request.host) # IP地址
print(self.request.protocol)
# self.get_query_argument('a', value)
# self.get_body_argument()
# self.request.files
self.write("Hello, world")
def post(self):
data = tornado.escape.json_decode(self.request.body)
print("=====>", data, type(data))
self.write(json.dumps({ 'code': 100, 'message': 'success' }))
self.write(json.dumps({ 'code': 100, 'msg': 'success' }))
message = {'imei': '12345678900005', 'system': {'free_size': 0}, 'lvgl': {'total_size': 5242880, 'free_cnt': 31, 'free_size': 1279664, 'free_biggest_size': 1205448, 'used_cnt': 832, 'used_pct': 76, 'frag_pct': 6}, 'evm': {'total_size': 2097152, 'free_size': 0, 'gc_usage': 50}, 'image': [{'uri': 'evue_launcher', 'length': 1043, 'png_total_count': 0, 'png_uncompressed_size': 0, 'png_file_size': 0}, {'uri': 'kdgs_1_storyList', 'length': 9608, 'png_total_count': 193, 'png_uncompressed_size': 370884, 'png_file_size': 209807}]}
insert_data(message)
NotifyHandler.broadcastMessage(message)
class WatchHandler(BaseHandler):
def get(self, *args, **kwargs):
# 获取手表列表
print("#############", args)
print("/////////////", kwargs)
print(self.request.path) # 请求路径
print(self.request.method) # 请求方法
print(self.request.host) # IP地址
print(self.request.protocol)
try:
result = get_watch_list()
if result:
self.write(json.dumps({ 'code': 200, 'data': result, 'msg': 'success' }))
else:
self.write(json.dumps({ 'code': 204, 'data': None, 'msg': 'no data' }))
except Exception as e:
logger.error(e)
self.write(json.dumps({ 'code': 500, 'data': None, 'msg': 'server error' }))
def post(self):
data = tornado.escape.json_decode(self.request.body)
print("=====>", data, type(data))
self.write(json.dumps({ 'code': 100, 'msg': 'success' }))
class DeviceMessageHandler(BaseHandler):
def get(self):
self.write("Hello, world")
if not self.get_argument('watch', None):
self.write(json.dumps({ 'code': 400, 'msg': 'params error, watch can not be null' }))
return
try:
watch = self.get_query_argument('watch')
category = self.get_query_argument('category', 'all')
start = self.get_query_argument('start', None)
end = self.get_query_argument('end', None)
if start and start.isdigit():
start = int(start)
start = time.localtime(start)
start = time.strftime("%Y-%m-%d %H:%M:%S", start)
else:
start = (datetime.now()-timedelta(minutes=10)).strftime("%Y-%m-%d %H:%M:%S")
if end and end.isdigit():
end = time.localtime(int(end))
end = time.strftime("%Y-%m-%d %H:%M:%S", end)
result = get_monitor_list(int(watch), category, start, end)
if result:
self.write(json.dumps({ 'code': 200, 'data': result, 'msg': 'success', 'type': 'array' if isinstance(result, list) else 'object' }))
else:
self.write(json.dumps({ 'code': 204, 'data': None, 'msg': 'no data' }))
except Exception as e:
logger.error(e)
traceback.print_exc()
self.write(json.dumps({ 'code': 500, 'data': None, 'msg': 'server error' }))
def post(self):
data = tornado.escape.json_decode(self.request.body)
print("=====>", data, type(data))
request = {
'host': self.request.remote_ip,
......@@ -169,6 +233,7 @@ def make_app():
return tornado.web.Application([
(r"/", MainHandler),
(r"/api/v1/evm_store/monitor", DeviceMessageHandler),
(r"/api/v1/evm_store/watch", WatchHandler),
(r"/ws/v1/notify", NotifyHandler),
(r"/dist/(.*)", StaticFileHandler, { "path": "dist" }),
])
......
<!--
* @Author: your name
* @Date: 2021-04-14 14:12:18
* @LastEditTime: 2021-07-01 00:18:54
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \evm-store\frontend\src\App.vue
-->
<template>
<div id="app">
<router-view />
......
......@@ -215,19 +215,18 @@ export function deleteRole(id) {
});
}
export function getPermissionList(params) {
export function getWatchList() {
return request({
url: "/api/v1/evm_store/permission/list",
method: "post",
data: params,
url: "/api/v1/evm_store/watch",
method: "get",
});
}
export function addPermission(params) {
export function getMonitorData(params) {
return request({
url: "/api/v1/evm_store/permission/add",
method: "post",
data: params,
url: "/api/v1/evm_store/monitor",
method: "get",
params,
});
}
......
/*
* @Author: your name
* @Date: 2021-04-14 14:12:19
* @LastEditTime: 2021-07-01 00:41:19
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \evm-store\frontend\src\main.js
*/
import Vue from "vue";
import "normalize.css/normalize.css"; // A modern alternative to CSS resets
// elementu-ui framework
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
//import locale from 'element-ui/lib/locale/lang/en' // lang i18n
import "@/styles/index.scss"; // global css
import "@/styles/theme-blue/index.css"; // blue theme css
import "@/styles/index.scss";
import "@/styles/theme-blue/index.css";
import App from "./App";
import store from "./store";
import router from "./router";
import "@/icons"; // icon
import "@/permission"; // permission control
import "@/icons/icon.js"; // iconfont
import "@/icons/icon-color.js"; // iconfont
import "@/icons";
import "@/permission";
import "@/icons/icon.js";
import "@/icons/icon-color.js";
import IconFont from "@/components/IconFont";
import myCharts from '@/utils/myCharts.js';
Vue.use(myCharts)
/**
* If you don't want to use mock-server
* you want to use MockJs for mock api
......@@ -40,11 +49,9 @@ import IconFont from "@/components/IconFont";
Vue.component("IconFont", IconFont);
// set ElementUI lang to EN
//Vue.use(ElementUI, { locale })
// Vue.use(ElementUI, { locale })
// 如果想要中文版 element-ui,按如下方式声明
Vue.use(ElementUI);
// Vue.prototype.$axios = gAxios;
// Vue.prototype.$client = client;
Vue.config.productionTip = false;
new Vue({
......
......@@ -175,6 +175,28 @@ export const constantRoutes = [
meta: { title: '应用管理', icon: 'home' }
}]
},
{
path: '/chart',
redirect: '/chart/index',
component: Layout,
children: [{
path: 'index',
name: 'AppChart',
component: () => import('@/views/system/chart'),
meta: { title: '实时曲线', icon: 'home' }
}]
},
{
path: '/history',
redirect: '/history/index',
component: Layout,
children: [{
path: 'index',
name: 'AppHistoryChart',
component: () => import('@/views/system/history'),
meta: { title: '历史曲线', icon: 'home' }
}]
},
{
path: '/tool',
redirect: '/tool/index',
......
/*
* @Author: your name
* @Date: 2021-04-14 14:12:19
* @LastEditTime: 2021-06-29 19:49:09
* @LastEditTime: 2021-07-01 11:26:51
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \evm-store\frontend\src\settings.js
......@@ -64,13 +64,6 @@ export default {
icon: "gongzuotai",
path: "profile/index",
},
{
vue: "app-store/docs.vue",
title: "开发文档",
name: "Document",
icon: "gongzuotai",
path: "docs/index",
},
{
vue: "system/monitor.vue",
title: "资源监视",
......@@ -78,6 +71,20 @@ export default {
icon: "gongzuotai",
path: "monitor/index",
},
{
vue: "system/chart.vue",
title: "实时曲线",
name: "AppChart",
icon: "gongzuotai",
path: "chart/index",
},
{
vue: "system/history.vue",
title: "历史曲线",
name: "AppHistoryChart",
icon: "gongzuotai",
path: "history/index",
},
{
vue: "system/tool.vue",
title: "工具",
......@@ -85,5 +92,12 @@ export default {
icon: "gongzuotai",
path: "tool/index",
},
{
vue: "app-store/docs.vue",
title: "开发文档",
name: "Document",
icon: "gongzuotai",
path: "docs/index",
},
],
};
/*
* @Author: your name
* @Date: 2021-04-14 14:12:19
* @LastEditTime: 2021-07-01 01:11:46
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \evm-store\frontend\src\utils\wsNotify.js
*/
import Vue from "vue";
export const wsNotify = new WebSocket(
`ws://${window.location.hostname}:5001/ws/v1/notify`
);
window.wsNotify = wsNotify;
wsNotify.eventBus = new Vue();
wsNotify.onopen = function (event) {
console.log("websocket is conneted!", event);
wsNotify.eventBus.$emit("open", event);
};
wsNotify.onmessage = function (event) {
var message = JSON.parse(event.data);
wsNotify.eventBus.$emit("message", message);
};
wsNotify.onerror = function (error) {
console.log(error);
wsNotify.eventBus.$emit("error", error);
};
wsNotify.onclose = function (event) {
console.log("websocket is colosed!", event);
wsNotify.eventBus.$emit("close", event);
};
/*
* @Author: your name
* @Date: 2021-07-01 00:39:07
* @LastEditTime: 2021-07-01 00:39:56
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \evm-store\frontend\src\utils\myCharts.js
*/
import * as echarts from "echarts";
const install = function (Vue) {
Object.defineProperties(Vue.prototype, {
$chart: {
get() {
return {
line: function (id) {
this.chart = echarts.init(document.getElementById(id));
this.chart.clear();
const optionData = {
xAxis: {
type: "category",
data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
},
yAxis: {
type: "value",
},
series: [
{
data: [820, 932, 901, 934, 1290, 1330, 1320],
type: "line",
smooth: true,
},
],
};
this.chart.setOption(optionData);
},
};
},
},
});
};
export default {
install,
};
/*
* @Author: your name
* @Date: 2021-04-14 14:12:19
* @LastEditTime: 2021-07-01 02:12:04
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \evm-store\frontend\src\utils\utils.js
*/
function formatNumber(n) {
n = n.toString();
return n[1] ? n : "0" + n;
}
export function getUTCDateTime(datetime) {
var year = datetime.getUTCFullYear();
var month = datetime.getUTCMonth() + 1;
var day = datetime.getUTCDate();
var hour = datetime.getUTCHours();
var minute = datetime.getUTCMinutes();
var second = datetime.getUTCSeconds();
export function getDateTime(datetime) {
var year = datetime.getFullYear();
var month = datetime.getMonth() + 1;
var day = datetime.getDate();
var hour = datetime.getHours();
var minute = datetime.getMinutes();
var second = datetime.getSeconds();
return [year, month, day, hour, minute, second].map(formatNumber);
}
......@@ -24,9 +32,9 @@ export function formatDateTime(
return result;
}
export function formatUTCDateTime(datetime) {
export function getDateTimeString(datetime) {
if (!(datetime instanceof Date)) datetime = new Date(datetime);
datetime = getUTCDateTime(datetime);
datetime = getDateTime(datetime);
const format = ["-", "-", " ", ":", ":"];
let result = "";
datetime.forEach((d, i) => {
......
import Vue from "vue";
import defaultSettings from "@/settings";
let wsNotify = null;
const connectWSServer = () => {
try {
wsNotify = new WebSocket(
"ws://" +
window.location.hostname +
":" +
defaultSettings.port +
"/ws/api/v1/notify"
);
} catch (err) {
console.error(err);
}
};
connectWSServer();
window.wsNotify = wsNotify;
wsNotify.notifyBus = new Vue();
wsNotify.onopen = function(event) {
console.log("wsNotify websocket is conneted!", event);
};
wsNotify.onmessage = function(event) {
var message = JSON.parse(event.data);
console.log(message);
// console.log(message["type"]);
wsNotify.notifyBus.$emit(message["type"], message);
};
wsNotify.onerror = function(event) {
console.log(event);
};
wsNotify.onclose = function(event) {
// 关闭 websocket
console.log("wsNotify websocket is colosed!", event);
// connectWSServer();
};
export default wsNotify;
@font-face {
font-family: "iconfont";
src: url("//at.alicdn.com/t/font_2113109_7bz8s7j187s.eot?t=1601822003589"); /* IE9 */
src: url("//at.alicdn.com/t/font_2113109_7bz8s7j187s.eot?t=1601822003589#iefix")
format("embedded-opentype"),
/* IE6-IE8 */
url("data:application/x-font-woff2;charset=utf-8;base64,d09GMgABAAAAAAvoAAsAAAAAGiAAAAuZAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHEIGVgCFQAqkBJxvATYCJANICyYABCAFhG0HgSYbmxWjoo5yUtRkf3FgG9MauiEWkVzOXLAsfnHTsZAB+q/BIrKGB8a9Ybrw3hBox36eP/XPfcq970WoUioplWRgkta/nApmc8c3+a2TsgxStg86H0D3t9d4DZ22wkSYTnlzq+k5CJS/4IXc2MqcE8fz79/OrbcWFWoQcZRAgJln2pLog9T/6lIp4S87bLuEPAvKPJVDUke7ZUm+y7V8x68b8h6gucPUYWuYz/9+76q43rZ5SKKlaQlf7Mrkzt/+TAVIqiFxOP3fPzFvW0NCwxOHEGmRDLFgIV510hc2KuAjdgYIAC9cKrSe3dyrEQYhhFZ7DEaNQimYHFMEJ3ApKxagE1i4W0s9BwCb7c+PXsgMBqCwPdCCru3UqYOH+/IILQ5L1aRVQNQeBwBvqwHQAFIBMADdqfIPgHZhqo35tIaMSwAi+e/IgAAXIAEhoAiEBmICNmdHT//8NwI/fHlk+H+udkgQ3cMHRr2IoB2tHXt8ACWODIuCqPAIgZwCTQNTz+QfbwDCcmi+V60BAU56AiUIEARxIoCCDEQBCixICChQIKGggEBiQEEFYgMFHsQJBO2SDiAA6QYFOUgPEPRB+kGBBpkP4RjJG6CAQX6AJ1CDL4+IDx+s1SvEAtgO2A/ZCJS4YfYVFA4jpw9hhPFYHLzj8NCC4CaOIQbPhBIl4SLMGg1D2FvQhGsYRPir5DzPmCjc3ATLaoJVvFrOE14WH2LiFEJDWVpB21wBjldimxWMVUbMaJBCLScrJkydTBR8Awv030vZymuvhLMHX81TgGoxA7+CEwAi47fZQcElU2SMR6JSgCkg0sptqKXHgFYWnFCjKmlIfRTjSrW/TuaWhS7CbX39eUzV4y9L6999G1958gQCPThJv872osTAVjJL+5yyhSyygeBWxZHHREz0ZqSeMoM0sxhTHfoc6RYPqWRhZmvjIS1gXZxDxJQcfi8/0kZRdkr6RPLN9NxpjEUA+1VCInfhAZAt1ogh9GMTMZ6uGW1ko9JFBnrjGazoz3ZBY1VDK4iFqKSKYZ65Y1bvcvdym24pM5lAxOp6Q3hqFG5EifyNxujkSNSAU6XdjWUN51zOaSUAQk6FNvWI7XhUN6fVgdBA9sncOIUrld0PiGC5ELpR0Vfde8YuehIOlAt+eEbqBGWtBCKWK4wYGGYjpF4faRkEMMgr39yN13S52Y2kJiYAwohEcays7VqQBpMFBVzOg0iFqddSCwyPQsER69t4/6jB1OIAPtYJLzaxrlH5xPj63jJTcN5i35weGwzvEJTYpZ/PzcSV2sYu7Wdv+W8d+RbkVrYSGBgalO1NNCahC+FMf49Wf3rEZRzsYpn0ZoguZTwM8fQU8WdgYj8/+m5o7Y/+HenX0xAfFLk3XnL/iMSVKS+2upAi/o6VFYhgq+b/QfM6O9VgsYiJQYzC1veFYhUHXo2RreFuX+oB0HtKZxK9knkOQHYPjr2dtf3y50uPkr2gU9cb49RtEs3sbf7QWOTTaZQcmCjviHp2b3pk9+u/+6a+Hmipno0N8AvyLUmvqgWIeqlWRSCwP3MQqkMEyqDgQIH6FMEEhUX5E1LeMIud3ZjE3Khn606I/azC6JY6e5rgfzA4iIVMlEupru186/lWZ0cWV6pc4JoMqpDpvc66oioRt7+bpf52d1+sHNgPtV2jIdFC4RFSY0YSNVrYqqnneqSG5XsSg1j4Tz5etuGh7Ff1LfqyZipS36a7GSdpihOdev9n8Jy54ujWUbUn5S55svaUPdPHe/f+NUmdHHy/moy8RfcXFhX57EL7ZTLsX+0gcnnsJXNzsNw6l418/PEa9W11rc/3FiG3yS58uzn2bXyNnCYbcYK4cdnAt0LMA4kRI99DLdT7+t2KfJ/qSnOkjVA/765Lc8ZGuW1M64ivDYm2oefHGK32QmeRM6vcy9PaUlfBRA1uJ/bcMTlj7CzPM5r88SWVWoa8C15+e9k+DdGohbcTyc8fxbeIojFnVe6qRoXXTnaU7IN62W6bsrOr/MJDbms1Q4Bkier3qSbqffW73UetTSuLjTie7+1PzG8aqlbs2d+0vGqH4sxR3Qp6ysqT+3u3Vh9T1OdPQSVGAhWHqas2xbfTxrY6vjQlVlxGZXeOj/dLxJeDCfEs8xBy6UxbTKGz2KlzSYTRlrjyJ7W5kYI9Z0zumCxWEGhNwfjSSo6cOF1J54JXJ5uYiEvFZYClW9r8bRw9I1HTHs3vfsIF75mmLVdVV3R+2atbZhEcjcksZx9T1VAE1jb9cfjj+x+Qy7O3fS4QGuGP9JeVlbeVs49ay7l9WWu59VaXS2llBhRRz6XlNdQ3hMHV3FDVEL3JqIbqhtK0yRtIp2wotUmqlqKkKinacDVL9VLYFdVnS/uvqRs96uZ8ecKGTz9FeavGMQ3HK49PoDOXofw1Tqbl6qQbEDUzp6DxiA/U0zSwCcKM/6JSs/D6If8u2N1e9mXilwlPf5N4+8qiOIN76BWlfPGJT9UqS2esXLm8XhhcqhitT1ZNHvqoPSp5wtyarTPkqcaOKg0/NMdqLl3jU1V2LHIa8sOtBmvO06lIXXOswvxwescdI0RDXLNcp6eX/pEaN+gvnzy5+5c7P78xUu6SSvf0nE2L695W/+g7pA/05c3+bYge/d7DT7TvvuHqg6jLoq2nCW4h42ozzmjh2MTjDLX5qU9U587PHc1bSLpNbnG2im+IrSarqdhkMY1MGc2UJ0WPiN8NE9D4x6+6Yn+rrnGOB/OYP2/8qR2LldrliwsuuTc4WHRv5CJku78FL/OOVKfssXF/PqYp5vlrdQeYwdwr5quDORltczk8dcAykD6FCIPnRrw2mvzonr9ZyL+kOLxoMJf1C/xMT7rHMotwc10VgzlXzc13WBzzHtWC3otkNqg7zT4UGJufzrXzAjuNPbpHX3OJ+aWMH8KbssZkaRxRti1nvXOi+TpPzK7bGo+DH5gs7w8aF5YwM5rlJTrDHQoDyu6pyjYDWo+sst14f+VlrC85qkaknUzakWTtKu+eofCUMHxsauUTG/UUkbDeMireRrxsO3MUj2PJ0P9z7lQ3js0CW5RD83mO70i0SV+WoPeKon5vU2mjhyeexgl0O+s9PX00g3iqpIcCf2LSB54Pkr73ZEoR32R9k3Zt5yt1hroLv08Z68pxNcR27as3dNqPlGqE+1Ev/hP9jz/qggBFbdnHL6gUjQrVheN+W8nKj9PlEAzydIWeMC9wQ3NTy79WZXb/JA5+cO+o9G8cNAoqs34zduzAyIRfLYTS12b+4rD8bg5GVFykazmUjWfnstM4acJNY/8Cww5N4H6Z5MjmjeaXEod0+k+gb2d7XFoI3mb37vf3A8Dw0/RqOs923QFLoHIXwU+LgR+47ocLdIvrS/RHtBU+BZxf19RP5+aImio7pd9sAEBf1Buo2gev0dPC8qX3z1QP0bOZmeBsS9Y67/yGycPnc+8e/D+LSdovAozKQqim4LlLn1IAw/9X2buEUrX1PbZS2Kq71i4hFRQAnt8HMNxPhg/6jjeUFmiIQ6I3QJExAxoWq8popgKWIBtwsDLASzGqvkBnBoBukZxkKwEQtfOAonQf0NSeV2U03wcso+8ARx0a8Goz3aAgPl2TYyYj5PDpHaNNnRfpMnFa31J4bgwHJbbLI3GJpbhKt0Zrz6kjbmOR8hLWIh49pxbPjN1R0yTMnCqyMt+I5K2FpT3tEHObWjVhx4ghiIMme9cBu1hJxz9cTGKf/hYJnjUMzhn0J+Ajwor45ihDOmsJ1XPclRp0LB1nehGszWKch7InS1poJONIw6sS5EmfrkIsMddZoyLbYmGTtZfF8/7j220fw9Y3JC2vDYVoxCAWcUiGMCJ3nYIHNLYSqZAaaZAW6UC1oMozUynkZj42pNVlwlvb9M2zi0kLvUn/JTpK8BFzn94sNZCdh5xFb6QNHKk4YPH92JpA4JLVgaPTTSyiFAAA")
format("woff2"),
url("//at.alicdn.com/t/font_2113109_7bz8s7j187s.woff?t=1601822003589")
format("woff"),
url("//at.alicdn.com/t/font_2113109_7bz8s7j187s.ttf?t=1601822003589")
format("truetype"),
/* chrome, firefox, opera, Safari, Android, iOS 4.2+ */
url("//at.alicdn.com/t/font_2113109_7bz8s7j187s.svg?t=1601822003589#iconfont")
format("svg"); /* iOS 4.1- */
}
.iconfont {
font-family: "iconfont" !important;
font-size: 16px;
font-style: normal;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.icon-file:before {
content: "\e61a";
}
.icon-compressed-file:before {
content: "\e61b";
color: rgb(244, 196, 70);
}
.icon-xml:before {
content: "\e66e";
color: #fc7b24;
}
.icon-audio:before {
content: "\e8a4";
color: rgb(55, 159, 211);
}
.icon-text:before {
content: "\e60d";
color: rgb(249, 202, 6);
}
.icon-video:before {
content: "\e609";
color: rgb(128, 149, 255);
}
.icon-zip:before {
content: "\e60b";
}
.icon-excel:before {
content: "\e6d6";
color: rgb(16, 123, 15);
}
.icon-pdf:before {
content: "\e64f";
color: rgb(220, 46, 27);
}
.icon-ppt:before {
content: "\e642";
color: rgb(210, 70, 37);
}
.icon-html:before {
content: "\e667";
color: rgb(247, 98, 44);
}
.icon-psd:before {
content: "\e66a";
}
.icon-rtf:before {
content: "\e66b";
}
.icon-image:before {
content: "\e606";
color: rgb(18, 150, 219);
}
.icon-doc:before {
content: "\e623";
color: rgb(13, 71, 161);
}
.icon-grid:before {
content: "\e6ef";
}
.icon-list:before {
content: "\e67a";
}
This diff is collapsed.
<template>
<div class="app-container">
<el-form :inline="true" :model="form" size="mini">
<el-form-item label="设备">
<el-select
v-model="watch_id"
filterable
placeholder="请输入设备名称"
@change="onChange"
>
<el-option
v-for="(item, index) in watchs"
:key="index"
:label="item.imei"
:value="item.id"
></el-option>
</el-select>
</el-form-item>
<el-form-item
><el-button type="primary" @click="onSubmit"
>查询</el-button
></el-form-item
>
<el-form-item><el-button @click="onReset">重置</el-button></el-form-item>
</el-form>
<LineChart :chartData="evm" :dataList="evmList"></LineChart>
<LvglChart :chartData="lvgl"></LvglChart>
<ImageChart :chartData="image"></ImageChart>
</div>
</template>
<script>
import { getWatchList, getMonitorData } from "@/api/index";
import LineChart from "./components/EvmChart";
import LvglChart from "./components/LvglChart";
import ImageChart from "./components/ImageChart";
import { wsNotify } from "@/utils/eventBus.js";
export default {
name: "AppChart",
data() {
return {
socket: null,
watchs: [],
watch_id: null,
device: null,
devices: {},
isLoading: false,
evm: {},
evmList: [],
lvgl: {},
lvglList: [],
image: [],
imageList: [],
form: {
start: null,
end: null,
},
};
},
components: {
LineChart,
LvglChart,
ImageChart,
},
methods: {
sendMsg() {
this.socket.send("hello,world");
},
fetchData() {
this.isLoading = true;
getWatchList()
.then((res) => {
if (res.code == 200) this.watchs = res.data;
})
.catch((err) => {
this.$message.warning(err.msg);
})
.finally(() => {
this.isLoading = false;
});
},
queryData() {
let params = {
watch: this.watch_id,
};
if (this.value2 && this.value2.length) {
if (this.value2.length > 1) {
params.start = Math.ceil(this.value2[0] / 1000);
params.end = Math.ceil(this.value2[1] / 1000);
} else {
params.start = Math.ceil(this.value2[0] / 1000);
}
}
getMonitorData(params)
.then((res) => {
if (res.type == "object") {
this.evmList = res.data.evm
this.lvglList = res.data.lvgl
this.imageList = res.data.image
} else {
if (params.category == "evm") this.evmList = res.data
else if (params.category == "lvgl") this.lvglList = res.data
else if (params.category == "image") this.imageList = res.data
}
})
.catch((err) => {
this.$message.warning(err.msg);
});
},
onChange(res) {
var t = this.watchs.find((item) => {
return item.id == res;
});
if (t) this.device = t.imei;
this.processData();
},
onSubmit() {
this.queryData();
},
onReset(formName) {
this.$refs[formName].resetFields();
this.fetchData();
},
handleMessage(message) {
if (!this.device) this.device = message.imei;
this.devices[message.imei] = message;
this.processData()
},
processData() {
this.evm = this.devices[this.device].evm;
this.lvgl = this.devices[this.device].lvgl;
this.image = this.devices[this.device].image;
}
},
mounted() {},
created() {
this.socket = wsNotify;
wsNotify.eventBus.$on("open", (message) => {
this.sendMsg();
this.$nextTick(() => {
console.log(message);
});
});
wsNotify.eventBus.$on("close", (message) => {
this.$nextTick(() => {
console.log(message);
});
});
wsNotify.eventBus.$on("message", (message) => {
this.$nextTick(() => {
console.log(message);
this.handleMessage(message);
});
});
this.fetchData();
},
};
</script>
<style lang="scss" scoped>
.app-container {
& > div.page-wrapper {
margin: 10px 0px;
}
#chart1 {
width: 100%;
height: 300px;
}
}
</style>
<template>
<div :class="className" :style="{ height: height, width: width }" />
</template>
<script>
import * as echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme
import resize from "./mixins/resize";
import { getDateTimeString } from "@/utils/utils";
// function randomData() {
// now = new Date(+now + oneDay);
// value = value + Math.random() * 21 - 10;
// return {
// name: "EVM",
// value: [
// [now.getFullYear(), now.getMonth() + 1, now.getDate()].join("/") +
// " " +
// [now.getHours(), now.getMinutes() + 1, now.getSeconds()].join(":"),
// Math.round(value),
// ],
// };
// }
// const dataList = [];
// let now = +new Date(1997, 9, 3);
// const oneDay = 24 * 3600 * 1000;
// var value = Math.random() * 1000;
// for (var i = 0; i < 1000; i++) {
// dataList.push(randomData());
// }
const seriesData = {
heap_total_size: [],
heap_used_size: [],
stack_total_size: [],
stack_used_size: [],
};
export default {
mixins: [resize],
props: {
className: {
type: String,
default: "chart",
},
width: {
type: String,
default: "100%",
},
height: {
type: String,
default: "350px",
},
autoResize: {
type: Boolean,
default: true,
},
chartData: {
type: Object,
required: true,
},
},
data() {
return {
loading: null,
chart: null,
timer: null,
series: [
{
name: "heap_total_size",
type: "line",
max: "dataMax",
showSymbol: false,
emphasis: {
scale: false,
focus: "series",
blurScope: "coordinateSystem",
},
data: seriesData.heap_total_size,
},
{
name: "heap_used_size",
type: "line",
max: "dataMax",
showSymbol: false,
emphasis: {
focus: "series",
blurScope: "coordinateSystem",
},
data: seriesData.heap_used_size,
},
{
name: "stack_total_size",
type: "line",
max: "dataMax",
showSymbol: false,
emphasis: {
focus: "series",
blurScope: "coordinateSystem",
},
data: seriesData.stack_total_size,
},
{
name: "stack_used_size",
type: "line",
max: "dataMax",
showSymbol: false,
emphasis: {
focus: "series",
blurScope: "coordinateSystem",
},
data: seriesData.stack_used_size,
},
],
legendData: [
"heap_total_size",
"heap_used_size",
"stack_total_size",
"stack_used_size",
],
};
},
watch: {
chartData: {
deep: true,
handler(val) {
this.handleMessage(val);
},
},
},
mounted() {
// this.timer = setInterval(() => {
// for (var i = 0; i < 5; i++) {
// dataList.shift();
// dataList.push(randomData());
// }
// if (!this.chart) {
// clearInterval(this.timer);
// }
// this.chart &&
// this.chart.setOption({
// series: [
// {
// data: dataList,
// },
// ],
// });
// }, 1000);
// this.loading = this.$loading({
// lock: true,
// text: "Loading",
// spinner: "el-icon-loading",
// background: "rgba(0, 0, 0, 0.7)",
// });
// setTimeout(() => {
// this.loading.close()
// }, 2000)
this.$nextTick(() => {
this.initChart();
});
},
beforeDestroy() {
if (!this.chart) {
return;
}
this.chart.dispose();
this.chart = null;
},
methods: {
handleData(data) {
// 关闭从WebSocket接收数据
// 重置所有数据
Object.keys(seriesData).forEach((key) => {
seriesData[key] = [];
});
// this.series.forEach((item) => {
// item.data = [];
// });
// this.chart.setOption({ series: this.series });
data.forEach((item) => {
this.handleMessage(item);
});
},
handleMessage(data) {
// 这里面应该增加一个数组长度判断,当超过了多少个之后,弹出数组第一项,防止数组内存溢出
// seriesData[k].shift()
Object.keys(data).forEach((k) => {
var t = getDateTimeString(new Date());
if (k == "timestamp") t = data[k];
if (this.legendData.includes(k)) {
seriesData[k].push({
name: k,
value: [t, data[k]],
});
}
});
this.$nextTick(() => {
this.chart &&
this.chart.setOption({
series: this.series,
});
});
},
initChart() {
this.chart = echarts.init(this.$el, "macarons");
this.setOptions();
},
setOptions() {
this.chart.setOption({
title: {
text: "EVM",
},
xAxis: {
type: "time",
splitLine: {
show: false,
},
// data: xAxisTitle,
// boundaryGap: false,
// axisTick: {
// show: false,
// },
axisLabel: {
formatter: "{hh}:{mm}:{ss}",
},
},
yAxis: {
type: "value",
scale: true,
boundaryGap: [0, "100%"],
splitLine: {
show: false,
},
},
// grid: {
// left: 10,
// right: 10,
// bottom: 20,
// top: 30,
// containLabel: true,
// },
tooltip: {
trigger: "axis",
axisPointer: {
type: "cross",
animation: false,
},
// formatter: function (params) {
// params = params[0];
// console.log(params);
// var date = new Date(params.name);
// return (
// date.getDate() +
// "/" +
// (date.getMonth() + 1) +
// "/" +
// date.getFullYear() +
// " : " +
// params.value[1]
// );
// },
padding: [5, 10],
},
legend: {
data: this.legendData,
},
series: this.series,
});
},
},
};
</script>
<template>
<div :class="className" :style="{ height: height, width: width }" />
</template>
<script>
import * as echarts from "echarts";
require("echarts/theme/macarons");
import resize from "./mixins/resize";
const seriesData = {
heap_total_size: [],
heap_used_size: [],
stack_total_size: [],
stack_used_size: [],
};
export default {
mixins: [resize],
props: {
className: {
type: String,
default: "chart",
},
width: {
type: String,
default: "100%",
},
height: {
type: String,
default: "350px",
},
autoResize: {
type: Boolean,
default: true,
},
dataList: {
type: Array,
required: false,
default: () => [],
},
},
data() {
return {
loading: null,
chart: null,
series: [
{
name: "heap_total_size",
type: "line",
max: "dataMax",
showSymbol: false,
emphasis: {
scale: false,
focus: "series",
blurScope: "coordinateSystem",
},
data: seriesData.heap_total_size,
},
{
name: "heap_used_size",
type: "line",
max: "dataMax",
showSymbol: false,
emphasis: {
focus: "series",
blurScope: "coordinateSystem",
},
data: seriesData.heap_used_size,
},
{
name: "stack_total_size",
type: "line",
max: "dataMax",
showSymbol: false,
emphasis: {
focus: "series",
blurScope: "coordinateSystem",
},
data: seriesData.stack_total_size,
},
{
name: "stack_used_size",
type: "line",
max: "dataMax",
showSymbol: false,
emphasis: {
focus: "series",
blurScope: "coordinateSystem",
},
data: seriesData.stack_used_size,
},
],
legendData: [
"heap_total_size",
"heap_used_size",
"stack_total_size",
"stack_used_size",
],
};
},
watch: {
dataList: {
deep: true,
handler(val) {
if (val.length > 0) this.handleData(val);
},
},
},
mounted() {
this.$nextTick(() => {
this.initChart();
});
},
beforeDestroy() {
if (!this.chart) {
return;
}
this.chart.dispose();
this.chart = null;
},
methods: {
handleData(data) {
Object.keys(seriesData).forEach((key) => {
seriesData[key] = [];
});
// this.series.forEach((item) => {
// item.data = [];
// });
// this.chart.setOption({ series: this.series });
data.forEach((item) => {
this.handleMessage(item);
});
},
handleMessage(data) {
Object.keys(data).forEach((k) => {
if (this.legendData.includes(k)) {
seriesData[k].push({
name: k,
value: [data.timestamp, data[k]],
});
}
});
this.$nextTick(() => {
this.chart &&
this.chart.setOption({
series: this.series,
});
});
},
initChart() {
this.chart = echarts.init(this.$el, "macarons");
this.setOptions();
},
setOptions() {
this.chart.setOption({
title: {
text: "EVM",
},
xAxis: {
type: "time",
splitLine: {
show: false,
},
// data: xAxisTitle,
// boundaryGap: false,
// axisTick: {
// show: false,
// },
axisLabel: {
formatter: "{hh}:{mm}:{ss}",
},
},
yAxis: {
type: "value",
scale: true,
boundaryGap: [0, "100%"],
splitLine: {
show: false,
},
},
// grid: {
// left: 10,
// right: 10,
// bottom: 20,
// top: 30,
// containLabel: true,
// },
tooltip: {
trigger: "axis",
axisPointer: {
type: "cross",
animation: false,
},
// formatter: function (params) {
// params = params[0];
// console.log(params);
// var date = new Date(params.name);
// return (
// date.getDate() +
// "/" +
// (date.getMonth() + 1) +
// "/" +
// date.getFullYear() +
// " : " +
// params.value[1]
// );
// },
padding: [5, 10],
},
legend: {
data: this.legendData,
},
series: this.series,
});
},
},
};
</script>
<template>
<div :class="className" :style="{ height: height, width: width }" />
</template>
<script>
import * as echarts from "echarts";
require("echarts/theme/macarons");
import resize from "./mixins/resize";
// import { getDateTimeString } from "@/utils/utils";
const seriesData = {
heap_total_size: [],
heap_used_size: [],
stack_total_size: [],
stack_used_size: [],
};
var data = [
["2000-06-05", 116],
["2000-06-06", 129],
["2000-06-07", 135],
["2000-06-08", 86],
["2000-06-09", 73],
["2000-06-10", 85],
["2000-06-11", 73],
["2000-06-12", 68],
["2000-06-13", 92],
["2000-06-14", 130],
["2000-06-15", 245],
["2000-06-16", 139],
["2000-06-17", 115],
["2000-06-18", 111],
["2000-06-19", 309],
["2000-06-20", 206],
["2000-06-21", 137],
["2000-06-22", 128],
["2000-06-23", 85],
["2000-06-24", 94],
["2000-06-25", 71],
["2000-06-26", 106],
["2000-06-27", 84],
["2000-06-28", 93],
["2000-06-29", 85],
["2000-06-30", 73],
["2000-07-01", 83],
["2000-07-02", 125],
["2000-07-03", 107],
["2000-07-04", 82],
["2000-07-05", 44],
["2000-07-06", 72],
["2000-07-07", 106],
["2000-07-08", 107],
["2000-07-09", 66],
["2000-07-10", 91],
["2000-07-11", 92],
["2000-07-12", 113],
["2000-07-13", 107],
["2000-07-14", 131],
["2000-07-15", 111],
["2000-07-16", 64],
["2000-07-17", 69],
["2000-07-18", 88],
["2000-07-19", 77],
["2000-07-20", 83],
["2000-07-21", 111],
["2000-07-22", 57],
["2000-07-23", 55],
["2000-07-24", 60],
];
var dateList = data.map(function (item) {
return item[0];
});
var valueList = data.map(function (item) {
return item[1];
});
export default {
mixins: [resize],
props: {
className: {
type: String,
default: "chart",
},
width: {
type: String,
default: "100%",
},
height: {
type: String,
default: "600px",
},
autoResize: {
type: Boolean,
default: true,
},
chartData: {
type: Array,
required: true,
},
},
data() {
return {
chart: null,
series: [
{
name: "heap_total_size",
type: "line",
showSymbol: false,
emphasis: {
scale: false,
focus: "series",
blurScope: "coordinateSystem",
},
data: seriesData.heap_total_size,
},
{
name: "heap_used_size",
type: "line",
showSymbol: false,
emphasis: {
focus: "series",
blurScope: "coordinateSystem",
},
data: seriesData.heap_used_size,
},
{
name: "stack_total_size",
type: "line",
showSymbol: false,
emphasis: {
focus: "series",
blurScope: "coordinateSystem",
},
data: seriesData.stack_total_size,
},
{
name: "stack_used_size",
type: "line",
showSymbol: false,
emphasis: {
focus: "series",
blurScope: "coordinateSystem",
},
data: seriesData.stack_used_size,
},
],
legendData: [
"heap_total_size",
"heap_used_size",
"stack_total_size",
"stack_used_size",
],
options: {
tooltip: {
trigger: "axis",
},
visualMap: [],
title: [],
xAxis: [],
yAxis: [],
grid: [],
series: []
},
};
},
watch: {
chartData: {
deep: true,
handler(val) {
this.handleMessage(val);
},
},
},
mounted() {
this.$nextTick(() => {
this.initChart();
});
},
beforeDestroy() {
if (!this.chart) {
return;
}
this.chart.dispose();
this.chart = null;
},
methods: {
handleMessage(data) {
console.log(data);
// Object.keys(data).forEach((k) => {
// if (this.legendData.includes(k))
// seriesData[k].push({
// name: k,
// value: [getDateTimeString(new Date()), data[k]],
// });
// });
this.$nextTick(() => {
// this.chart &&
// this.chart.setOption({
// series: this.series,
// });
});
},
initChart() {
this.chart = echarts.init(this.$el, "macarons");
this.setOptions();
},
initOption() {},
setOptions() {
this.chart.setOption({
// Make gradient line here
visualMap: [
{
show: false,
type: "continuous",
seriesIndex: 0,
min: 0,
max: 400,
},
{
show: false,
type: "continuous",
seriesIndex: 1,
dimension: 0,
min: 0,
max: dateList.length - 1,
},
],
title: [
{
left: "center",
text: "Gradient along the y axis",
},
{
top: "300px",
left: "center",
text: "Gradient along the x axis",
},
],
tooltip: {
trigger: "axis",
},
xAxis: [
{
data: dateList,
gridIndex: 0,
},
{
data: dateList,
gridIndex: 1,
},
],
yAxis: [
{
gridIndex: 0,
},
{
gridIndex: 1,
},
],
grid: [
{
bottom: "350px",
},
{
top: "350px",
},
],
series: [
{
type: "line",
showSymbol: false,
data: valueList,
xAxisIndex: 0,
yAxisIndex: 0,
},
{
type: "line",
showSymbol: false,
data: valueList,
xAxisIndex: 1,
yAxisIndex: 1,
},
],
});
},
},
};
</script>
<template>
<div :class="className" :style="{height:height,width:width}" />
</template>
<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from '../../dashboard/components/mixins/resize'
export default {
mixins: [resize],
props: {
className: {
type: String,
default: 'chart'
},
width: {
type: String,
default: '100%'
},
height: {
type: String,
default: '350px'
},
autoResize: {
type: Boolean,
default: true
},
chartData: {
type: Object,
required: true
}
},
data() {
return {
chart: null
}
},
watch: {
chartData: {
deep: true,
handler(val) {
this.setOptions(val)
}
}
},
mounted() {
this.$nextTick(() => {
this.initChart()
})
},
beforeDestroy() {
if (!this.chart) {
return
}
this.chart.dispose()
this.chart = null
},
methods: {
initChart() {
this.chart = echarts.init(this.$el, 'macarons')
this.setOptions(this.chartData)
},
setOptions({ expectedData, actualData } = {}) {
this.chart.setOption({
xAxis: {
type: 'category',
data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月','9月','10月','11月','12月'],
boundaryGap: false,
axisTick: {
show: false
}
},
grid: {
left: 10,
right: 10,
bottom: 20,
top: 30,
containLabel: true
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross'
},
padding: [5, 10]
},
yAxis: {
axisTick: {
show: false
}
},
legend: {
data: ['应收款', '实收款']
},
series: [{
name: '应收款', itemStyle: {
normal: {
color: '#FF005A',
lineStyle: {
color: '#FF005A',
width: 2
}
}
},
smooth: true,
type: 'line',
data: expectedData,
animationDuration: 2800,
animationEasing: 'cubicInOut'
},
{
name: '实收款',
smooth: true,
type: 'line',
itemStyle: {
normal: {
color: '#3888fa',
lineStyle: {
color: '#3888fa',
width: 2
},
areaStyle: {
color: '#f3f8ff'
}
}
},
data: actualData,
animationDuration: 2800,
animationEasing: 'quadraticOut'
}]
})
}
}
}
</script>
<template>
<div :class="className" :style="{ height: height, width: width }" />
</template>
<script>
import * as echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme
import resize from "./mixins/resize";
import { getDateTimeString } from "@/utils/utils";
const seriesData = {
frag_pct: [],
free_biggest_size: [],
free_cnt: [],
free_size: [],
total_size: [],
used_cnt: [],
used_pct: [],
};
export default {
mixins: [resize],
props: {
className: {
type: String,
default: "chart",
},
width: {
type: String,
default: "100%",
},
height: {
type: String,
default: "350px",
},
autoResize: {
type: Boolean,
default: true,
},
chartData: {
type: Object,
required: true,
},
dataList: {
type: Array,
required: false,
default: () => [],
},
},
data() {
return {
chart: null,
series: [
{
name: "frag_pct",
type: "line",
showSymbol: false,
emphasis: {
scale: false,
focus: "series",
blurScope: "coordinateSystem",
},
data: seriesData.frag_pct,
},
{
name: "free_biggest_size",
type: "line",
showSymbol: false,
emphasis: {
focus: "series",
blurScope: "coordinateSystem",
},
data: seriesData.free_biggest_size,
},
{
name: "free_cnt",
type: "line",
showSymbol: false,
emphasis: {
focus: "series",
blurScope: "coordinateSystem",
},
data: seriesData.free_cnt,
},
{
name: "free_size",
type: "line",
showSymbol: false,
emphasis: {
focus: "series",
blurScope: "coordinateSystem",
},
data: seriesData.free_size,
},
{
name: "total_size",
type: "line",
showSymbol: false,
emphasis: {
focus: "series",
blurScope: "coordinateSystem",
},
data: seriesData.total_size,
},
{
name: "used_cnt",
type: "line",
showSymbol: false,
emphasis: {
focus: "series",
blurScope: "coordinateSystem",
},
data: seriesData.used_cnt,
},
{
name: "used_pctused_pct",
type: "line",
showSymbol: false,
emphasis: {
focus: "series",
blurScope: "coordinateSystem",
},
data: seriesData.used_pctused_pct,
},
],
legendData: [
"frag_pct",
"free_biggest_size",
"free_cnt",
"free_size",
"total_size",
"used_cnt",
"used_pctused_pct",
],
};
},
watch: {
chartData: {
deep: true,
handler(val) {
this.handleMessage(val);
},
},
dataList: {
deep: true,
handler(val) {
if (val.length > 0) this.handleData(val);
},
},
},
mounted() {
this.$nextTick(() => {
this.initChart();
});
},
beforeDestroy() {
if (!this.chart) {
return;
}
this.chart.dispose();
this.chart = null;
},
methods: {
handleData(data) {
Object.keys(seriesData).forEach(key => {
seriesData[key] = []
});
this.series.forEach(item => {
item.data = []
});
this.chart.setOption({ series: this.series });
data.forEach((item) => {
this.handleMessage(item);
});
},
handleMessage(data) {
Object.keys(data).forEach((k) => {
var t = getDateTimeString(new Date());
if (k == "timestamp") t = data[k];
if (this.legendData.includes(k))
seriesData[k].push({
name: k,
value: [t, data[k]],
});
});
this.$nextTick(() => {
this.chart &&
this.chart.setOption({
series: this.series,
});
});
},
initChart() {
this.chart = echarts.init(this.$el, "macarons");
this.setOptions();
},
setOptions() {
this.chart.setOption({
title: {
text: "LVGL",
},
xAxis: {
type: "time",
splitLine: {
show: false,
},
axisLabel: {
formatter: "{hh}:{mm}:{ss}",
},
},
yAxis: {
type: "value",
boundaryGap: [0, "100%"],
splitLine: {
show: false,
},
},
tooltip: {
trigger: "axis",
axisPointer: {
type: "cross",
animation: false,
},
padding: [5, 10],
},
legend: {
data: this.legendData,
},
series: this.series,
});
},
},
};
</script>
<template>
<div :class="className" :style="{ height: height, width: width }" />
</template>
<script>
import * as echarts from "echarts";
require("echarts/theme/macarons");
import resize from "./mixins/resize";
import { getDateTimeString } from "@/utils/utils";
const seriesData = {
frag_pct: [],
free_biggest_size: [],
free_cnt: [],
free_size: [],
total_size: [],
used_cnt: [],
used_pct: [],
};
export default {
mixins: [resize],
props: {
className: {
type: String,
default: "chart",
},
width: {
type: String,
default: "100%",
},
height: {
type: String,
default: "350px",
},
autoResize: {
type: Boolean,
default: true,
},
dataList: {
type: Array,
required: false,
default: () => [],
},
},
data() {
return {
chart: null,
series: [
{
name: "frag_pct",
type: "line",
showSymbol: false,
emphasis: {
scale: false,
focus: "series",
blurScope: "coordinateSystem",
},
data: seriesData.frag_pct,
},
{
name: "free_biggest_size",
type: "line",
showSymbol: false,
emphasis: {
focus: "series",
blurScope: "coordinateSystem",
},
data: seriesData.free_biggest_size,
},
{
name: "free_cnt",
type: "line",
showSymbol: false,
emphasis: {
focus: "series",
blurScope: "coordinateSystem",
},
data: seriesData.free_cnt,
},
{
name: "free_size",
type: "line",
showSymbol: false,
emphasis: {
focus: "series",
blurScope: "coordinateSystem",
},
data: seriesData.free_size,
},
{
name: "total_size",
type: "line",
showSymbol: false,
emphasis: {
focus: "series",
blurScope: "coordinateSystem",
},
data: seriesData.total_size,
},
{
name: "used_cnt",
type: "line",
showSymbol: false,
emphasis: {
focus: "series",
blurScope: "coordinateSystem",
},
data: seriesData.used_cnt,
},
{
name: "used_pctused_pct",
type: "line",
showSymbol: false,
emphasis: {
focus: "series",
blurScope: "coordinateSystem",
},
data: seriesData.used_pctused_pct,
},
],
legendData: [
"frag_pct",
"free_biggest_size",
"free_cnt",
"free_size",
"total_size",
"used_cnt",
"used_pctused_pct",
],
};
},
watch: {
dataList: {
deep: true,
handler(val) {
if (val.length > 0) this.handleData(val);
},
},
},
mounted() {
this.$nextTick(() => {
this.initChart();
});
},
beforeDestroy() {
if (!this.chart) {
return;
}
this.chart.dispose();
this.chart = null;
},
methods: {
handleData(data) {
Object.keys(seriesData).forEach(key => {
seriesData[key] = []
});
this.series.forEach(item => {
item.data = []
});
this.chart.setOption({ series: this.series });
data.forEach((item) => {
this.handleMessage(item);
});
},
handleMessage(data) {
Object.keys(data).forEach((k) => {
var t = getDateTimeString(new Date());
if (k == "timestamp") t = data[k];
if (this.legendData.includes(k))
seriesData[k].push({
name: k,
value: [t, data[k]],
});
});
this.$nextTick(() => {
this.chart &&
this.chart.setOption({
series: this.series,
});
});
},
initChart() {
this.chart = echarts.init(this.$el, "macarons");
this.setOptions();
},
setOptions() {
this.chart.setOption({
title: {
text: "LVGL",
},
xAxis: {
type: "time",
splitLine: {
show: false,
},
axisLabel: {
formatter: "{hh}:{mm}:{ss}",
},
},
yAxis: {
type: "value",
boundaryGap: [0, "100%"],
splitLine: {
show: false,
},
},
tooltip: {
trigger: "axis",
axisPointer: {
type: "cross",
animation: false,
},
padding: [5, 10],
},
legend: {
data: this.legendData,
},
series: this.series,
});
},
},
};
</script>
<template>
<div class="app-container">
<el-form :inline="true" :model="form" size="mini">
<el-form-item label="设备">
<el-select
v-model="watch_id"
filterable
placeholder="请输入设备名称"
@change="onChange"
>
<el-option
v-for="(item, index) in watchs"
:key="index"
:label="item.imei"
:value="item.id"
></el-option>
</el-select>
</el-form-item>
<el-form-item label="起止时间">
<el-date-picker
v-model="value2"
type="datetimerange"
:unlink-panels="true"
:picker-options="pickerOptions"
value-format="timestamp"
range-separator="至"
start-placeholder="开始日期"
end-placeholder="结束日期"
align="right"
>
</el-date-picker>
</el-form-item>
<el-form-item
><el-button type="primary" @click="onSubmit"
>查询</el-button
></el-form-item
>
<el-form-item><el-button @click="onReset">重置</el-button></el-form-item>
</el-form>
<EvmHistoryChart :dataList="[]"></EvmHistoryChart>
<LvglHistoryChart :dataList="[]"></LvglHistoryChart>
</div>
</template>
<script>
import { getWatchList, getMonitorData } from "@/api/index";
import EvmHistoryChart from "./components/EvmHistoryChart";
import LvglHistoryChart from "./components/LvglHistoryChart";
export default {
name: "AppHistoryChart",
data() {
return {
list: [],
watch_id: null,
isLoading: false,
watchs: [],
evmList: [],
lvglList: [],
imageList: [],
form: {
start: null,
end: null,
},
pickerOptions: {
shortcuts: [
{
text: "最近一周",
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
picker.$emit("pick", [start, end]);
},
},
{
text: "最近一个月",
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
picker.$emit("pick", [start, end]);
},
},
{
text: "最近三个月",
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
picker.$emit("pick", [start, end]);
},
},
],
},
value2: "",
};
},
components: {
EvmHistoryChart,
LvglHistoryChart,
},
methods: {
fetchData() {
let params = {
watch: this.watch_id,
};
if (this.value2 && this.value2.length) {
if (this.value2.length > 1) {
params.start = Math.ceil(this.value2[0] / 1000);
params.end = Math.ceil(this.value2[1] / 1000);
} else {
params.start = Math.ceil(this.value2[0] / 1000);
}
}
getMonitorData(params)
.then((res) => {
if (res.type == "object") {
this.evmList = res.data.evm;
this.lvglList = res.data.lvgl;
this.imageList = res.data.image;
} else {
if (params.category == "evm") this.evmList = res.data;
else if (params.category == "lvgl") this.lvglList = res.data;
else if (params.category == "image") this.imageList = res.data;
}
})
.catch((err) => {
this.$message.warning(err.msg);
});
},
fetchSelectData() {
this.isLoading = true;
getWatchList()
.then((res) => {
if (res.code == 200) this.watchs = res.data;
console.log(this.watchs);
})
.catch((err) => {
this.$message.warning(err.msg);
})
.finally(() => {
this.isLoading = false;
});
},
onChange() {
this.fetchData();
},
onAdd() {},
onSubmit() {
this.fetchData();
},
onReset(formName) {
this.$refs[formName].resetFields();
this.fetchData();
},
},
mounted() {},
created() {
this.fetchData();
this.fetchSelectData();
},
};
</script>
<style lang="scss" scoped>
.app-container {
& > div.page-wrapper {
margin: 10px 0px;
}
}
</style>
<template>
<div class="app-container">
<div>
<el-select size="mini" v-model="device" @change="onSelectChange" placeholder="请选择设备">
<el-option v-for="(item, index) in deviceList" :key="index" :label="item" :value="item"></el-option>
<el-select
size="mini"
v-model="device"
@change="onSelectChange"
placeholder="请选择设备"
>
<el-option
v-for="(item, index) in deviceList"
:key="index"
:label="item"
:value="item"
></el-option>
</el-select>
</div>
<h2>REQUEST</h2>
......@@ -44,18 +54,10 @@
fit
highlight-current-row
>
<el-table-column
label="imei"
min-width="180"
show-overflow-tooltip
>
<el-table-column label="imei" min-width="180" show-overflow-tooltip>
<template slot-scope="scope">{{ scope.row.imei }}</template>
</el-table-column>
<el-table-column
label="free_size"
min-width="180"
show-overflow-tooltip
>
<el-table-column label="free_size" min-width="180" show-overflow-tooltip>
<template slot-scope="scope">{{ scope.row.free_size }}(KB)</template>
</el-table-column>
</el-table>
......@@ -69,11 +71,7 @@
fit
highlight-current-row
>
<el-table-column
label="total_size"
min-width="180"
show-overflow-tooltip
>
<el-table-column label="total_size" min-width="180" show-overflow-tooltip>
<template slot-scope="scope">{{ scope.row.total_size }}(KB)</template>
</el-table-column>
<el-table-column
......@@ -82,35 +80,21 @@
min-width="180"
show-overflow-tooltip
></el-table-column>
<el-table-column
label="free_size"
min-width="180"
show-overflow-tooltip
>
<el-table-column label="free_size" min-width="180" show-overflow-tooltip>
<template slot-scope="scope">{{ scope.row.free_size }}(KB)</template>
</el-table-column>
<el-table-column
label="free_biggest_size"
min-width="180"
<el-table-column label="free_biggest_size" min-width="180">
<template slot-scope="scope"
>{{ scope.row.free_biggest_size }}(KB)</template
>
<template slot-scope="scope">{{ scope.row.free_biggest_size }}(KB)</template>
</el-table-column>
<el-table-column
label="used_cnt"
min-width="180"
>
<el-table-column label="used_cnt" min-width="180">
<template slot-scope="scope">{{ scope.row.used_cnt }}</template>
</el-table-column>
<el-table-column
label="used_pct"
min-width="180"
>
<el-table-column label="used_pct" min-width="180">
<template slot-scope="scope">{{ scope.row.used_pct }}(%)</template>
</el-table-column>
<el-table-column
label="frag_pct"
min-width="180"
>
<el-table-column label="frag_pct" min-width="180">
<template slot-scope="scope">{{ scope.row.frag_pct }}(%)</template>
</el-table-column>
</el-table>
......@@ -143,35 +127,45 @@
min-width="180"
show-overflow-tooltip
>
<template slot-scope="scope">{{ scope.row.heap_map_size }}(KB)</template>
<template slot-scope="scope"
>{{ scope.row.heap_map_size }}(KB)</template
>
</el-table-column>
<el-table-column
label="heap_total_size"
min-width="180"
show-overflow-tooltip
>
<template slot-scope="scope">{{ scope.row.heap_total_size }}(KB)</template>
<template slot-scope="scope"
>{{ scope.row.heap_total_size }}(KB)</template
>
</el-table-column>
<el-table-column
label="heap_used_size"
min-width="180"
show-overflow-tooltip
>
<template slot-scope="scope">{{ scope.row.heap_used_size }}(KB)</template>
<template slot-scope="scope"
>{{ scope.row.heap_used_size }}(KB)</template
>
</el-table-column>
<el-table-column
label="stack_total_size"
min-width="180"
show-overflow-tooltip
>
<template slot-scope="scope">{{ scope.row.stack_total_size }}(KB)</template>
<template slot-scope="scope"
>{{ scope.row.stack_total_size }}(KB)</template
>
</el-table-column>
<el-table-column
label="stack_used_size"
min-width="180"
show-overflow-tooltip
>
<template slot-scope="scope">{{ scope.row.stack_used_size }}(KB)</template>
<template slot-scope="scope"
>{{ scope.row.stack_used_size }}(KB)</template
>
</el-table-column>
</el-table>
<h2>APP</h2>
......@@ -190,11 +184,7 @@
min-width="180"
show-overflow-tooltip
></el-table-column>
<el-table-column
label="length"
min-width="180"
show-overflow-tooltip
>
<el-table-column label="length" min-width="180" show-overflow-tooltip>
<template slot-scope="scope">{{ scope.row.length }}(KB)</template>
</el-table-column>
<el-table-column
......@@ -202,7 +192,9 @@
min-width="180"
show-overflow-tooltip
>
<template slot-scope="scope">{{ scope.row.png_file_size }}(KB)</template>
<template slot-scope="scope"
>{{ scope.row.png_file_size }}(KB)</template
>
</el-table-column>
<el-table-column
prop="png_total_count"
......@@ -215,12 +207,15 @@
min-width="180"
show-overflow-tooltip
>
<template slot-scope="scope">{{ scope.row.png_uncompressed_size }}(KB)</template>
<template slot-scope="scope"
>{{ scope.row.png_uncompressed_size }}(KB)</template
>
</el-table-column>
</el-table>
</div>
</template>
<script>
import { wsNotify } from "@/utils/eventBus.js";
export default {
name: "Monitor",
data() {
......@@ -235,23 +230,27 @@ export default {
request: [],
socket: null,
form: {
system: ['free_size'],
lvgl: ['total_size', 'free_size', 'free_biggest_size'],
evm: ['total_size', 'free_size', 'heap_map_size', 'heap_total_size', 'heap_used_size', 'stack_total_size', 'stack_used_size'],
image: ['png_uncompressed_size', 'png_file_size', 'length']
system: ["free_size"],
lvgl: ["total_size", "free_size", "free_biggest_size"],
evm: [
"total_size",
"free_size",
"heap_map_size",
"heap_total_size",
"heap_used_size",
"stack_total_size",
"stack_used_size",
],
image: ["png_uncompressed_size", "png_file_size", "length"],
},
};
},
filters: {
kb(value) {
return Math.ceil(value / 1024);
},
},
methods: {
initWebSocket() {
if ("WebSocket" in window) {
// this.socket = new WebSocket(`ws://${window.location.host}/ws/v1/notify`);
this.socket = new WebSocket(`ws://${window.location.hostname}:5001/ws/v1/notify`);
this.socket = new WebSocket(
`ws://${window.location.hostname}:5001/ws/v1/notify`
);
this.socket.onopen = () => {
console.log("连接成功");
this.sendMsg();
......@@ -278,30 +277,30 @@ export default {
},
handleMessage(msg) {
if (!this.deviceList.includes(msg.imei)) {
this.deviceList.push(msg.imei)
this.deviceList.push(msg.imei);
}
if (!this.device) {
this.device = this.deviceList[0]
this.device = this.deviceList[0];
}
this.devices[msg.imei] = msg
this.processData(this.devices[this.device])
this.devices[msg.imei] = msg;
this.processData(this.devices[this.device]);
},
processData(msg) {
Object.keys(msg).forEach(item => {
Object.keys(msg).forEach((item) => {
if (this.form[item]) {
var keys = this.form[item]
for(var i = 0; i < keys.length; i++) {
var k = keys[i]
var keys = this.form[item];
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
if (item == "image") {
for(var j = 0; j < msg[item].length; j++) {
msg[item][j][k] = Math.ceil(msg[item][j][k] / 1024)
for (var j = 0; j < msg[item].length; j++) {
msg[item][j][k] = Math.ceil(msg[item][j][k] / 1024);
}
} else {
msg[item][k] = Math.ceil(msg[item][k] / 1024)
msg[item][k] = Math.ceil(msg[item][k] / 1024);
}
}
}
})
});
this.system = [{ imei: msg.imei, ...msg.system }];
this.lvgl = [{ ...msg.lvgl }];
......@@ -310,14 +309,32 @@ export default {
this.image = msg.image;
},
onSelectChange(res) {
this.device = res
this.processData(this.devices[this.device])
console.log(res)
this.device = res;
this.processData(this.devices[this.device]);
console.log(res);
},
},
mounted() {},
created() {
this.initWebSocket();
this.socket = wsNotify
wsNotify.eventBus.$on("open", (message) => {
this.sendMsg();
this.$nextTick(() => {
console.log(message)
});
});
wsNotify.eventBus.$on("close", (message) => {
this.$nextTick(() => {
console.log(message)
});
});
wsNotify.eventBus.$on("message", (message) => {
this.$nextTick(() => {
console.log(message)
this.handleMessage(message)
});
});
// this.initWebSocket();
},
};
</script>
......
<template>
<div class="app-container">
<el-form :inline="true" :model="form" size="mini">
<el-form-item label="权限名称">
<el-select v-model="form.uuid" filterable placeholder="请输入权限名称">
<el-option v-for="(item, index) in roles" :key="index" :label="item.name" :value="item.uuid"></el-option>
</el-select>
</el-form-item>
<el-form-item><el-button type="primary" @click="onSubmit">查询</el-button></el-form-item>
<el-form-item><el-button @click="onReset">重置</el-button></el-form-item>
<el-form-item><el-button type="warning" @click="onAdd">添加</el-button></el-form-item>
</el-form>
<el-table v-loading="isLoading" element-loading-text="Loading" :data="list" size="mini" border stripe fit highlight-current-row>
<el-table-column prop="name" label="权限名称" align="center" min-width="100"></el-table-column>
<el-table-column prop="create_at" label="创建时间" width="150"></el-table-column>
<el-table-column prop="create_by.username" label="创建者" width="150"></el-table-column>
<el-table-column prop="update_at" label="更新时间" width="150" :show-overflow-tooltip="true"></el-table-column>
<el-table-column prop="update_by.username" label="更新者" width="150"></el-table-column>
<el-table-column label="操作" align="center" width="180" fixed="right">
<template slot-scope="scope">
<el-button size="mini" type="success" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
<el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
<!-- <el-tag type="warning" v-if="!checkPermission(['area-modify']) && !checkPermission(['area-remove'])">没有操作权限</el-tag> -->
</template>
</el-table-column>
</el-table>
<div class="page-wrapper">
<el-pagination @current-change="handleCurrentChange" :current-page.sync="form.pagenum" background small :page-size="form.pagesize" :pager-count="5" layout="pager, prev, next, total" :total="total"></el-pagination>
</div>
<el-dialog
:title="dialogTitle"
:visible.sync="dialogVisible"
width="45%"
>
<el-form :model="post" status-icon :rules="rules" :inline="true" ref="post" size="mini" label-width="80px">
<el-form-item label="权限名称" prop="permission">
<el-input type="text" v-model="post.permission" autocomplete="off"></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="primary" size="mini" plain @click="submitForm('post')">提交</el-button>
<el-button type="success" size="mini" plain @click="onReset('post')">重置</el-button>
<el-button size="mini" @click="dialogVisible = false">关闭</el-button>
</div>
</el-dialog>
</div>
</template>
<script>
import { getPermissionList, deletePermission, addPermission, updatePermission } from '@/api/index'
import checkPermission from '@/utils/permission'
import { mapTrim, compareObjectDiff } from '@/utils/index'
import { formatUTCDateTime } from '@/utils/utils'
export default {
data() {
return {
total: 0,
list: [],
isLoading: false,
roles: [],
depots: [],
form: {
uuid: null,
name: null,
pagesize: 15,
pagenum: 1
},
dialogTitle: "",
dialogVisible: false,
post: {
permission: null,
name: null,
},
rules: {
permission: [{ type: 'string', required: true, message: '权限名称不能为空', trigger: 'blur' }],
name: [
{ type: 'string', required: true, message: '用户名不能为空', trigger: 'blur' },
{ min: 1, max: 20, message: '字符串长度在 1 到 20 之间', trigger: 'blur' }
]
}
}
},
methods: {
checkPermission,
fetchData(params) {
this.isLoading = true
getPermissionList(Object.assign({
pagenum: this.form.pagenum,
pagesize: this.form.pagesize,
}, params)).then(res => {
if (res.code == 200) {
this.total = res.count
this.list = res.data.map(item => {
item.create_at = formatUTCDateTime(item.create_at)
item.update_at = formatUTCDateTime(item.update_at)
return item
})
}
}).catch(err => {
// this.$message.error(err.message)
console.log(err.message)
}).finally(() => {
this.isLoading = false
})
},
fetchSelectData() {
getPermissionList({ "scope_type": "list" }).then(res => {
this.roles = res.data
}).catch(err => {
// this.$message.error(err.message)
console.log(err.message)
})
},
handleSizeChange(e) {
this.form.pagesize = e
this.fetchData(mapTrim(this.form))
},
handleCurrentChange(e) {
this.form.pagenum = e
this.fetchData(mapTrim(this.form))
},
handleEdit(index, row) {
this.post.account = row.account
this.post.username = row.username
this.post.contact = row.contact
this.post.birthday = row.birthday
this.post.email = row.email
this.post.hometown = row.hometown
this.post.entry_time = row.entry_time
this.post.expire_date = row.expire_date
this.post.role = row.role
this.post.depot = row.depot
this.dialogTitle = "编辑"
this.dialogVisible = true
},
handleDelete(index, row) {
this.$alert('您确定要删除么?删除操作将不可恢复。如需取消操作,请点击右上角关闭按钮。', '删除提醒', {
confirmButtonText: '确定',
callback: action => {
if (action == 'confirm') deletePermission(row.id).then(res => {
console.log(res)
this.total -= 1
this.$delete(this.list, index)
this.$message({ type: 'success', message: `成功删除第${ index }行` })
}).catch(err => {
this.$message.error(err.message)
})
}
})
},
submitForm(formName) {
this.$refs[formName].validate((valid) => {
let result = true
if (valid) {
if (this.dialogTitle === '添加') addPermission(mapTrim(this.post)).then(res => {
console.log(res)
this.$message({ type: 'success', message: res.message })
}).catch(err => {
this.$message.error(err.message)
})
else if (this.dialogTitle === '编辑') updatePermission(this.currentValue.id, compareObjectDiff(this.post, this.currentValue)).then(res => {
console.log(res)
// this.$set(this.list, this.currentIndex, Object.assign(this.currentValue, tmp))
this.$message({ type: 'success', message: '更新成功' })
}).catch(err => {
this.$message.error(err.message)
})
} else {
result = false
}
this.dialogVisible = false
return result
})
},
onAdd() {
this.dialogTitle = "添加"
this.dialogVisible = true
},
onSubmit() {
this.form.pagenum = 1
this.form.pagesize = 15
this.fetchData(mapTrim(this.form))
},
onReset(formName) {
this.form = {
account: null,
username: null,
pagesize: 15,
pagenum: 1
}
this.$refs[formName].resetFields()
this.fetchData()
}
},
mounted() {
},
created() {
this.fetchData()
this.fetchSelectData()
}
}
</script>
<style lang="scss" scoped>
.app-container {
& > div.page-wrapper {
margin: 10px 0px;
}
}
</style>
'''
Author: your name
Date: 2021-06-15 17:40:06
LastEditTime: 2021-06-30 18:17:48
LastEditors: your name
Description: In User Settings Edit
FilePath: \evm-store\tools\resources\application\__init__.py
'''
#!/usr/bin/env python
# -*- coding: utf_8 -*-
import sys
sys.path.append("..")
from controllers import initConnect
initConnect()
\ No newline at end of file
# -*- coding: utf-8 -*-
import sys
import string
import flask_restful
from flask import Flask, abort, jsonify
......@@ -98,15 +99,12 @@ def create_app(config):
# 自定义abort 400 响应数据格式
flask_restful.abort = _custom_abort
# 数据库初始化
<<<<<<< HEAD
db.init_app(app)
=======
# db.app = app
db.init_app(app)
# 创建表
db.create_all()
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
# 注册蓝图
sys.path.append("..")
from views import api_v1
app.register_blueprint(api_v1, url_prefix='/api/v1')
# 使用flask原生异常处理程序
......
......@@ -32,24 +32,15 @@ class ProductionConfig(object):
MYSQL_PORT = 3306
MYSQL_USER = 'debian-sys-maint'
MYSQL_PWD = 'XMigC2B2uugnv18y'
<<<<<<< HEAD
SQLALCHEMY_BINDS = "sqlite:////test.db"
SQLALCHEMY_DATABASE_URI = "sqlite:////test.db"
=======
SQLALCHEMY_BINDS = {
'app-store': 'sqlite:///../test.db'
}
SQLALCHEMY_DATABASE_URI = 'sqlite:///../test.db'
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
def __init__(self):
super().__init__()
<<<<<<< HEAD
self.SQLALCHEMY_DATABASE_URI = "sqlite:////test.db"
=======
self.SQLALCHEMY_DATABASE_URI = 'sqlite:///../test.db'
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
class DevelopConfig(object):
......@@ -77,26 +68,17 @@ class DevelopConfig(object):
MYSQL_PORT = 3306
MYSQL_USER = 'debian-sys-maint'
MYSQL_PWD = 'XMigC2B2uugnv18y'
<<<<<<< HEAD
SQLALCHEMY_BINDS = "sqlite:////test.db"
SQLALCHEMY_DATABASE_URI = "sqlite:////test.db"
=======
SQLALCHEMY_BINDS = {
'app-store': 'sqlite:///../test.db'
}
SQLALCHEMY_DATABASE_URI = 'sqlite:///../test.db'
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
SQLALCHEMY_TRACK_MODIFICATIONS = True
SQLALCHEMY_ECHO = False
def __init__(self):
super().__init__()
<<<<<<< HEAD
self.SQLALCHEMY_DATABASE_URI = "sqlite:////test.db"
=======
self.SQLALCHEMY_DATABASE_URI = 'sqlite:///../test.db'
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
if MODE == 'production':
config = ProductionConfig()
......
......@@ -21,10 +21,7 @@ class SignalManager(object):
actionGetListUser = PySignal()
actionGetUser = PySignal()
actionPutUser = PySignal()
<<<<<<< HEAD
=======
actionPostLogin = PySignal()
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
actionGetListLogin = PySignal()
actionGetLogin = PySignal()
......
#!/usr/bin/env python
# -*- coding: utf_8 -*-
<<<<<<< HEAD
from application.app import signalManager
=======
from application.signal_manager import signalManager
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
from .area import areaManager
from .app import appManager
from .package import packageManager
......@@ -30,13 +26,6 @@ def initConnect():
signalManager.actionGetListUser.connect(userManager.getList)
signalManager.actionGetUser.connect(userManager.get)
signalManager.actionPutUser.connect(userManager.put)
<<<<<<< HEAD
signalManager.actionGetListLogin.connect(loginManager.getList)
signalManager.actionGetLogin.connect(loginManager.get)
initConnect()
=======
signalManager.actionPostLogin.connect(loginManager.post)
signalManager.actionGetListLogin.connect(loginManager.getList)
signalManager.actionGetLogin.connect(loginManager.get)
\ No newline at end of file
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
from datetime import datetime
from application.app import db
from models.app import AppModel
<<<<<<< HEAD
from webcreator.utils import ResponseCode, response_result
=======
from webcreator.log import logger
from webcreator.response import ResponseCode, response_result
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
class AppResource(object):
def __init__(self):
super().__init__()
<<<<<<< HEAD
def get(self, params):
# handle business
filters = []
result = AppModel.query.filter(*filters).order_by(AppModel.areaId).paginate(params.get('page', 1), params.get('pageSize', 10), error_out=False)
return result
def post(self, params, jwt=None):
# handle business
result = AppModel.query.filter(AppModel.areaName == params.get('areaName')).first()
if result and result.is_delete:
result.is_delete = False
result.update_by = jwt['id']
result.update_date = datetime.now()
db.session.commit()
return response_result(ResponseCode.OK)
elif result and result.is_delete == False:
return response_result(ResponseCode.EXISTS_ERROR)
=======
def get(self, uuid, params):
# handle business
filters = [AppModel.is_delete==False, AppModel.uuid==uuid]
......@@ -59,38 +35,10 @@ class AppResource(object):
return (True, None)
elif result and result.is_delete == False:
return (False, "record code exists")
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
result = AppModel(**params)
db.session.add(result)
db.session.commit()
<<<<<<< HEAD
return response_result(ResponseCode.OK)
def put(self, id, params, jwt=None):
# handle business
result = AppModel.query.get(id)
if not result: return response_result(ResponseCode.NO_DATA)
if params:
for key, value in params.items():
if value != None: setattr(result, key, value)
result.update_by = jwt['id']
result.update_date = datetime.now()
db.session.commit()
else:
return response_result(ResponseCode.PARAM_NULL)
def delete(self, id, jwt=None):
# handle business
result = AppModel.query.get(id)
if not result: return response_result(ResponseCode.NO_DATA_FOUND)
else:
result.update_by = jwt['id']
result.update_date = datetime.now()
result.is_delete = True
db.session.delete(result)
db.session.commit()
=======
return (True, None)
def put(self, uuid, params, jwt={}):
......@@ -121,6 +69,5 @@ class AppResource(object):
db.session.delete(result)
db.session.commit()
return (True, None)
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
appManager = AppResource()
\ No newline at end of file
from datetime import datetime
from application.app import db
from models.area import AreaModel
<<<<<<< HEAD
from webcreator.utils import ResponseCode, response_result
=======
from webcreator.log import logger
from webcreator.response import ResponseCode, response_result
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
class AreaResource(object):
def __init__(self):
super().__init__()
<<<<<<< HEAD
def get(self, params):
# handle business
filters = []
result = AreaModel.query.filter(*filters).order_by(AreaModel.areaId).paginate(params.get('page', 1), params.get('pageSize', 10), error_out=False)
return result
def post(self, params, jwt=None):
# handle business
result = AreaModel.query.filter(AreaModel.areaName == params.get('areaName')).first()
if result and result.is_delete:
result.is_delete = False
result.update_by = jwt['id']
result.update_date = datetime.now()
db.session.commit()
return response_result(ResponseCode.OK)
elif result and result.is_delete == False:
return response_result(ResponseCode.EXISTS_ERROR)
=======
def get(self, uuid, params):
# handle business
filters = [AreaModel.is_delete==False, AreaModel.uuid==uuid]
......@@ -59,38 +35,10 @@ class AreaResource(object):
return (True, None)
elif result and result.is_delete == False:
return (False, "record code exists")
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
result = AreaModel(**params)
db.session.add(result)
db.session.commit()
<<<<<<< HEAD
return response_result(ResponseCode.OK)
def put(self, id, params, jwt=None):
# handle business
result = AreaModel.query.get(id)
if not result: return response_result(ResponseCode.NO_DATA)
if params:
for key, value in params.items():
if value != None: setattr(result, key, value)
result.update_by = jwt['id']
result.update_date = datetime.now()
db.session.commit()
else:
return response_result(ResponseCode.PARAM_NULL)
def delete(self, id, jwt=None):
# handle business
result = AreaModel.query.get(id)
if not result: return response_result(ResponseCode.NO_DATA_FOUND)
else:
result.update_by = jwt['id']
result.update_date = datetime.now()
result.is_delete = True
db.session.delete(result)
db.session.commit()
=======
return (True, None)
def put(self, uuid, params, jwt={}):
......@@ -121,6 +69,5 @@ class AreaResource(object):
db.session.delete(result)
db.session.commit()
return (True, None)
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
areaManager = AreaResource()
\ No newline at end of file
from datetime import datetime
from application.app import db
from models.login import LoginModel
<<<<<<< HEAD
from webcreator.utils import ResponseCode, response_result
=======
from webcreator.log import logger
from webcreator.response import ResponseCode, response_result
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
class LoginResource(object):
def __init__(self):
super().__init__()
<<<<<<< HEAD
def get(self, params):
# handle business
filters = []
result = LoginModel.query.filter(*filters).order_by(LoginModel.areaId).paginate(params.get('page', 1), params.get('pageSize', 10), error_out=False)
return result
def post(self, params, jwt=None):
# handle business
result = LoginModel.query.filter(LoginModel.areaName == params.get('areaName')).first()
if result and result.is_delete:
result.is_delete = False
result.update_by = jwt['id']
result.update_date = datetime.now()
db.session.commit()
return response_result(ResponseCode.OK)
elif result and result.is_delete == False:
return response_result(ResponseCode.EXISTS_ERROR)
=======
def get(self, uuid, params):
# handle business
filters = [LoginModel.is_delete==False, LoginModel.uuid==uuid]
......@@ -59,38 +35,10 @@ class LoginResource(object):
return (True, None)
elif result and result.is_delete == False:
return (False, "record code exists")
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
result = LoginModel(**params)
db.session.add(result)
db.session.commit()
<<<<<<< HEAD
return response_result(ResponseCode.OK)
def put(self, id, params, jwt=None):
# handle business
result = LoginModel.query.get(id)
if not result: return response_result(ResponseCode.NO_DATA)
if params:
for key, value in params.items():
if value != None: setattr(result, key, value)
result.update_by = jwt['id']
result.update_date = datetime.now()
db.session.commit()
else:
return response_result(ResponseCode.PARAM_NULL)
def delete(self, id, jwt=None):
# handle business
result = LoginModel.query.get(id)
if not result: return response_result(ResponseCode.NO_DATA_FOUND)
else:
result.update_by = jwt['id']
result.update_date = datetime.now()
result.is_delete = True
db.session.delete(result)
db.session.commit()
=======
return (True, None)
def put(self, uuid, params, jwt={}):
......@@ -121,6 +69,5 @@ class LoginResource(object):
db.session.delete(result)
db.session.commit()
return (True, None)
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
loginManager = LoginResource()
\ No newline at end of file
from datetime import datetime
from application.app import db
from models.package import PackageModel
<<<<<<< HEAD
from webcreator.utils import ResponseCode, response_result
=======
from webcreator.log import logger
from webcreator.response import ResponseCode, response_result
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
class PackageResource(object):
def __init__(self):
super().__init__()
<<<<<<< HEAD
def get(self, params):
# handle business
filters = []
result = PackageModel.query.filter(*filters).order_by(PackageModel.areaId).paginate(params.get('page', 1), params.get('pageSize', 10), error_out=False)
return result
def post(self, params, jwt=None):
# handle business
result = PackageModel.query.filter(PackageModel.areaName == params.get('areaName')).first()
if result and result.is_delete:
result.is_delete = False
result.update_by = jwt['id']
result.update_date = datetime.now()
db.session.commit()
return response_result(ResponseCode.OK)
elif result and result.is_delete == False:
return response_result(ResponseCode.EXISTS_ERROR)
=======
def get(self, uuid, params):
# handle business
filters = [PackageModel.is_delete==False, PackageModel.uuid==uuid]
......@@ -59,38 +35,10 @@ class PackageResource(object):
return (True, None)
elif result and result.is_delete == False:
return (False, "record code exists")
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
result = PackageModel(**params)
db.session.add(result)
db.session.commit()
<<<<<<< HEAD
return response_result(ResponseCode.OK)
def put(self, id, params, jwt=None):
# handle business
result = PackageModel.query.get(id)
if not result: return response_result(ResponseCode.NO_DATA)
if params:
for key, value in params.items():
if value != None: setattr(result, key, value)
result.update_by = jwt['id']
result.update_date = datetime.now()
db.session.commit()
else:
return response_result(ResponseCode.PARAM_NULL)
def delete(self, id, jwt=None):
# handle business
result = PackageModel.query.get(id)
if not result: return response_result(ResponseCode.NO_DATA_FOUND)
else:
result.update_by = jwt['id']
result.update_date = datetime.now()
result.is_delete = True
db.session.delete(result)
db.session.commit()
=======
return (True, None)
def put(self, uuid, params, jwt={}):
......@@ -121,6 +69,5 @@ class PackageResource(object):
db.session.delete(result)
db.session.commit()
return (True, None)
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
packageManager = PackageResource()
\ No newline at end of file
from datetime import datetime
from application.app import db
from models.user import UserModel
<<<<<<< HEAD
from webcreator.utils import ResponseCode, response_result
=======
from webcreator.log import logger
from webcreator.response import ResponseCode, response_result
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
class UserResource(object):
def __init__(self):
super().__init__()
<<<<<<< HEAD
def get(self, params):
# handle business
filters = []
result = UserModel.query.filter(*filters).order_by(UserModel.areaId).paginate(params.get('page', 1), params.get('pageSize', 10), error_out=False)
return result
def post(self, params, jwt=None):
# handle business
result = UserModel.query.filter(UserModel.areaName == params.get('areaName')).first()
if result and result.is_delete:
result.is_delete = False
result.update_by = jwt['id']
result.update_date = datetime.now()
db.session.commit()
return response_result(ResponseCode.OK)
elif result and result.is_delete == False:
return response_result(ResponseCode.EXISTS_ERROR)
=======
def get(self, uuid, params):
# handle business
filters = [UserModel.is_delete==False, UserModel.uuid==uuid]
......@@ -59,38 +35,10 @@ class UserResource(object):
return (True, None)
elif result and result.is_delete == False:
return (False, "record code exists")
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
result = UserModel(**params)
db.session.add(result)
db.session.commit()
<<<<<<< HEAD
return response_result(ResponseCode.OK)
def put(self, id, params, jwt=None):
# handle business
result = UserModel.query.get(id)
if not result: return response_result(ResponseCode.NO_DATA)
if params:
for key, value in params.items():
if value != None: setattr(result, key, value)
result.update_by = jwt['id']
result.update_date = datetime.now()
db.session.commit()
else:
return response_result(ResponseCode.PARAM_NULL)
def delete(self, id, jwt=None):
# handle business
result = UserModel.query.get(id)
if not result: return response_result(ResponseCode.NO_DATA_FOUND)
else:
result.update_by = jwt['id']
result.update_date = datetime.now()
result.is_delete = True
db.session.delete(result)
db.session.commit()
=======
return (True, None)
def put(self, uuid, params, jwt={}):
......@@ -121,6 +69,5 @@ class UserResource(object):
db.session.delete(result)
db.session.commit()
return (True, None)
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
userManager = UserResource()
\ No newline at end of file
This diff is collapsed.
'''
Author: your name
Date: 2021-06-15 17:40:09
LastEditTime: 2021-06-30 18:09:51
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \evm-store\tools\resources\manager.py
'''
# -*- coding: utf-8 -*-
from gevent import monkey
monkey.patch_all()
import logging
from tornado.wsgi import WSGIContainer
from tornado.web import Application, FallbackHandler
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from flask_script import Manager
from flask_migrate import Migrate
from multiprocessing import cpu_count
from application.app import create_app, db
from application.config import config
......@@ -24,31 +27,11 @@ def run():
To use: python3 manager.py run
"""
# app.logger.setLevel(app.config.get('LOG_LEVEL', logging.INFO))
# service_config = {
# 'bind': app.config.get('BIND', '0.0.0.0:3000'),
# 'workers': app.config.get('WORKERS', cpu_count() * 2 + 1),
# 'worker_class': 'gevent',
# 'worker_connections': app.config.get('WORKER_CONNECTIONS', 10000),
# 'backlog': app.config.get('BACKLOG', 2048),
# 'timeout': app.config.get('TIMEOUT', 60),
# 'loglevel': app.config.get('LOG_LEVEL', 'info'),
# 'pidfile': app.config.get('PID_FILE', 'run.pid'),
# }
http_server = HTTPServer(WSGIContainer(app))
http_server.listen(3000, address='127.0.0.1')
<<<<<<< HEAD
# wsgi_app = WSGIContainer(app)
# application = Application([
# (r'.*', FallbackHandler, dict(fallback=wsgi_app))
# ], **service_config)
# application.listen(3000)
=======
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
http_server.listen(3000, address='127.0.0.1', xheaders=True)
IOLoop.instance().start()
@manager.command
def debug():
"""
......@@ -56,10 +39,6 @@ def debug():
To use: python3 manager.py debug
"""
# app.logger.setLevel(logging.DEBUG)
<<<<<<< HEAD
print("start from here......")
=======
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
app.run(debug=True, port=3000, host='127.0.0.1')
if __name__ == '__main__':
......
'''
Author: your name
Date: 2021-04-22 18:04:10
LastEditTime: 2021-06-30 17:22:15
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \evm-store\tools\resources\models\__init__.py
'''
# -*- coding: utf-8 -*-
<<<<<<< HEAD
from sqlalchemy import Column, Integer, String
=======
from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import sessionmaker
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
from sqlalchemy.ext.declarative import declared_attr, declarative_base
class BaseModelMixin(object):
......@@ -32,9 +35,6 @@ class MyMixin(object):
# example:
class MyModel(MyMixin, BaseModel):
<<<<<<< HEAD
name = Column(String(1000))
=======
__tablename__ = 'mymodel'
name = Column(String(20))
fullname = Column(String(32))
......@@ -64,4 +64,3 @@ session.commit()
# our_user = session.query(MyModel).filter_by(name='ed').first()
# print(our_user)
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
......@@ -7,19 +7,6 @@ from marshmallow import Schema, fields, INCLUDE, EXCLUDE
class AppModel(PrimaryModel):
__tablename__ = 'evm_app'
<<<<<<< HEAD
app_name = db.Column(db.String(70), index = True)
app_icon = db.Column(db.String(200))
app_version = db.Column(db.String(20))
category = db.Column(db.Integer)
category_2th = db.Column(db.Integer)
developer = db.Column(db.Integer)
download_url = db.Column(db.String(20))
app_file_size = db.Column(db.Integer)
app_screen_size = db.Column(db.Integer)
app_arch = db.Column(db.String(20))
app_review = db.Column(db.String(100))
=======
app_name = db.Column(db.String(70), index = True, nullable = False)
app_icon = db.Column(db.String(200), nullable = False)
app_version = db.Column(db.String(20), nullable = False)
......@@ -31,7 +18,6 @@ class AppModel(PrimaryModel):
app_screen_size = db.Column(db.Integer, nullable = False)
app_arch = db.Column(db.String(20), nullable = False)
app_review = db.Column(db.String(100), nullable = False)
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
# __table_args__ = (
# db.Index('idx_xxx', 'xxx', mysql_using='btree'),
......@@ -72,11 +58,7 @@ class AppModel(PrimaryModel):
class PostAppSchema(ma.SQLAlchemySchema):
class Meta:
# unknown = INCLUDE # 未知字段默认包含
<<<<<<< HEAD
# unknown = EXCLUDE # 未知字段默认排除
=======
unknown = EXCLUDE # 未知字段默认排除
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
model = AppModel
app_name = ma.auto_field()
......@@ -90,19 +72,11 @@ class PostAppSchema(ma.SQLAlchemySchema):
app_review = ma.auto_field()
postAppSchema = PostAppSchema()
<<<<<<< HEAD
postAppsSchema = PostAppSchema(many=True)
=======
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
class DeleteAppSchema(ma.SQLAlchemySchema):
class Meta:
# unknown = INCLUDE # 未知字段默认包含
<<<<<<< HEAD
# unknown = EXCLUDE # 未知字段默认排除
=======
unknown = EXCLUDE # 未知字段默认排除
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
model = AppModel
......@@ -111,11 +85,7 @@ deleteAppSchema = DeleteAppSchema()
class GetListAppSchema(ma.SQLAlchemySchema):
class Meta:
# unknown = INCLUDE # 未知字段默认包含
<<<<<<< HEAD
# unknown = EXCLUDE # 未知字段默认排除
=======
unknown = EXCLUDE # 未知字段默认排除
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
model = AppModel
page = fields.Integer(required=False)
......@@ -127,19 +97,12 @@ class GetListAppSchema(ma.SQLAlchemySchema):
app_arch = ma.auto_field()
getListAppSchema = GetListAppSchema()
<<<<<<< HEAD
=======
getListAppsSchema = GetListAppSchema(many=True)
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
class GetAppSchema(ma.SQLAlchemySchema):
class Meta:
# unknown = INCLUDE # 未知字段默认包含
<<<<<<< HEAD
# unknown = EXCLUDE # 未知字段默认排除
=======
unknown = EXCLUDE # 未知字段默认排除
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
model = AppModel
app_name = ma.auto_field()
......@@ -153,11 +116,7 @@ getAppSchema = GetAppSchema()
class PutAppSchema(ma.SQLAlchemySchema):
class Meta:
# unknown = INCLUDE # 未知字段默认包含
<<<<<<< HEAD
# unknown = EXCLUDE # 未知字段默认排除
=======
unknown = EXCLUDE # 未知字段默认排除
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
model = AppModel
app_name = ma.auto_field()
......
......@@ -7,15 +7,6 @@ from marshmallow import Schema, fields, INCLUDE, EXCLUDE
class AreaModel(PrimaryModel):
__tablename__ = 'evm_area'
<<<<<<< HEAD
areaCode = db.Column(db.String(20), index = True)
areaName = db.Column(db.String(20), index = True)
level = db.Column(db.Integer, default = 1)
cityCode = db.Column(db.Integer)
center = db.Column(db.String(20), index = True)
parentId = db.Column(db.String(20))
hasChildren = db.Column(db.Boolean)
=======
areaCode = db.Column(db.String(20), index = True, nullable = False)
areaName = db.Column(db.String(20), index = True, nullable = False)
level = db.Column(db.Integer, nullable = False, default = 1)
......@@ -23,7 +14,6 @@ class AreaModel(PrimaryModel):
center = db.Column(db.String(20), index = True, nullable = False)
parentId = db.Column(db.String(20), nullable = True)
hasChildren = db.Column(db.Boolean, nullable = True)
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
# __table_args__ = (
# db.Index('idx_xxx', 'xxx', mysql_using='btree'),
......@@ -56,38 +46,23 @@ class AreaModel(PrimaryModel):
class PostAreaSchema(ma.SQLAlchemySchema):
class Meta:
# unknown = INCLUDE # 未知字段默认包含
<<<<<<< HEAD
# unknown = EXCLUDE # 未知字段默认排除
=======
unknown = EXCLUDE # 未知字段默认排除
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
model = AreaModel
areaCode = ma.auto_field()
areaName = ma.auto_field()
level = ma.auto_field()
<<<<<<< HEAD
=======
parentId = ma.auto_field()
hasChildren = ma.auto_field()
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
cityCode = ma.auto_field()
center = ma.auto_field()
postAreaSchema = PostAreaSchema()
<<<<<<< HEAD
postAreasSchema = PostAreaSchema(many=True)
=======
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
class DeleteAreaSchema(ma.SQLAlchemySchema):
class Meta:
# unknown = INCLUDE # 未知字段默认包含
<<<<<<< HEAD
# unknown = EXCLUDE # 未知字段默认排除
=======
unknown = EXCLUDE # 未知字段默认排除
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
model = AreaModel
......@@ -96,11 +71,7 @@ deleteAreaSchema = DeleteAreaSchema()
class GetListAreaSchema(ma.SQLAlchemySchema):
class Meta:
# unknown = INCLUDE # 未知字段默认包含
<<<<<<< HEAD
# unknown = EXCLUDE # 未知字段默认排除
=======
unknown = EXCLUDE # 未知字段默认排除
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
model = AreaModel
page = fields.Integer(required=False)
......@@ -112,19 +83,12 @@ class GetListAreaSchema(ma.SQLAlchemySchema):
field = fields.String(required=False, length=None)
getListAreaSchema = GetListAreaSchema()
<<<<<<< HEAD
=======
getListAreasSchema = GetListAreaSchema(many=True)
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
class GetAreaSchema(ma.SQLAlchemySchema):
class Meta:
# unknown = INCLUDE # 未知字段默认包含
<<<<<<< HEAD
# unknown = EXCLUDE # 未知字段默认排除
=======
unknown = EXCLUDE # 未知字段默认排除
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
model = AreaModel
areaName = ma.auto_field()
......@@ -138,15 +102,6 @@ getAreaSchema = GetAreaSchema()
class PutAreaSchema(ma.SQLAlchemySchema):
class Meta:
# unknown = INCLUDE # 未知字段默认包含
<<<<<<< HEAD
# unknown = EXCLUDE # 未知字段默认排除
model = AreaModel
areaName = ma.auto_field()
level = ma.auto_field()
parentId = ma.auto_field()
hasChildren = ma.auto_field()
=======
unknown = EXCLUDE # 未知字段默认排除
model = AreaModel
......@@ -154,7 +109,6 @@ class PutAreaSchema(ma.SQLAlchemySchema):
level = fields.Integer(required=False)
parentId = fields.String(required=False, length=None)
hasChildren = fields.Boolean(required=False)
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
field = fields.String(required=False, length=None)
putAreaSchema = PutAreaSchema()
......@@ -4,12 +4,9 @@ import uuid
from datetime import datetime
from application.app import db
<<<<<<< HEAD
=======
def generate_uuid():
return uuid.uuid1().hex
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
class BaseModel(db.Model):
# Flask-SQLAlchemy创建table时,如何声明基类(这个类不会创建表,可以被继承)
# 方法就是把__abstract__这个属性设置为True,这个类为基类,不会被创建为表!
......@@ -24,11 +21,7 @@ class BaseModel(db.Model):
class PrimaryModel(BaseModel):
__abstract__ = True
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
<<<<<<< HEAD
uuid = db.Column(db.String(64), primary_key=True, default=uuid.uuid1)
=======
uuid = db.Column(db.String(64), primary_key=False, default=generate_uuid)
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
class AutoBaseModel(BaseModel):
__abstract__ = True
......@@ -37,11 +30,7 @@ class AutoBaseModel(BaseModel):
class UuidBaseModel(BaseModel):
__abstract__ = True
<<<<<<< HEAD
id = db.Column(db.String(64), primary_key=True, default=uuid.uuid1)
=======
id = db.Column(db.String(64), primary_key=True, default=generate_uuid)
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
sort = db.Column(db.Integer, default=0)
class SortBaseModel(BaseModel):
......
......@@ -7,21 +7,12 @@ from marshmallow import Schema, fields, INCLUDE, EXCLUDE
class LoginModel(PrimaryModel):
__tablename__ = 'evm_login'
<<<<<<< HEAD
user = db.Column(db.Integer)
login_at = db.Column(db.String(200))
user_agent = db.Column(db.String(200))
ip = db.Column(db.String(128))
geo_location = db.Column(db.String(200))
operator = db.Column(db.String(50))
=======
user = db.Column(db.Integer, nullable = False)
login_at = db.Column(db.String(200), nullable = False)
user_agent = db.Column(db.String(200), nullable = False)
ip = db.Column(db.String(128), nullable = False)
geo_location = db.Column(db.String(200), nullable = False)
operator = db.Column(db.String(50), nullable = False)
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
# __table_args__ = (
# db.Index('idx_xxx', 'xxx', mysql_using='btree'),
......@@ -48,12 +39,6 @@ class LoginModel(PrimaryModel):
}
<<<<<<< HEAD
class GetListLoginSchema(ma.SQLAlchemySchema):
class Meta:
# unknown = INCLUDE # 未知字段默认包含
# unknown = EXCLUDE # 未知字段默认排除
=======
class PostLoginSchema(ma.SQLAlchemySchema):
class Meta:
# unknown = INCLUDE # 未知字段默认包含
......@@ -69,7 +54,6 @@ class GetListLoginSchema(ma.SQLAlchemySchema):
class Meta:
# unknown = INCLUDE # 未知字段默认包含
unknown = EXCLUDE # 未知字段默认排除
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
model = LoginModel
page = fields.Integer(required=False)
......@@ -82,19 +66,12 @@ class GetListLoginSchema(ma.SQLAlchemySchema):
operator = ma.auto_field()
getListLoginSchema = GetListLoginSchema()
<<<<<<< HEAD
=======
getListLoginsSchema = GetListLoginSchema(many=True)
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
class GetLoginSchema(ma.SQLAlchemySchema):
class Meta:
# unknown = INCLUDE # 未知字段默认包含
<<<<<<< HEAD
# unknown = EXCLUDE # 未知字段默认排除
=======
unknown = EXCLUDE # 未知字段默认排除
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
model = LoginModel
user = ma.auto_field()
......
......@@ -7,18 +7,6 @@ from marshmallow import Schema, fields, INCLUDE, EXCLUDE
class PackageModel(PrimaryModel):
__tablename__ = 'evm_package'
<<<<<<< HEAD
app = db.Column(db.Integer)
app_version = db.Column(db.String(200))
package_info = db.Column(db.String(20))
file_path = db.Column(db.String(200))
source = db.Column(db.Integer)
user_agent = db.Column(db.String(200))
download_url = db.Column(db.String(200))
ip = db.Column(db.String(128))
geo_location = db.Column(db.String(200))
operator = db.Column(db.String(50))
=======
app = db.Column(db.Integer, nullable = False)
app_version = db.Column(db.String(200), nullable = False)
package_info = db.Column(db.String(20), nullable = False)
......@@ -29,7 +17,6 @@ class PackageModel(PrimaryModel):
ip = db.Column(db.String(128), nullable = False)
geo_location = db.Column(db.String(200), nullable = False)
operator = db.Column(db.String(50), nullable = False)
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
# __table_args__ = (
# db.Index('idx_xxx', 'xxx', mysql_using='btree'),
......@@ -67,11 +54,7 @@ class PackageModel(PrimaryModel):
class GetListPackageSchema(ma.SQLAlchemySchema):
class Meta:
# unknown = INCLUDE # 未知字段默认包含
<<<<<<< HEAD
# unknown = EXCLUDE # 未知字段默认排除
=======
unknown = EXCLUDE # 未知字段默认排除
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
model = PackageModel
page = fields.Integer(required=False)
......@@ -88,19 +71,12 @@ class GetListPackageSchema(ma.SQLAlchemySchema):
operator = ma.auto_field()
getListPackageSchema = GetListPackageSchema()
<<<<<<< HEAD
=======
getListPackagesSchema = GetListPackageSchema(many=True)
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
class GetPackageSchema(ma.SQLAlchemySchema):
class Meta:
# unknown = INCLUDE # 未知字段默认包含
<<<<<<< HEAD
# unknown = EXCLUDE # 未知字段默认排除
=======
unknown = EXCLUDE # 未知字段默认排除
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
model = PackageModel
app = ma.auto_field()
......
......@@ -7,19 +7,6 @@ from marshmallow import Schema, fields, INCLUDE, EXCLUDE
class UserModel(PrimaryModel):
__tablename__ = 'evm_user'
<<<<<<< HEAD
app_name = db.Column(db.String(70), index = True)
app_icon = db.Column(db.String(200))
app_version = db.Column(db.String(20))
category = db.Column(db.Integer)
category_2th = db.Column(db.Integer)
developer = db.Column(db.Integer)
download_url = db.Column(db.String(20))
app_file_size = db.Column(db.Integer)
app_screen_size = db.Column(db.Integer)
app_arch = db.Column(db.String(20))
app_review = db.Column(db.String(100))
=======
app_name = db.Column(db.String(70), index = True, nullable = False)
app_icon = db.Column(db.String(200), nullable = False)
app_version = db.Column(db.String(20), nullable = False)
......@@ -31,7 +18,6 @@ class UserModel(PrimaryModel):
app_screen_size = db.Column(db.Integer, nullable = False)
app_arch = db.Column(db.String(20), nullable = False)
app_review = db.Column(db.String(100), nullable = False)
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
# __table_args__ = (
# db.Index('idx_xxx', 'xxx', mysql_using='btree'),
......@@ -72,11 +58,7 @@ class UserModel(PrimaryModel):
class PostUserSchema(ma.SQLAlchemySchema):
class Meta:
# unknown = INCLUDE # 未知字段默认包含
<<<<<<< HEAD
# unknown = EXCLUDE # 未知字段默认排除
=======
unknown = EXCLUDE # 未知字段默认排除
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
model = UserModel
app_name = ma.auto_field()
......@@ -90,19 +72,11 @@ class PostUserSchema(ma.SQLAlchemySchema):
app_review = ma.auto_field()
postUserSchema = PostUserSchema()
<<<<<<< HEAD
postUsersSchema = PostUserSchema(many=True)
=======
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
class DeleteUserSchema(ma.SQLAlchemySchema):
class Meta:
# unknown = INCLUDE # 未知字段默认包含
<<<<<<< HEAD
# unknown = EXCLUDE # 未知字段默认排除
=======
unknown = EXCLUDE # 未知字段默认排除
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
model = UserModel
......@@ -111,11 +85,7 @@ deleteUserSchema = DeleteUserSchema()
class GetListUserSchema(ma.SQLAlchemySchema):
class Meta:
# unknown = INCLUDE # 未知字段默认包含
<<<<<<< HEAD
# unknown = EXCLUDE # 未知字段默认排除
=======
unknown = EXCLUDE # 未知字段默认排除
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
model = UserModel
page = fields.Integer(required=False)
......@@ -127,19 +97,12 @@ class GetListUserSchema(ma.SQLAlchemySchema):
app_arch = ma.auto_field()
getListUserSchema = GetListUserSchema()
<<<<<<< HEAD
=======
getListUsersSchema = GetListUserSchema(many=True)
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
class GetUserSchema(ma.SQLAlchemySchema):
class Meta:
# unknown = INCLUDE # 未知字段默认包含
<<<<<<< HEAD
# unknown = EXCLUDE # 未知字段默认排除
=======
unknown = EXCLUDE # 未知字段默认排除
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
model = UserModel
app_name = ma.auto_field()
......@@ -153,11 +116,7 @@ getUserSchema = GetUserSchema()
class PutUserSchema(ma.SQLAlchemySchema):
class Meta:
# unknown = INCLUDE # 未知字段默认包含
<<<<<<< HEAD
# unknown = EXCLUDE # 未知字段默认排除
=======
unknown = EXCLUDE # 未知字段默认排除
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
model = UserModel
app_name = ma.auto_field()
......
......@@ -3,12 +3,8 @@ from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from flask_jwt_extended import ( jwt_required, get_jwt_identity )
from application.signal_manager import signalManager
<<<<<<< HEAD
from models.app import postAppSchema,deleteAppSchema,getListAppSchema,getAppSchema,putAppSchema
=======
from models.app import postAppSchema,deleteAppSchema,getListAppSchema,getListAppsSchema,getAppSchema,putAppSchema
from models.app import postAppSchema, deleteAppSchema, getListAppSchema, getListAppsSchema, getAppSchema, putAppSchema
from webcreator.log import logger
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
from webcreator.response import ResponseCode, response_result
class AppResourceList(Resource):
......@@ -25,13 +21,6 @@ class AppResourceList(Resource):
try:
json_payload = request.json
<<<<<<< HEAD
print("========>", json_payload)
data = getListAppSchema.load(json_payload)
result = signalManager.actionGetApp.emit(**data)
json_dumps = getListAppSchema.dump(result)
return jsonify(json_dumps), 200
=======
logger.warn(json_payload)
data = getListAppSchema.load(json_payload)
result = signalManager.actionGetListApp.emit(data)
......@@ -41,32 +30,21 @@ class AppResourceList(Resource):
logger.warn(json_dumps)
return response_result(ResponseCode.OK, data=json_dumps, count=result[2])
return response_result(ResponseCode.REQUEST_ERROR)
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
except Exception as e:
current_app.logger.error(e)
return response_result(ResponseCode.DB_ERROR)
<<<<<<< HEAD
@jwt_required
=======
@jwt_required(locations=["headers"])
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
def post(self):
try:
json_payload = request.json
data = postAppSchema.load(json_payload)
<<<<<<< HEAD
result = signalManager.actionPostApp.emit(**data)
json_dumps = postAppSchema.dump(result)
return jsonify(json_dumps), 200
=======
result = signalManager.actionPostApp.emit(data)
if result[0] == False:
# json_dumps = postAppSchema.dump(result)
return response_result(ResponseCode.REQUEST_ERROR, msg=result[1])
logger.warn(result)
return response_result(ResponseCode.OK)
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
except Exception as e:
current_app.logger.error(e)
return response_result(ResponseCode.DB_ERROR)
......@@ -78,11 +56,7 @@ class AppResource(Resource):
# 特殊参数,即不是从json获取参数的接口,可以将这个注释打开
# self.parser = RequestParser()
<<<<<<< HEAD
@jwt_required
=======
@jwt_required(locations=["headers"])
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
def get(self, uuid):
# 特殊参数,即不是从json获取参数的接口,可以将这个注释打开
# self.parser.add_argument("page", type=int, location="args", default=1)
......@@ -93,69 +67,42 @@ class AppResource(Resource):
json_payload = request.json
print("========>", uuid, json_payload)
data = getAppSchema.load(json_payload)
<<<<<<< HEAD
result = signalManager.actionGetApp.emit(**data)
json_dumps = getAppSchema.dump(result)
return jsonify(json_dumps), 200
=======
result = signalManager.actionGetApp.emit(uuid, data)
if result[0]:
json_dumps = getAppSchema.dump(result[1])
return response_result(ResponseCode.OK, data=json_dumps)
return response_result(ResponseCode.NO_DATA)
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
except Exception as e:
current_app.logger.error(e)
return response_result(ResponseCode.DB_ERROR)
<<<<<<< HEAD
@jwt_required
=======
@jwt_required(locations=["headers"])
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
def put(self, uuid):
try:
json_payload = request.json
print("========>", uuid, json_payload)
data = putAppSchema.load(json_payload)
<<<<<<< HEAD
result = signalManager.actionPutApp.emit(**data)
json_dumps = putAppSchema.dump(result)
return jsonify(json_dumps), 200
=======
result = signalManager.actionPutApp.emit(uuid, data)
if result[0] == True:
# json_dumps = putAppSchema.dump(result)
return response_result(ResponseCode.OK)
return response_result(ResponseCode.NOTHING_CHANGE, msg=result[1])
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
except Exception as e:
current_app.logger.error(e)
return response_result(ResponseCode.DB_ERROR)
<<<<<<< HEAD
@jwt_required
=======
@jwt_required(locations=["headers"])
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
def delete(self, uuid):
try:
json_payload = request.json
print("========>", uuid, json_payload)
<<<<<<< HEAD
data = deleteAppSchema.load(json_payload)
result = signalManager.actionDeleteApp.emit(**data)
json_dumps = deleteAppSchema.dump(result)
return jsonify(json_dumps), 200
=======
# data = deleteAppSchema.load(json_payload)
result = signalManager.actionDeleteApp.emit(uuid)
if result[0] == True:
return response_result(ResponseCode.OK)
return response_result(ResponseCode.REQUEST_ERROR, msg=result[1])
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
except Exception as e:
current_app.logger.error(e)
return response_result(ResponseCode.DB_ERROR)
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
'''
Author: your name
Date: 2021-06-15 17:40:14
LastEditTime: 2021-06-30 17:22:44
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \evm-store\tools\resources\webcreator\event.py
'''
# -*- coding: utf_8 -*-
############################
......@@ -42,7 +50,6 @@ class PySignal(object):
def emit(self, *args, **kwargs):
rets = {}
for handler in self._handlers:
ret = handler(*args, **kwargs)
rets[handler.__name__] = ret
......
......@@ -16,19 +16,10 @@ if not os.path.exists(logPath):
fh = RotatingFileHandler("logs/running.log", maxBytes=10 * 1024 * 1024, backupCount=100)
fh.setLevel(logging.DEBUG)
<<<<<<< HEAD
# log write in console
ch = logging.StreamHandler()
ch.setLevel(logging.WARNING)
# log formatter
formatter = logging.Formatter('[%(asctime)s][%(levelname)7s] [%(filename)15s%(funcName)15s%(lineno)06s] %(message)s')
=======
ch = logging.StreamHandler()
ch.setLevel(logging.WARNING)
formatter = logging.Formatter('[%(asctime)s][%(levelname)7s][in %(pathname)s -> %(funcName)s line:%(lineno)s] %(message)s')
>>>>>>> 735d39eb4d0c3134b62bf4fe1b7a2ca0ea8da1ca
fh.setFormatter(formatter)
ch.setFormatter(formatter)
......
This diff is collapsed.
......@@ -98,7 +98,6 @@ export default {
* @return {*}
*/
preview(disk, path) {
window.console.log("###############===========>", disk)
return request.get('preview', {
responseType: 'arraybuffer',
params: { disk, path },
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment