1、完成首页的接口开发

2、完成文件上传下载
3、模型的部分接口实现
main
周平 1 year ago
parent 2406ef5c95
commit eee871a2da

@ -144,12 +144,12 @@ class Application(tornado.web.Application):
autoescape=None,
)
self.db_app = Connection(
settings.mysql_app["host"],
settings.mysql_app["database"],
user=settings.mysql_app["user"],
password=settings.mysql_app["password"],
time_zone=settings.mysql_app["time_zone"])
# self.db_app = Connection(
# settings.mysql_app["host"],
# settings.mysql_app["database"],
# user=settings.mysql_app["user"],
# password=settings.mysql_app["password"],
# time_zone=settings.mysql_app["time_zone"])
self.app_mysql = app_engine
@ -204,7 +204,10 @@ def main():
# handler.addFilter(PwdFilter())
app = Application()
app.listen(options.port)
# app.listen(options.port)
server = tornado.httpserver.HTTPServer(app, max_buffer_size=104857600*3)
server.listen(options.port)
# def ping():
# try:

@ -86,9 +86,9 @@ class BaseHandler(BaseRequestHandler):
self.set_header("Cache-control", "no-cache")
return super(BaseHandler, self).render(template_name, **kwargs)
@property
def db_app(self):
return self.application.db_app
# @property
# def db_app(self):
# return self.application.db_app
@property
def app_mysql(self):
@ -204,7 +204,7 @@ class BaseHandler(BaseRequestHandler):
# self.traffic_threshold()
def set_default_jsonbody(self):
if self.request.headers.get('Content-Type') == 'application/json;charset=UTF-8' and self.request.body:
if self.request.headers.get('Content-Type') == 'application/json' and self.request.body:
# logging.info(self.request.headers.get('Content-Type'))
# if self.request.headers.get('Content-Type') == 'application/json; charset=UTF-8':
json_body = tornado.escape.json_decode(self.request.body)

@ -21,19 +21,22 @@ 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 "
sql_text = "select id, name, industry, logo, create_at from enterprise where 1=1 "
param = {}
count_sql_text = "select count(id) from enterprise "
count_param = {}
if name:
sql_text += "where name like :name"
sql_text += "and name like :name"
param["name"] = "%{}%".format(name)
count_sql_text += "where name like :name"
count_sql_text += "and name like :name"
count_param["name"] = "%{}%".format(name)
sql_text += " and del=0"
count_sql_text += " and del=0"
sql_text += " order by id desc limit :pageSize offset :offset"
param["pageSize"] = pageSize
param["offset"] = (pageNo - 1) * pageSize
@ -231,6 +234,24 @@ class EntityInfoHandler(APIHandler):
self.finish(data)
class EntityDeleteHandler(APIHandler):
"""删除企业"""
@authenticated
def post(self):
eid = self.get_int_argument("id")
with self.app_mysql.connect() as conn:
conn.execute(
text("update enterprise set del=1 where id=:id"), {"id": eid}
)
conn.commit()
self.finish()
class EntityPwdcheckHandler(APIHandler):
"""查看企业密码"""

@ -7,6 +7,7 @@ handlers = [
("/enterprise/entity/add", handler.EntityAddHandler),
("/enterprise/entity/edit", handler.EntityEditHandler),
("/enterprise/entity/info", handler.EntityInfoHandler),
("/enterprise/entity/delete", handler.EntityDeleteHandler),
("/enterprise/entity/pwdcheck", handler.EntityPwdcheckHandler),
]

@ -0,0 +1,85 @@
# -*- coding: utf-8 -*-
import logging
import hashlib
import re
import os
from sqlalchemy import text
from website import errors
from website import db
from website import settings
from website.handler import APIHandler, authenticated
class UploadHandler(APIHandler):
@authenticated
def post(self):
file_metas = self.request.files.get('file', None)
if not file_metas:
raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "请选择文件")
filename = file_metas[0].filename
punctuation = """!"#$%&'()*+,/:;<=>?@[\]^`{|}~ """
regex = re.compile('[%s]' % re.escape(punctuation))
filename = regex.sub("", filename.replace('..', ''))
file_size = len(file_metas[0].body)
logging.info("file_size: %s", file_size)
if file_size > 300 * 1024 * 1024:
raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, 'Exceed 300M size limit')
filetype = filename.split(".") and filename.split(".")[-1] or ""
file_upload_dir = settings.file_upload_dir
os.makedirs(file_upload_dir, exist_ok=True)
md5_str = hashlib.md5(file_metas[0].body).hexdigest()
row = None
with self.app_mysql.connect() as conn:
sql = text("select id from files where md5_str=:md5_str")
cur = conn.execute(sql, {"md5_str": md5_str})
row = cur.fetchone()
if not row:
filepath = os.path.join(settings.file_upload_dir, md5_str + '_' + filename)
if not os.path.exists(filepath):
for meta in file_metas:
# filename = meta['filename']
with open(filepath, 'wb') as f:
f.write(meta['body'])
with self.app_mysql.connect() as conn:
sql = text("insert into files(filename, filepath, md5_str, filetype, user) values(:filename, :filepath, :md5_str, :filetype, :user)")
conn.execute(sql, {"filename": filename, "filepath": filepath, "md5_str": md5_str, "filetype": filetype, "user": self.current_user.id})
conn.commit()
self.finish({"result": md5_str})
class DeleteHandler(APIHandler):
@authenticated
def post(self):
md5_str = self.get_escaped_argument("file_md5", "")
if not md5_str:
raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "file md5 is required")
logging.info("md5_str: %s", md5_str)
row = None
with self.app_mysql.connect() as conn:
sql = text("select filepath from files where md5_str=:md5_str")
cur = conn.execute(sql, {"md5_str": md5_str})
row = db.to_json(cur)
if not row:
raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "file not found")
filepath = row["filepath"]
if os.path.exists(filepath):
os.remove(filepath)
sql_del = text("delete from files where md5_str=:md5_str")
conn.execute(sql_del, {"md5_str": md5_str})
conn.commit()
self.finish()

@ -0,0 +1,11 @@
from website.handlers.file import handler
handlers = [
# ("/", handler.Handler),
("/file/upload", handler.UploadHandler),
("/file/delete", handler.DeleteHandler),
]
page_handlers = [
]

@ -0,0 +1,181 @@
# -*- 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.handler import APIHandler, authenticated
class ClassificationAddHandler(APIHandler):
"""
添加模型分类
"""
@authenticated
def post(self):
name = self.get_escaped_argument("name", "")
if not name:
raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "参数缺失")
if len(name) > 128:
raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "分类名称过长")
with self.app_mysql.connect() as conn:
cur = conn.execute(text("select id from model_classification where name=:name"), name=name)
classification_id = cur.fetchone()[0]
if classification_id:
raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "分类名称重复")
conn.execute(text("""
insert into model_classification (name, created_at) values (:name, NOW())"""),
name=name)
conn.commit()
self.finish()
class ClassificationListHandler(APIHandler):
"""
模型分类列表
"""
@authenticated
def post(self):
with self.app_mysql.connect() as conn:
cur = conn.execute(text("""
select id, name from model_classification"""))
result = db.to_json_list(cur)
self.finish({"data": result})
class ClassificationDeleteHandler(APIHandler):
"""
删除模型分类
"""
@authenticated
def post(self):
classification_id = self.get_int_argument("id")
if not classification_id:
raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "参数缺失")
with self.app_mysql.connect() as conn:
conn.execute(text("""
DELETE FROM model_classification WHERE id=:id"""),
id=classification_id)
self.finish()
class ListHandler(APIHandler):
"""
"""
@authenticated
def post(self):
self.finish()
class AddHandler(APIHandler):
"""
"""
@authenticated
def post(self):
self.finish()
class EditHandler(APIHandler):
"""
"""
@authenticated
def post(self):
self.finish()
class InfoHandler(APIHandler):
"""
"""
@authenticated
def post(self):
self.finish()
class DeleteHandler(APIHandler):
"""
"""
@authenticated
def post(self):
self.finish()
class VersionAddHandler(APIHandler):
"""
"""
@authenticated
def post(self):
self.finish()
class VersionEditHandler(APIHandler):
"""
"""
@authenticated
def post(self):
self.finish()
class VersionListHandler(APIHandler):
"""
"""
@authenticated
def post(self):
self.finish()
class VersionInfoHandler(APIHandler):
"""
"""
@authenticated
def post(self):
self.finish()
class VersionSetDefaultHandler(APIHandler):
"""
"""
@authenticated
def post(self):
self.finish()
class VersionDeleteHandler(APIHandler):
"""
"""
@authenticated
def post(self):
self.finish()

@ -0,0 +1,25 @@
from website.handlers.model import handler
handlers = [
# ("/", handler.Handler),
("/model/classification/add", handler.ClassificationAddHandler),
("/model/classification/list", handler.ClassificationListHandler),
("/model/classification/delete", handler.ClassificationDeleteHandler),
("/model/list", handler.ListHandler),
("/model/add", handler.AddHandler),
("/model/edit", handler.EditHandler),
("/model/info", handler.InfoHandler),
("/model/delete", handler.DeleteHandler),
("/model/version/add", handler.VersionAddHandler),
("/model/version/edit", handler.VersionEditHandler),
("/model/version/list", handler.VersionListHandler),
("/model/version/info", handler.VersionInfoHandler),
("//model/version/setdefault", handler.VersionSetDefaultHandler),
("/model/version/delete", handler.VersionDeleteHandler),
]
page_handlers = [
]

@ -66,11 +66,14 @@ class LoginHandler(APIHandler):
# if wrong_time_lock:
# raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "账号处于冷却期,请稍后再试")
# return
logging.info(self.request.body)
logging.info(self.request.arguments)
logging.info(password)
logging.info("#########################")
if not username or not password:
raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "请输入用户名和密码")
# if not captcha:
# raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "请输入验证码")
# if not captcha_token:

@ -1,19 +1,20 @@
from website.handler import BaseHandler
from sqlalchemy import text
from typing import Any
# 获取企业模型数量
def get_enterprise_model_count(id):
def get_enterprise_model_count(id: int) -> int:
return 0
# 获取企业设备数量
def get_enterprise_device_count(id):
def get_enterprise_device_count(id: int) -> int:
return 0
# 获取所有企业实体数量
def get_enterprise_entity_count(engine):
def get_enterprise_entity_count(engine: Any) -> int:
with engine.connect() as conn:
count_sql_text = "select count(id) from enterprise "
count = conn.execute(text(count_sql_text)).fetchone()
@ -23,9 +24,9 @@ def get_enterprise_entity_count(engine):
return 0
# 获取所有企业模型数量
def get_enterprise_model_count():
def get_enterprise_model_count() -> int:
return 0
# 获取所有企业设备数量
def get_enterprise_device_count():
def get_enterprise_device_count() -> int:
return 0

@ -72,8 +72,10 @@ pwd_aes_key = "FquMBlcVoIkTAmL7"
enterprise_aes_key = "FquMBlcVoIkTAmL7"
rsa_public_file = "/data/gap/public"
rsa_license_file = "/data/gap/license"
file_upload_dir = "/data/fileupload"
rsa_public_file = "/data/app/public"
rsa_license_file = "/data/app/license"
# hashlib.sha256(base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes)).hexdigest()

Loading…
Cancel
Save