完成企业节点的增删改查接口

main
周平 12 months ago
parent ae4ac605c0
commit 57ce3d896e

@ -45,7 +45,7 @@ importlib.reload(sys)
try:
import website
except ImportError:
print("app package import error")
print("app package import error and try to config sys.path")
logging.info("app import error")
# sys.path.append(os.path.join(_ROOT, "../.."))

@ -54,18 +54,18 @@ app_engine = create_engine(
# pool_recycle=int(settings.SQLALCHEMY_POOL_RECYCLE), # 多久时间回收连接
)
# Session = sessionmaker(bind=engine)
# Base = declarative_base(engine)
#
#
# @contextlib.contextmanager
# def get_session():
# s = Session()
# try:
# yield s
# s.commit()
# except Exception as e:
# s.rollback()
# raise e
# finally:
# s.close()
Session = sessionmaker(bind=app_engine)
# Base = declarative_base(app_engine)
@contextlib.contextmanager
def get_session():
s = Session()
try:
yield s
s.commit()
except Exception as e:
s.rollback()
raise e
finally:
s.close()

@ -10,6 +10,7 @@ import urllib
import json
# import urlparse
from urllib.parse import parse_qs, unquote
from typing import Any
# from urllib import unquote
import tornado
@ -272,7 +273,8 @@ class BaseHandler(BaseRequestHandler):
value = super(BaseHandler, self).get_argument(name, default, strip)
return escape.utf8(value) if isinstance(value, str) else value
def get_int_argument(self, name, default=0):
# def get_int_argument(self, name, default=0):
def get_int_argument(self, name: Any, default: int = 0) -> int:
try:
return int(self.get_argument(name, default))
except ValueError:

@ -0,0 +1,16 @@
# -*- coding: utf-8 -*-
import logging
from website.db import get_session
from sqlalchemy import text
class EnterpriseEntityDB(object):
def __init__(self):
pass
def select_entity_suid(self, entity_id: int) -> str:
with get_session() as session:
res = session.execute(text("select suid from enterprise where id=:id"),
{"id": entity_id})
return res.fetchone()["suid"]

@ -21,7 +21,7 @@ class EntityIndexHandler(APIHandler):
name = self.tostr(self.get_escaped_argument("name", ""))
with self.app_mysql.connect() as conn:
sql_text = "select id, name, industry, logo, create_at from enterprise where 1=1 "
sql_text = "select id, name, industry, logo, create_time from enterprise where 1=1 "
param = {}
count_sql_text = "select count(id) from enterprise "
@ -61,7 +61,7 @@ class EntityIndexHandler(APIHandler):
"modelCount": modelCount,
"deviceCount": deviceCount,
"logo": item["logo"],
"createTime": str(item["create_at"])
"createTime": str(item["create_time"])
}
)
@ -111,10 +111,11 @@ class EntityAddHandler(APIHandler):
with self.app_mysql.connect() as conn:
conn.execute(
text(
"insert into enterprise(name, province, city, addr, industry, contact, phone, summary, logo, account, pwd) "
"values(:name, :province, :city, :addr, :industry, :contact, :phone, :summary, :logo, :account, :pwd)"
"insert into enterprise(suid, name, province, city, addr, industry, contact, phone, summary, logo, account, pwd) "
"values(:suid, :name, :province, :city, :addr, :industry, :contact, :phone, :summary, :logo, :account, :pwd)"
),
{
"suid": shortuuid.ShortUUID().random(length=10),
"name": name,
"province": province,
"city": city,
@ -227,7 +228,7 @@ class EntityInfoHandler(APIHandler):
"phone": row["phone"],
"summary": row["summary"],
"logo": row["logo"],
"createTime": str(row["create_at"]),
"createTime": str(row["create_time"]),
"account": row["account"], # 企业账号
}

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from website.handlers.enterprise import handler
from website.handlers.enterprise_entity import handler
handlers = [
("/enterprise/entity/index", handler.EntityIndexHandler),

@ -0,0 +1,122 @@
# -*- coding: utf-8 -*-
from typing import List, Dict, Any
from sqlalchemy import text
from website.db import get_session, to_json_list
"""
CREATE TABLE `enterprise_node` (
`id` int NOT NULL AUTO_INCREMENT,
`entity_suid` int NOT NULL COMMENT '企业uuid',
`name` varchar(255) DEFAULT '' COMMENT '企业name',
`parent` int DEFAULT NULL,
`addr` varchar(255) DEFAULT '',
`lola` varchar(255) DEFAULT '',
`contact` varchar(255) DEFAULT '',
`phone` varchar(255) DEFAULT '',
`comment` varchar(255) DEFAULT '',
`del` int DEFAULT '0',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='企业节点表'
"""
class EnterpriseNodeDB(object):
def insert_node(self, node: dict) -> int:
with get_session() as session:
session.execute(
text(
"insert into "
"enterprise_node(suid, entity_id, entity_suid, name, parent, addr, lola, contact, phone, comment) "
"values (:suid, :entity_id, :entity_suid, :name, :parent, :addr, :lola, :contact, :phone, :comment)"
), node)
# last_insert_id = session.execute(text("SELECT LAST_INSERT_ID()")).scalar()
# logging.info(f"last_insert_id: {last_insert_id}")
return 0
def update_node(self, node: dict) -> int:
with get_session() as session:
sql = ("update enterprise_node "
"set name=:name, parent=:parent, addr=:addr, lola=:lola, contact=:contact, phone=:phone, comment=:comment where id=:id")
param = {
"id": node["id"],
"name": node["name"],
"parent": node["parent"],
"addr": node["addr"],
"lola": node["lola"],
"contact": node["contact"],
"phone": node["phone"],
"comment": node["comment"]
}
session.execute(text(sql), param)
return 0
def select_tree(self, entity_id: int, name: str = "") -> List[Dict[str, Any]]:
roots = []
with get_session() as session:
sql = "select id, name, suid from enterprise_node where entity_id=:entity_id and del=0 and parent=0 "
param = {"entity_id": entity_id}
if name:
sql += " and name like :name"
param["name"] = f"%{name}%"
res = session.execute(text(sql), param)
node_list = to_json_list(res)
node_list = node_list and node_list or []
for node in node_list:
root = {
"id": node["id"],
"name": node["name"],
"suid": node["suid"],
"children": self.build_tree(session, node, name)
}
roots.append(root)
# return node_list
return roots
def build_tree(self, session: Any, node: Dict[str, Any], name: str = "") -> List[Any]:
sql = "select id, name, suid from enterprise_node where del=0 and parent=:parent"
param = {"parent": node["id"]}
if name:
sql += " and name like :name"
param["name"] = f"%{name}%"
res = session.execute(text(sql), param)
node_list = to_json_list(res)
node_list = node_list and node_list or []
children = []
for node in node_list:
child = {
"id": node["id"],
"name": node["name"],
"suid": node["suid"],
"children": self.build_tree(session, node, name)
}
children.append(child)
return children
def select_node(self, node_id: int) -> Dict[str, Any]:
with get_session() as session:
sql = ("select id, name, parent, addr, lola, contact, phone, comment, suid from enterprise_node "
"where id=:id and del=0")
param = {"id": node_id}
res = session.execute(text(sql), param)
node_list = to_json_list(res)
node_list = node_list and node_list or []
return node_list[0] if node_list else None
def delete_node(self, node_id: int) -> int:
with get_session() as session:
sql = ("update enterprise_node set del=1 where id=:id")
param = {"id": node_id}
session.execute(text(sql), param)
return 0

@ -1,12 +1,198 @@
# -*- coding: utf-8 -*-
import logging
from sqlalchemy import text
from website import errors
from website import settings
from website import consts
from website import db
from website.util import shortuuid, aes
from website.service import enterprise
from website.handler import APIHandler, authenticated
from website.handlers.enterprise_entity import db as DB_Entity
from website.handlers.enterprise_node import db as DB_Node
from website.util import shortuuid
class AddHandler(APIHandler):
"""
- 描述添加企业节点
- 请求方式post
- 请求参数
>- entity_suid, int, 企业id, short uuid
>- name, string, 名称
>- parent, int, 上级节点id
>- addr, string, 地址
>- lola, string, 经纬度longitude and latitude
>- contact, string, 负责人
>- phone, string, 联系方式
>- comment, string, 简介
- 返回值
"""
# @authenticated
def post(self):
entity_id = self.get_int_argument("entity_suid")
entity_suid = self.get_escaped_argument("entity_suid", "")
name = self.get_escaped_argument("name", "")
parent = self.get_int_argument("parent", 0)
addr = self.get_escaped_argument("addr", "")
lola = self.get_escaped_argument("lola", "")
contact = self.get_escaped_argument("contact", "")
phone = self.get_escaped_argument("phone", "")
comment = self.get_escaped_argument("comment", "")
if not entity_id or not name:
raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "参数错误")
db_entity = DB_Entity.EnterpriseEntityDB()
entity_suid = db_entity.select_entity_suid(entity_id)
db_node = DB_Node.EnterpriseNodeDB()
db_node.insert_node({
"suid": shortuuid.ShortUUID().random(length=10),
"entity_id": entity_id,
"entity_suid": entity_suid,
"name": name,
"parent": parent,
"addr": addr,
"lola": lola,
"contact": contact,
"phone": phone,
"comment": comment
})
self.finish()
class UpdateHandler(APIHandler):
"""
- 描述更新企业节点
- 请求方式post
- 请求参数
>- node_id, int, 节点id
>- name, string, 名称
>- parent, int, 上级节点id
>- addr, string, 地址
>- lola, string, 经纬度longitude and latitude
>- contact, string, 负责人
>- phone, string, 联系方式
>- comment, string, 简介
- 返回值
"""
# @authenticated
def post(self):
node_id = self.get_int_argument("node_id", 0)
name = self.get_escaped_argument("name", "")
parent = self.get_int_argument("parent", 0)
addr = self.get_escaped_argument("addr", "")
lola = self.get_escaped_argument("lola", "")
contact = self.get_escaped_argument("contact", "")
phone = self.get_escaped_argument("phone", "")
comment = self.get_escaped_argument("comment", "")
if not node_id or not name:
raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "参数错误")
db_node = DB_Node.EnterpriseNodeDB()
db_node.update_node({
"node_id": node_id,
"name": name,
"parent": parent,
"addr": addr,
"lola": lola,
"contact": contact,
"phone": phone,
"comment": comment
})
self.finish()
class TreeHandler(APIHandler):
"""
- 描述企业节点树
- 请求方式post
- 请求参数
>- entity_id, int, 企业id
>- name, string, 搜索内容
- 返回值
```
{
"data":[
{
"id": 123,
"name": "xxx",
"children": [
{
"id": 123,
"name": "xxx"
"children": [
{
"id": 123,
"name": "xxx"
},
]
},
...
]
},
...
]
}
```
"""
@authenticated
def post(self):
entity_id = self.get_escaped_argument("entity_id", "")
name = self.get_escaped_argument("name", "")
if not entity_id:
raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "参数错误")
db_node = DB_Node.EnterpriseNodeDB()
nodes = db_node.select_tree(entity_id, name)
self.finish({
"data": nodes
})
class InfoHandler(APIHandler):
"""
- 描述企业节点信息
- 请求方式post
- 请求参数
>- node_id, int, 节点id
- 返回值
```
{
"name": "xxx",
"parent": "xxx",
"addr": "xxx",
"lola": "xxx",
"contact": "xxx",
"phone": "xxx",
"comment": "xxx",
}
```
"""
@authenticated
def post(self):
node_id = self.get_int_argument("node_id")
if not node_id:
raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "参数错误")
db_node = DB_Node.EnterpriseNodeDB()
node = db_node.select_node(node_id)
node = node and node or {}
self.finish(node)
class DeleteHandler(APIHandler):
@authenticated
def post(self):
node_id = self.get_int_argument("node_id")
if not node_id:
raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "参数错误")
db_node = DB_Node.EnterpriseNodeDB()
db_node.delete_node(node_id)
self.finish()

@ -0,0 +1,14 @@
# -*- coding: utf-8 -*-
from website.handlers.enterprise_node import handler
handlers = [
('/enterprise/entity/nodes/add', handler.AddHandler),
('/enterprise/entity/nodes/update', handler.UpdateHandler),
('/enterprise/entity/nodes', handler.TreeHandler),
('/enterprise/entity/nodes/info', handler.InfoHandler),
('/enterprise/entity/nodes/delete', handler.DeleteHandler),
]
page_handlers = [
]

@ -105,7 +105,7 @@ class ListHandler(APIHandler):
result = []
with self.app_mysql.connect() as conn:
sql = "select m.id, m.name, m.model_type, m.default_version, mc.name classification_name, m.update_at " \
sql = "select m.id, m.name, m.model_type, m.default_version, mc.name classification_name, m.update_time " \
"from model m left join model_classification mc on m.classification=mc.id where m.del=0 "
param = {}
@ -137,7 +137,7 @@ class ListHandler(APIHandler):
"model_type": consts.model_type_map[item["model_type"]],
"classification_name": item["classification_name"],
"default_version": item["default_version"],
"update_time": str(item["update_at"])
"update_time": str(item["update_time"])
})
self.finish({"data": data, "count": count})
@ -197,7 +197,7 @@ class EditHandler(APIHandler):
text(
"""update model
set name=:name, model_type=:model_type, classification=:classification, comment=:comment,
update_at=NOW()
update_time=NOW()
where id=:id"""),
{"name": name, "model_type": model_type, "classification": classification, "comment": comment,
"id": mid}
@ -222,7 +222,7 @@ class InfoHandler(APIHandler):
with self.app_mysql.connect() as conn:
cur = conn.execute(
text(
"""select m.name, mc.name as classification_name, m.comment, m.update_at
"""select m.name, mc.name as classification_name, m.comment, m.update_time
from model m, model_classification mc where m.id=:id and m.classification=c.id"""),
{"id": mid}
)
@ -235,7 +235,7 @@ class InfoHandler(APIHandler):
"name": result["name"],
"classification_name": result["classification_name"],
"comment": result["comment"],
"update_time": str(result["update_at"])
"update_time": str(result["update_time"])
}
self.finish(data)
@ -296,7 +296,7 @@ class VersionAddHandler(APIHandler):
text(
"""
insert into model_version
(model_id, version, comment,model_file, config_file, config_str, created_at, update_at)
(model_id, version, comment,model_file, config_file, config_str, created_at, update_time)
values (:model_id, :version, :comment, :model_file, :config_file, :config_str, NOW(), NOW())"""
),
@ -342,7 +342,7 @@ class VersionEditHandler(APIHandler):
text(
"update model_version "
"set version=:version, comment=:comment, model_file=:model_file, config_file=:config_file, "
"config_str=:config_str, update_at=NOW() where id=:id"),
"config_str=:config_str, update_time=NOW() where id=:id"),
{"version": version, "comment": comment, "model_file": model_file, "config_file": config_file,
"config_str": config_str, "id": version_id}
)
@ -393,7 +393,7 @@ class VersionListHandler(APIHandler):
cur = conn.execute(
text(
"""
select mv.id as version_id, mv.version, mv.model_file, mv.update_at, mv.is_default, f.filepath, f.filesize
select mv.id as version_id, mv.version, mv.model_file, mv.update_time, mv.is_default, f.filepath, f.filesize
from model_version mv
left join files f on mv.model_file=f.md5
where mv.model_id=:mid and mv.del=0
@ -419,12 +419,12 @@ class VersionListHandler(APIHandler):
for item in result:
data.append({
"version_id": item["version_id"], # 版本id
"version": item["version"], # 版本号
"path": item["filepath"], # 文件路径
"version_id": item["version_id"], # 版本id
"version": item["version"], # 版本号
"path": item["filepath"], # 文件路径
"size": item["filesize"],
"update_time": str(item["update_at"]),
"is_default": item["is_default"] # 是否默认1/默认0/非默认
"update_time": str(item["update_time"]),
"is_default": item["is_default"] # 是否默认1/默认0/非默认
})
self.finish({"count": count, "data": data})

@ -45,7 +45,7 @@ class ListHandler(APIHandler):
count = 0
with self.app_mysql.connect() as conn:
sql = "select id, name, create_at, update_at from model_hub where 1=1"
sql = "select id, name, create_time, update_time from model_hub where 1=1"
param = {}
sql_count = "select count(id) from model where 1=1"
@ -72,8 +72,8 @@ class ListHandler(APIHandler):
data.append({
"id": item["id"],
"name": item["name"],
"create_time": item["create_at"].strftime("%Y-%m-%d %H:%M:%S"),
"update_time": item["update_at"].strftime("%Y-%m-%d %H:%M:%S")
"create_time": item["create_time"].strftime("%Y-%m-%d %H:%M:%S"),
"update_time": item["update_time"].strftime("%Y-%m-%d %H:%M:%S")
})
self.finish({"count": count, "data": data})
@ -141,7 +141,7 @@ class AddHandler(APIHandler):
raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "name and host and port must be provided.")
with self.app_mysql.connect() as conn:
conn.execute(text("""insert into model_hub (name, host, port, path, comment, create_at, update_at)
conn.execute(text("""insert into model_hub (name, host, port, path, comment, create_time, update_time)
values (:name, :host, :port, :path, :comment, NOW(), NOW())"""),
{"name": name, "host": host, "port": port, "path": path, "comment": comment})
@ -174,7 +174,7 @@ class EditHandler(APIHandler):
if not id or not name or not host or not port or path:
raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "parameter error")
with self.app_mysql.connect() as conn:
conn.execute(text("""update model_hub set name=:name, host=:host, port=:port, path=:path, comment=:comment, update_at=NOW()
conn.execute(text("""update model_hub set name=:name, host=:host, port=:port, path=:path, comment=:comment, update_time=NOW()
where id=:id"""), {"id": id, "name": name, "host": host, "port": port, "path": path, "comment": comment})
conn.commit()
self.finish()

@ -100,11 +100,11 @@ class ActivateInfoHandler(APIHandler):
date_remain = 0
row = self.db_app.get(
"select create_at, expireat from license limit 1"
"select create_time, expireat from license limit 1"
)
if row:
license_str = open(settings.rsa_license_file, 'r').read()
activate_at = str(row["create_at"])
activate_at = str(row["create_time"])
expire_at = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(row["expireat"])))
now = datetime.datetime.now()
delta = (datetime.datetime.fromtimestamp(int(row["expireat"])).date() - now.date()).days

Loading…
Cancel
Save