#!/bin/python
# -*- coding: utf-8 -*-
# @File : dboperator.py
# @Author: wangms
# @Date : 2019/5/9
# @Brief: 简述报表功能
import os, json, tempfile, re
from threading import Lock
from datetime import datetime
from catalogdb.model import Item, User
BASE_JSON_DB = {
"title": "MyBase",
"items": {},
"lock_item_ids": [],
"items_hash": "",
"users": {},
"version": 0,
"modification_time": ""
}
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
ITEM_ROOT_ID = 0
lock = Lock()
try:
import cPickle as pickle
except ImportError:
import pickle
class JsonEncoderForPersistence(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Item):
return {
"id": obj.id,
"title": obj.title,
"type": obj.type,
"parent_id": obj.parent_id,
"icon_path": obj.icon_path,
"file_path": obj.file_path,
"file_hash": obj.file_hash,
"status": obj.status,
"creation_time": obj.creation_time.strftime(DATETIME_FORMAT) if obj.creation_time else None,
"modification_time": obj.modification_time.strftime(DATETIME_FORMAT) if obj.modification_time else None
}
elif isinstance(obj, User):
return {
"username": obj.username,
"password": obj.password,
"regist_time": obj.regist_time.strftime(DATETIME_FORMAT) if obj.regist_time else None,
"login_time": obj.login_time.strftime(DATETIME_FORMAT) if obj.login_time else None,
"login_host": obj.login_host,
"edit_item_id": obj.edit_item_id,
"edit_start_time": obj.edit_start_time.strftime(DATETIME_FORMAT) if obj.edit_start_time else None
}
elif isinstance(obj, datetime):
return obj.strftime(DATETIME_FORMAT)
return json.JSONEncoder.default(self, obj)
class JsonEncoderForFrontEnd(json.JSONEncoder):
def default(self, o):
if isinstance(o, Item):
if o.children:
return {
"id": o.id,
"name": o.title,
"open": False,
"children": o.children
}
return {
"id": o.id,
"name": o.title,
"open": False
}
return super().default(o)
class DBOperator(object):
def __init__(self, app=None):
self.default_db_file_name = "json.db"
self._temp_db_file = os.path.join(tempfile.gettempdir(), self.default_db_file_name)
self.db_file = None
self._catalog_dict = {}
self._item_dict = {}
self._user_dict = {}
self._current_item_id = ITEM_ROOT_ID
if app:
self.init_db(app)
def init_db(self, app):
self.db_file = app.config.get("JSON_DB_FILE")
create = app.config.get("CREATE_DB_IF_NOT_FOUND")
if os.path.isdir(self.db_file):
child_file = os.path.join(self.db_file, self.default_db_file_name)
if os.path.isfile(child_file):
self.db_file = child_file
elif create:
open(child_file, "w", encoding="utf8").close()
self.db_file = child_file
else:
raise Exception("JSON DB FILE NOT FOUND")
try:
with open(self.db_file, 'r', encoding="utf8") as f:
self._catalog_dict = json.loads(f.read())
except:
with open(self._temp_db_file, "rb") as f:
content = f.read()
self._catalog_dict = pickle.loads(f.read()) if content else []
if not self._catalog_dict:
self._catalog_dict = BASE_JSON_DB
self.select_all_items(reload=True)
self.select_all_users()
def insert_item(self, item: Item, commit=True) -> bool:
parent = self.select_item_by_id(item.parent_id)
if item.parent_id > 0:
assert parent, "PARENT ITEM DOESN'T EXIST"
assert not parent.children or item not in parent.children, \
"ITEM ALREADY EXISTS IN THEN CHILDREN LIST OF PARENT ITEM"
item.id = self.fetch_latest_item_id()
self._item_dict[item.id] = item
if item.parent_id > 0:
parent.children.append(item)
parent.type = "folder"
if commit:
self._store()
return True
def delete_item(self, item: Item, commit=True) -> bool:
if not self.select_item_by_id(item.id):
return True
parent = self.select_item_by_id(item.parent_id)
if item.parent_id > 0:
assert parent, "PARENT ITEM DOESN'T EXIST"
assert parent.children and item in parent.children, \
"ITEM DOESN'T EXIST IN THE CHILDREN LIST OF PARENT ITEM"
parent.children.remove(item)
if not parent.children:
parent.type = "file"
self._item_dict.pop(item.id)
if commit:
self._store()
return True
def update_item(self, item: Item, commit=True) -> bool:
if not self.select_item_by_id(item.id) and item.id > 0:
raise Exception("THIS ITEM DOESN'T EXIST: <{}>".format(item.id))
parent = self.select_item_by_id(item.parent_id)
if item.parent_id > 0:
assert parent, "PARENT ITEM DOESN'T EXIST"
# no need to update the children list of parent item, as this item data is
# synchronization between children list of parent item and self._item_dict.
self._item_dict[item.id] = item
if commit:
self._store()
return True
def commit(self):
self._store()
def select_all_items(self, reload=False):
if reload == False and self._item_dict is not None:
return self._item_dict
self._current_item_id = ITEM_ROOT_ID
items_block = self._catalog_dict.get("items")
if not items_block:
return {}
for block in items_block.values():
item = self._json_block_to_item(block)
if item.id > self._current_item_id:
self._current_item_id = item.id
self._item_dict[item.id] = item
for parent in self._item_dict.values():
for child in self._item_dict.values():
if child.parent_id == parent.id:
parent.children.append(child)
return self._item_dict
def select_item_by_id(self, id):
return self._item_dict.get(id)
def select_items_by_parent_id(self, parent_id):
items = []
if parent_id == 0:
for item in self._item_dict.values():
if item.parent_id == 0:
items.append(item)
return items
parent = self.select_item_by_id(parent_id)
assert parent, "Not Found the parent_id: <{}>".format(parent_id)
return parent.children
def select_items_by_title(self, title, like: bool = False):
items = []
if like:
for item in self._item_dict:
if item.title == title:
items.append(item)
else:
for item in self._item_dict:
if re.match(item.title, title):
items.append(item)
return items
def fetch_catalog_for_font_end(self):
items = self.select_items_by_parent_id(0)
return json.loads(json.dumps(items, cls=JsonEncoderForFrontEnd))
def _json_block_to_item(self, block):
item = Item(
title=block.get("title"),
type=block.get("type"),
parent_id=block.get("parent_id"),
children=[],
icon_path=block.get("ico_path"),
file_path=block.get("file_path"),
file_hash=block.get("file_hash"),
status=block.get("status"),
creation_time=
没有合适的资源?快使用搜索试试~ 我知道了~
温馨提示
【项目资源】: 包含前端、后端、移动开发、操作系统、人工智能、物联网、信息化管理、数据库、硬件开发、大数据、课程资源、音视频、网站开发等各种技术项目的源码。 包括STM32、ESP8266、PHP、QT、Linux、iOS、C++、Java、python、web、C#、EDA、proteus、RTOS等项目的源码。 【项目质量】: 所有源码都经过严格测试,可以直接运行。 功能在确认正常工作后才上传。 【适用人群】: 适用于希望学习不同技术领域的小白或进阶学习者。 可作为毕设项目、课程设计、大作业、工程实训或初期项目立项。 【附加价值】: 项目具有较高的学习借鉴价值,也可直接拿来修改复刻。 对于有一定基础或热衷于研究的人来说,可以在这些基础代码上进行修改和扩展,实现其他功能。 【沟通交流】: 有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 鼓励下载和使用,并欢迎大家互相学习,共同进步。
资源推荐
资源详情
资源评论
收起资源包目录
IdeaNote是一款基于WEB的Markdown笔记应用,支持在多个电脑间笔记数据快速分片同步,可拖拽树形目录管理.zip (94个子文件)
资料总结
setup.py 347B
app.py 2KB
start.bat 1KB
catalogdb
__init__.py 329B
dboperator.py 12KB
fileopeator.py 5KB
model.py 1KB
templates
editor.html 8KB
base.html 3KB
model.py 1KB
core
__init__.py 182B
view.py 3KB
service.py 6KB
sync
__init__.py 129B
git
__init__.py 2KB
test
test_catalogdb.py 1KB
MANIFEST.in 69B
create_table.sql 573B
.gitignore 25B
static
js
jquery.splitter.js 17KB
require.min.js 17KB
jquery.contextmenu.min.js 27KB
bootstrap.min.js 50KB
idea-note.js 6KB
jquery.contextmenu.js 89KB
popper.min.js 19KB
jquery.ztree.exedit.min.js 20KB
jquery.ztree.core.min.js 31KB
highlight.pack.js 46KB
jquery.ztree.exhide.min.js 5KB
jquery.min.js 85KB
marked.min.js 22KB
codemirror
mode
markdown-mode.min.js 14KB
theme
idea.css 2KB
monokai.css 2KB
codemirror.min.js 165KB
codemirror.min.css 6KB
addone
closetag.js 8KB
css
bootstrap.min.css 122KB
font
FontAwesome.otf 60KB
context-menu-icons.woff 2KB
firacode
eot
FiraCode-Bold.eot 99KB
FiraCode-Regular.eot 92KB
FiraCode-Medium.eot 92KB
FiraCode-Light.eot 93KB
ttf
FiraCode-Medium.ttf 221KB
FiraCode-Regular.ttf 223KB
FiraCode-Bold.ttf 254KB
FiraCode-Light.ttf 223KB
FiraCode-Retina.ttf 223KB
woff2
FiraCode-Regular.woff2 79KB
FiraCode-Bold.woff2 85KB
FiraCode-Medium.woff2 78KB
FiraCode-Light.woff2 80KB
woff
FiraCode-Bold.woff 108KB
FiraCode-Light.woff 102KB
FiraCode-Medium.woff 100KB
FiraCode-Regular.woff 100KB
fontawesome-webfont.eot 37KB
fontawesome-webfont.woff 43KB
context-menu-icons.eot 3KB
context-menu-icons.ttf 3KB
fontawesome-webfont.svg 193KB
fontawesome-webfont.ttf 77KB
context-menu-icons.woff2 2KB
railscasts.min.css 921B
jquery.highlighttextarea.min.css 915B
idea-note.css 5KB
img
loading.gif 381B
diy
9.png 467B
3.png 762B
6.png 432B
5.png 710B
4.png 399B
8.png 529B
1_open.png 580B
7.png 534B
1_close.png 601B
2.png 570B
zTreeStandard.gif 5KB
line_conn.gif 45B
zTreeStandard.png 11KB
jquery.splitter.css 2KB
font-awesome.min.css 22KB
jquery.contextmenu.min.css 6KB
zTreeStyle.css 6KB
images
ui-icons_cc0000_256x240.png 5KB
ui-icons_777777_256x240.png 7KB
ui-icons_ffffff_256x240.png 6KB
ui-icons_444444_256x240.png 7KB
ui-icons_555555_256x240.png 7KB
ui-icons_777620_256x240.png 5KB
favicon.ico 47KB
config.py 1KB
共 94 条
- 1
资源评论
妄北y
- 粉丝: 1w+
- 资源: 1万+
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功