@ -1,33 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- encoding: utf-8 -*-
|
||||
'''
|
||||
@Date:2022/07/13 09:44:57
|
||||
'''
|
||||
|
||||
|
||||
from sqlalchemy import or_, asc
|
||||
from Business.Repository import Repository
|
||||
from DataEntity.ClientModels import EntityClient
|
||||
|
||||
|
||||
# 用户操作业务逻辑类
|
||||
class BllClient(Repository):
|
||||
# _instance_lock = threading.Lock()
|
||||
# #实现单例模式
|
||||
# def __new__(cls, *args, **kwargs):
|
||||
# if not hasattr(BllClient, "_instance"):
|
||||
# with BllClient._instance_lock:
|
||||
# if not hasattr(BllClient, "_instance"):
|
||||
# BllClient._instance = object.__new__(cls)
|
||||
# return BllClient._instance
|
||||
|
||||
def __init__(self, entityType=EntityClient):
|
||||
return super().__init__(entityType)
|
||||
|
||||
# 模糊查询根据客户端编号和客户端名字
|
||||
def like_ClientId_or_Name(self, searchValue):
|
||||
return self.findList(or_(EntityClient.client_code.like('%' + searchValue + '%'),
|
||||
EntityClient.client_name.like('%' + searchValue + '%'))).all()
|
||||
|
||||
def getAllClientList(self):
|
||||
return self.findList().order_by(asc(EntityClient.client_code)).all()
|
@ -1,62 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- encoding: utf-8 -*-
|
||||
'''
|
||||
@Date:2022/07/13 10:27:10
|
||||
'''
|
||||
|
||||
# from Common.utils import Utils
|
||||
from DataEntity.HumitureRecordModels import EntityHumitureRecord
|
||||
|
||||
from Business.Repository import Repository
|
||||
|
||||
|
||||
# 功能模块
|
||||
|
||||
|
||||
class BllHumitureRecord(Repository):
|
||||
# _instance_lock = threading.Lock()
|
||||
# #实现单例模式
|
||||
# def __new__(cls, *args, **kwargs):
|
||||
# if not hasattr(BllHumitureRecord, "_instance"):
|
||||
# with BllHumitureRecord._instance_lock:
|
||||
# if not hasattr(BllHumitureRecord, "_instance"):
|
||||
# BllHumitureRecord._instance = object.__new__(cls)
|
||||
# return BllHumitureRecord._instance
|
||||
|
||||
def __init__(self, entityType=EntityHumitureRecord):
|
||||
return super().__init__(entityType)
|
||||
|
||||
# 获取温湿度列表
|
||||
|
||||
def getHumitureList(self, customerId, pageParam):
|
||||
queryStr = 'select * from ((select * from rms_humiture_record where client_id=:client_id) '
|
||||
queryStr += ' union all (select * from rms_humiture_record where client_id!=:client_id order by client_name ASC ) )t order by t.record_date DESC '
|
||||
|
||||
queryCountStr = 'select COUNT(*) from ((select * from rms_humiture_record where client_id=:client_id) '
|
||||
queryCountStr += ' union all (select * from rms_humiture_record where client_id!=:client_id order by client_name ASC ) )t order by t.record_date DESC '
|
||||
# queryParams = {"clientId": CurrentInfo.ClientInfo.client_id}
|
||||
queryParams = {"client_id": customerId}
|
||||
templateList = self.execute(queryStr + ' limit ' + str((pageParam.curPage-1)
|
||||
* pageParam.pageRows)+','+str(pageParam.pageRows), queryParams).fetchall()
|
||||
pageParam.totalRecords = self.execute(
|
||||
queryCountStr, queryParams).fetchone()[0]
|
||||
jsonData = Utils.mysqlTable2Model(templateList)
|
||||
return jsonData
|
||||
|
||||
def insert_one(self, entity):
|
||||
self.insert(entity)
|
||||
|
||||
|
||||
# if __name__ == '__main__':
|
||||
# for x in range(100000):
|
||||
# en = EntityHumitureRecord(
|
||||
# record_id=str(Utils.UUID()),
|
||||
# device_id='',
|
||||
# client_id='72e70542-b70d-11e8-aea5-448a5bc6c418',
|
||||
# client_name='1号终端',
|
||||
# customer_id='',
|
||||
# temperature='30',
|
||||
# humidity='50',
|
||||
# record_date=datetime.datetime.now(),
|
||||
# is_add=1)
|
||||
# BllHumitureRecord().insert_one(en)
|
@ -1,35 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- encoding: utf-8 -*-
|
||||
'''
|
||||
@Date:2022/07/13 11:31:27
|
||||
'''
|
||||
from sqlalchemy import and_, or_
|
||||
|
||||
from Business.Repository import Repository
|
||||
from DataEntity.LogInfoModels import EntityLog
|
||||
|
||||
|
||||
# 功能模块
|
||||
class BllLog(Repository):
|
||||
# _instance_lock = threading.Lock()
|
||||
# #实现单例模式
|
||||
#
|
||||
# def __new__(cls, *args, **kwargs):
|
||||
# if not hasattr(BllLog, "_instance"):
|
||||
# with BllLog._instance_lock:
|
||||
# if not hasattr(BllLog, "_instance"):
|
||||
# BllLog._instance = object.__new__(cls)
|
||||
# return BllLog._instance
|
||||
|
||||
def __init__(self, entityType=EntityLog):
|
||||
return super().__init__(entityType)
|
||||
|
||||
# 查询某个时间段的日志数据
|
||||
def query_LogData_between_time(self, start_time, end_time):
|
||||
self.findList(and_(EntityLog.operate_date >= start_time,
|
||||
EntityLog.operate_date <= end_time))
|
||||
|
||||
# 获取模糊查询日志数据
|
||||
def like_Log_data(self, searchValue):
|
||||
return self.findList(or_(EntityLog.operate_user_name.like('%' + searchValue + '%'),
|
||||
EntityLog.operate_type.like('%' + searchValue + '%')))
|
@ -1,141 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- encoding: utf-8 -*-
|
||||
'''
|
||||
@Date:2022/07/14 08:39:04
|
||||
'''
|
||||
import threading
|
||||
import datetime
|
||||
|
||||
from sqlalchemy import and_, or_
|
||||
|
||||
from Common.utils import Utils
|
||||
from Business.Repository import Repository
|
||||
from DataEntity.MedicamentModels import EntityMedicamentVariety
|
||||
|
||||
from DataEntity.UserModels import EntityUser
|
||||
|
||||
|
||||
# 药剂品种业务逻辑类
|
||||
class BllMedicamentVariety(Repository):
|
||||
_instance_lock = threading.Lock()
|
||||
# #实现单例模式
|
||||
# def __new__(cls, *args, **kwargs):
|
||||
# if not hasattr(BllMedicamentVariety, "_instance"):
|
||||
# with BllMedicamentVariety._instance_lock:
|
||||
# if not hasattr(BllMedicamentVariety, "_instance"):
|
||||
# BllMedicamentVariety._instance = object.__new__(cls)
|
||||
# return BllMedicamentVariety._instance
|
||||
|
||||
def __init__(self, entityType=EntityMedicamentVariety):
|
||||
return super().__init__(entityType)
|
||||
|
||||
# 创建药剂品种
|
||||
def createDrugVariety(
|
||||
self, customerId, name, english, casNumber,
|
||||
purity, total, net_weight_unit, net_weight, tp, entityUser=EntityUser()
|
||||
):
|
||||
entity = self.findEntity(
|
||||
and_(
|
||||
EntityMedicamentVariety.name == name,
|
||||
EntityMedicamentVariety.purity == purity,
|
||||
# EntityMedicamentVariety.Unit == unit,
|
||||
# EntityMedicamentVariety.SpeciUnit == speciUnit,
|
||||
# EntityMedicamentVariety.Speci == speci
|
||||
EntityMedicamentVariety.total == total,
|
||||
EntityMedicamentVariety.net_weight_unit == net_weight_unit,
|
||||
EntityMedicamentVariety.net_weight == net_weight,
|
||||
EntityMedicamentVariety.tp == tp,
|
||||
)
|
||||
)
|
||||
|
||||
if(entity is None):
|
||||
print(entity, 9999999999999999999)
|
||||
entity = EntityMedicamentVariety()
|
||||
entity.variety_id = str(Utils.UUID())
|
||||
entity.customer_id = customerId
|
||||
entity.inventory_warning_value = 10
|
||||
entity.shelf_life_warning_value = 10
|
||||
entity.use_days_warning_value = 10
|
||||
entity.name = name
|
||||
entity.english_name = english
|
||||
entity.cas_number = casNumber
|
||||
entity.purity = purity
|
||||
entity.total = total
|
||||
entity.net_weight_unit = net_weight_unit
|
||||
entity.net_weight = net_weight
|
||||
entity.tp = tp
|
||||
# 库存总数
|
||||
entity.total_count = 1
|
||||
# 在库数量
|
||||
entity.normal_count = 1
|
||||
# 领用数量
|
||||
entity.use_count = 0
|
||||
# 空瓶数量
|
||||
entity.empty_count = 0
|
||||
entity.is_supervise = 0
|
||||
entity.create_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
entity.create_user_id = entityUser.user_id
|
||||
entity.create_user_name = entityUser.real_name
|
||||
self.insert(entity)
|
||||
# else:
|
||||
# # 库存总数 + 1
|
||||
# entity.TotalCount += 1
|
||||
# # 在库数量 + 1
|
||||
# entity.NormalCount += 1
|
||||
# self.update(entity)
|
||||
entity = self.session.merge(entity)
|
||||
return entity
|
||||
|
||||
# 模糊查询根据药剂名称或英文名称查询
|
||||
|
||||
def findEnglishOrChinseNameList(self, params):
|
||||
return self.findList(or_(EntityMedicamentVariety.name.like('%' + params + '%'),
|
||||
EntityMedicamentVariety.english_name.like('%' + params + '%')))
|
||||
|
||||
# #创建药剂品种
|
||||
# def createDrugVariety(self, customerId, name, english, casNumber, purity, unit, speciUnit, speci, entityUser=EntityUser()):
|
||||
# entity = self.findEntity(and_(EntityMedicamentVariety.Name == name, EntityMedicamentVariety.Purity == purity,
|
||||
# EntityMedicamentVariety.Unit == unit, EntityMedicamentVariety.SpeciUnit == speciUnit, EntityMedicamentVariety.Speci == speci))
|
||||
|
||||
# if(entity is None):
|
||||
# print(entity, 9999999999999999999)
|
||||
# entity = EntityMedicamentVariety()
|
||||
# entity.VarietyId = str(Utils.UUID())
|
||||
# entity.CustomerId = customerId
|
||||
# entity.InventoryWarningValue = 10
|
||||
# entity.ShelfLifeWarningValue = 10
|
||||
# entity.UseDaysWarningValue = 10
|
||||
# entity.Name = name
|
||||
# entity.EnglishName = english
|
||||
# entity.CASNumber = casNumber
|
||||
# entity.Purity = purity
|
||||
# entity.Unit = unit
|
||||
# entity.SpeciUnit = speciUnit
|
||||
# # 库存总数
|
||||
# entity.TotalCount = 1
|
||||
# # 在库数量
|
||||
# entity.NormalCount = 1
|
||||
# # 领用数量
|
||||
# entity.UseCount = 0
|
||||
# # 空瓶数量
|
||||
# entity.EmptyCount = 0
|
||||
# entity.IsSupervise = 0
|
||||
# entity.Speci = speci
|
||||
# entity.CreateDate = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
# entity.CreateUserId = entityUser.UserId
|
||||
# entity.CreateUserName = entityUser.RealName
|
||||
# self.insert(entity)
|
||||
# # else:
|
||||
# # # 库存总数 + 1
|
||||
# # entity.TotalCount += 1
|
||||
# # # 在库数量 + 1
|
||||
# # entity.NormalCount += 1
|
||||
# # self.update(entity)
|
||||
# entity = self.session.merge(entity)
|
||||
# return entity
|
||||
|
||||
# # 模糊查询根据药剂名称或英文名称查询
|
||||
|
||||
# def findEnglishOrChinseNameList(self, params):
|
||||
# return self.findList(or_(EntityMedicamentVariety.Name.like('%' + params + '%'),
|
||||
# EntityMedicamentVariety.EnglishName.like('%' + params + '%')))
|
@ -1,32 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- encoding: utf-8 -*-
|
||||
'''
|
||||
@Date:2022/07/13 08:39:51
|
||||
'''
|
||||
from Business.Repository import Repository
|
||||
from DataEntity.UserModels import EntityUser
|
||||
from sqlalchemy import and_
|
||||
|
||||
# 用户操作业务逻辑
|
||||
|
||||
|
||||
class BllUser(Repository):
|
||||
# _instance_lock = threading.Lock()
|
||||
# #实现单例模式
|
||||
# def __new__(cls, *args, **kwargs):
|
||||
# if not hasattr(BllUser, "_instance"):
|
||||
# with BllUser._instance_lock:
|
||||
# if not hasattr(BllUser, "_instance"):
|
||||
# BllUser._instance = object.__new__(cls)
|
||||
# return BllUser._instance
|
||||
|
||||
def __init__(self, entityType=EntityUser):
|
||||
return super().__init__(entityType)
|
||||
|
||||
# 用户账号密码登录
|
||||
def login(self, userAccount, userPwd):
|
||||
print(userAccount, userPwd,
|
||||
"++++++++++++++++++++++++++++++++++++++++++++++++++")
|
||||
print(self.findEntity(and_(EntityUser.account ==
|
||||
userAccount, EntityUser.password == userPwd)))
|
||||
return self.findEntity(and_(EntityUser.account == userAccount, EntityUser.password == userPwd))
|
@ -1,32 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- encoding: utf-8 -*-
|
||||
'''
|
||||
@Date:2022/07/13 17:07:42
|
||||
'''
|
||||
import threading
|
||||
from sqlalchemy import or_, desc
|
||||
|
||||
from DataEntity.WarningModels import EntityWarning
|
||||
from Business.Repository import Repository
|
||||
|
||||
# 功能模块
|
||||
|
||||
|
||||
class BllWarning(Repository):
|
||||
_instance_lock = threading.Lock()
|
||||
# #实现单例模式
|
||||
# def __new__(cls, *args, **kwargs):
|
||||
# if not hasattr(BllWarning, "_instance"):
|
||||
# with BllWarning._instance_lock:
|
||||
# if not hasattr(BllWarning, "_instance"):
|
||||
# BllWarning._instance = object.__new__(cls)
|
||||
# return BllWarning._instance
|
||||
|
||||
def __init__(self, entityType=EntityWarning):
|
||||
return super().__init__(entityType)
|
||||
|
||||
# 定义通过搜索预警对象进行模糊查询
|
||||
def like_warning_list(self, searchValue, page, limi):
|
||||
if len(str(page)) == 0 and len(str(limi)) == 0:
|
||||
return self.findList(or_(EntityWarning.object_name.like('%' + searchValue + '%'), EntityWarning.warning_content.like('%' + searchValue + '%'))).order_by(desc(EntityWarning.warning_date), desc(EntityWarning.is_solve)).all()
|
||||
return self.findList(or_(EntityWarning.object_name.like('%' + searchValue + '%'), EntityWarning.warning_content.like('%' + searchValue + '%'))).order_by(desc(EntityWarning.warning_date), desc(EntityWarning.is_solve)).offset((page-1)*limi).limit(limi).all()
|
@ -1,52 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- encoding: utf-8 -*-
|
||||
'''
|
||||
@Date:2022/07/13 09:42:59
|
||||
'''
|
||||
import json
|
||||
import datetime
|
||||
import decimal
|
||||
from sqlalchemy.ext.declarative import DeclarativeMeta
|
||||
|
||||
|
||||
# sqlalchemy对象编码转换类
|
||||
class AlchemyEncoder(json.JSONEncoder):
|
||||
# def _iterencode(self, o, markers=None):
|
||||
# if isinstance(o, decimal.Decimal):
|
||||
# return str(o)
|
||||
# return super(AlchemyEncoder, self)._iterencode(o, markers)
|
||||
def default(self, obj):
|
||||
if isinstance(obj, decimal.Decimal):
|
||||
return str(obj)
|
||||
elif isinstance(obj, datetime.datetime):
|
||||
return obj.isoformat()
|
||||
elif isinstance(obj, datetime.date):
|
||||
return obj.isoformat()
|
||||
if isinstance(obj.__class__, DeclarativeMeta):
|
||||
# SQLAlchemy类
|
||||
fields = {}
|
||||
for field in [x for x in dir(obj) if not x.startswith('_') and x != 'metadata']:
|
||||
data = obj.__getattribute__(field)
|
||||
try:
|
||||
json.dumps(data) # 序列化对象
|
||||
fields[field] = data
|
||||
if data is None:
|
||||
fields[field] = ''
|
||||
except TypeError: # 添加了对datetime的处理
|
||||
if data is None:
|
||||
fields[field] = ''
|
||||
if isinstance(data, datetime.datetime):
|
||||
fields[field] = data.isoformat()
|
||||
elif isinstance(data, datetime.date):
|
||||
fields[field] = data.isoformat()
|
||||
elif isinstance(data, datetime.timedelta):
|
||||
fields[field] = (
|
||||
datetime.datetime.min + data).time().isoformat()
|
||||
elif isinstance(data, decimal.Decimal):
|
||||
fields[field] = str(data)
|
||||
else:
|
||||
fields[field] = None
|
||||
# Json编码字典
|
||||
return fields
|
||||
|
||||
return json.JSONEncoder.default(self, obj)
|
@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- encoding: utf-8 -*-
|
||||
'''
|
||||
@Date:2022/07/18 15:14:51
|
||||
'''
|
||||
import json
|
||||
from werkzeug.exceptions import HTTPException
|
||||
|
||||
class APIException(HTTPException):
|
||||
|
||||
code = -1
|
||||
msg = "请求错误"
|
||||
data = []
|
||||
|
||||
def __init__(self, code=None, msg=None, data=None, headers=None):
|
||||
if code:
|
||||
self.code = code
|
||||
if msg:
|
||||
self.msg = msg
|
||||
if data:
|
||||
self.data = data
|
||||
super(APIException, self).__init__(msg, None)
|
||||
|
||||
def get_body(self, environ=None, scope=None):
|
||||
body = dict(
|
||||
code=self.code,
|
||||
msg=self.msg,
|
||||
data=self.data
|
||||
)
|
||||
text = json.dumps(body)
|
||||
return text
|
||||
|
||||
def get_headers(self, environ=None, scope=None):
|
||||
return [('Content-Type', 'application/json')]
|
@ -0,0 +1,61 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- encoding: utf-8 -*-
|
||||
'''
|
||||
@Date:2022/07/18 16:10:20
|
||||
'''
|
||||
import os
|
||||
import time
|
||||
|
||||
import logging
|
||||
import logging.handlers
|
||||
|
||||
class logUtil(object):
|
||||
def __init__(self):
|
||||
self.logger = logging.getLogger("")
|
||||
# 设置输出的等级
|
||||
LEVELS = {'NOSET': logging.NOTSET,
|
||||
'DEBUG': logging.DEBUG,
|
||||
'INFO': logging.INFO,
|
||||
'WARNING': logging.WARNING,
|
||||
'ERROR': logging.ERROR,
|
||||
'CRITICAL': logging.CRITICAL}
|
||||
# 创建文件目录
|
||||
logs_dir = "logs/{0}".format(time.strftime("%Y-%m", time.localtime()))
|
||||
if os.path.exists(logs_dir) and os.path.isdir(logs_dir):
|
||||
pass
|
||||
else:
|
||||
os.makedirs(logs_dir)
|
||||
# 修改log保存位置
|
||||
timestamp = time.strftime("%Y-%m-%d", time.localtime())
|
||||
logfilename = '%s.txt' % timestamp
|
||||
logfilepath = os.path.join(logs_dir, logfilename)
|
||||
rotatingFileHandler = logging.handlers.RotatingFileHandler(filename=logfilepath,
|
||||
maxBytes=1024 * 1024 * 50,
|
||||
backupCount=5)
|
||||
# 设置输出格式
|
||||
formatter = logging.Formatter(
|
||||
'[%(asctime)s] %(filename)s->%(funcName)s line:%(lineno)d [%(levelname)s]%(message)s')
|
||||
rotatingFileHandler.setFormatter(formatter)
|
||||
# 控制台句柄
|
||||
console = logging.StreamHandler()
|
||||
console.setLevel(logging.NOTSET)
|
||||
console.setFormatter(formatter)
|
||||
# 添加内容到日志句柄中
|
||||
self.logger.addHandler(rotatingFileHandler)
|
||||
self.logger.addHandler(console)
|
||||
self.logger.setLevel(logging.NOTSET)
|
||||
|
||||
def info(self, message):
|
||||
self.logger.info(message)
|
||||
|
||||
def debug(self, message):
|
||||
self.logger.debug(message)
|
||||
|
||||
def warning(self, message):
|
||||
self.logger.warning(message)
|
||||
|
||||
def error(self, message):
|
||||
self.logger.error(message)
|
||||
|
||||
|
||||
logger = logUtil()
|
@ -1,49 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- encoding: utf-8 -*-
|
||||
'''
|
||||
@Date:2022/07/14 13:59:09
|
||||
'''
|
||||
|
||||
|
||||
import json
|
||||
import time
|
||||
import os
|
||||
|
||||
|
||||
class GetDrugTypeData:
|
||||
|
||||
# 初始化只打开一次
|
||||
data = None
|
||||
|
||||
@classmethod
|
||||
def init(cls):
|
||||
cls.data = cls.open_text()
|
||||
|
||||
# 打开json文件
|
||||
@classmethod
|
||||
def open_text(cls):
|
||||
|
||||
with open(os.path.abspath('.')+'/Common/ReagentDB.json', 'r', encoding='utf-8') as f:
|
||||
content = json.loads(f.read())
|
||||
return content
|
||||
|
||||
# 模糊搜索
|
||||
@classmethod
|
||||
def search_data(cls, search_word):
|
||||
data_list = []
|
||||
for drug_dict in cls.data:
|
||||
if drug_dict['ChineseName'].find(search_word) != -1 or drug_dict['EnglishName'].find(search_word) != -1:
|
||||
new_dict = {}
|
||||
new_dict['id'] = drug_dict['CASNumber']
|
||||
new_dict['value'] = drug_dict['ChineseName']
|
||||
new_dict['subvalue'] = drug_dict['AliasName']
|
||||
new_dict['EnglishName'] = drug_dict['EnglishName']
|
||||
data_list.append(new_dict)
|
||||
# 根据列表的字典的key的长度进行排序
|
||||
data_list.sort(key=lambda i: len(i['value']))
|
||||
return data_list[:5]
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
GetDrugTypeData.init()
|
||||
print(GetDrugTypeData().search_data('甲醛'))
|
@ -1,39 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- encoding: utf-8 -*-
|
||||
'''
|
||||
@Date:2022/07/13 14:37:18
|
||||
'''
|
||||
|
||||
|
||||
def model_name_loer(db_model):
|
||||
for i in db_model.split("\n"):
|
||||
base = i.split(" = ")
|
||||
if len(base) < 2:
|
||||
continue
|
||||
# print(base)
|
||||
name = ""
|
||||
base_name = base[0].replace(" ", '')
|
||||
for k, v in enumerate(base_name):
|
||||
if k != 0 and name and v.isupper():
|
||||
name += '_'
|
||||
if v.isupper():
|
||||
name += v.lower()
|
||||
else:
|
||||
name += v
|
||||
base_d = base[1].replace(" ", '')
|
||||
comment = base_d.split("#")
|
||||
try:
|
||||
db_comment = comment[1]
|
||||
except IndexError:
|
||||
db_comment = ''
|
||||
|
||||
comment_name = comment[0][:-1] + f', comment="{db_comment}")'
|
||||
print(f"{name} = {comment_name}")
|
||||
|
||||
|
||||
def create_table(Base):
|
||||
from sqlalchemy import create_engine
|
||||
engine = create_engine('mysql+mysqldb://root:123456@localhost:3306/local_rms_db',
|
||||
pool_recycle=10600, pool_size=100, max_overflow=20)
|
||||
|
||||
Base.metadata.create_all(engine)
|
@ -1,2 +0,0 @@
|
||||
import pymysql
|
||||
pymysql.install_as_MySQLdb()
|
@ -1,261 +0,0 @@
|
||||
"""
|
||||
Django settings for YY_RMS_Multiple_Manage project.
|
||||
|
||||
Generated by 'django-admin startproject' using Django 2.2.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/2.2/topics/settings/
|
||||
|
||||
For the full list of settings and their values, see
|
||||
https://docs.djangoproject.com/en/2.2/ref/settings/
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
|
||||
|
||||
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
|
||||
# Quick-start development settings - unsuitable for production
|
||||
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = '%xoxlv+gx&4$^t8a2nyj56g93ayt-_xl_zl^dy3oru8o)3-r1k'
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = True
|
||||
|
||||
ALLOWED_HOSTS = ['*']
|
||||
|
||||
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = [
|
||||
'django.contrib.admin',
|
||||
'django.contrib.auth',
|
||||
'django.contrib.contenttypes',
|
||||
'django.contrib.sessions',
|
||||
'django.contrib.messages',
|
||||
'django.contrib.staticfiles',
|
||||
|
||||
|
||||
'account',
|
||||
'user',
|
||||
|
||||
|
||||
|
||||
'corsheaders',
|
||||
]
|
||||
|
||||
MIDDLEWARE = [
|
||||
'django.middleware.security.SecurityMiddleware',
|
||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
||||
|
||||
'corsheaders.middleware.CorsMiddleware', # 默认
|
||||
'django.middleware.common.CommonMiddleware',
|
||||
'django.middleware.csrf.CsrfViewMiddleware',
|
||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||
'django.contrib.messages.middleware.MessageMiddleware',
|
||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
|
||||
'user.login_required.LoginRequiredMiddleware',
|
||||
]
|
||||
|
||||
|
||||
# 跨域增加忽略
|
||||
CORS_ALLOW_CREDENTIALS = True
|
||||
CORS_ORIGIN_ALLOW_ALL = True
|
||||
|
||||
CORS_ALLOW_METHODS = (
|
||||
'DELETE',
|
||||
'GET',
|
||||
'OPTIONS',
|
||||
'PATCH',
|
||||
'POST',
|
||||
'PUT',
|
||||
'VIEW',
|
||||
)
|
||||
CORS_ALLOW_HEADERS = (
|
||||
'XMLHttpRequest',
|
||||
'X_FILENAME',
|
||||
'accept-encoding',
|
||||
'authorization',
|
||||
'content-type',
|
||||
'dnt',
|
||||
'origin',
|
||||
'user-agent',
|
||||
'x-csrftoken',
|
||||
'x-requested-with',
|
||||
)
|
||||
|
||||
|
||||
ROOT_URLCONF = 'YY_RMS_Multiple_Manage.urls'
|
||||
|
||||
TEMPLATES = [
|
||||
{
|
||||
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
||||
'DIRS': [os.path.join(BASE_DIR, 'templates')],
|
||||
'APP_DIRS': True,
|
||||
'OPTIONS': {
|
||||
'context_processors': [
|
||||
'django.template.context_processors.debug',
|
||||
'django.template.context_processors.request',
|
||||
'django.contrib.auth.context_processors.auth',
|
||||
'django.contrib.messages.context_processors.messages',
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
WSGI_APPLICATION = 'YY_RMS_Multiple_Manage.wsgi.application'
|
||||
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
|
||||
}
|
||||
}
|
||||
|
||||
X_FRAME_OPTIONS = 'ALLOWALL url'
|
||||
|
||||
# Password validation
|
||||
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
|
||||
|
||||
AUTH_PASSWORD_VALIDATORS = [
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
# Internationalization
|
||||
# https://docs.djangoproject.com/en/2.2/topics/i18n/
|
||||
|
||||
LANGUAGE_CODE = 'en-us'
|
||||
|
||||
TIME_ZONE = 'Asia/Shanghai'
|
||||
|
||||
USE_I18N = True
|
||||
|
||||
USE_L10N = True
|
||||
|
||||
USE_TZ = True
|
||||
|
||||
SESSION_ENGINE = 'redis_sessions.session'
|
||||
SESSION_REDIS = {
|
||||
'host': 'localhost',
|
||||
'port': 6379,
|
||||
'db': 0,
|
||||
'password': '123456',
|
||||
'prefix': 'session',
|
||||
'socket_timeout': 1
|
||||
}
|
||||
|
||||
# Static files (CSS, JavaScript, Images)
|
||||
# https://docs.djangoproject.com/en/2.2/howto/static-files/
|
||||
|
||||
STATIC_URL = '/static/'
|
||||
STATICFILES_DIRS = [
|
||||
os.path.join(BASE_DIR, 'static')
|
||||
]
|
||||
|
||||
# 部署路径
|
||||
|
||||
STATIC_ROOT = '../YY_RMS_Multiple_Manage/static_files'
|
||||
|
||||
|
||||
# 程序运行时加载 只加载一次
|
||||
from Common.searchDrug import GetDrugTypeData
|
||||
GetDrugTypeData.init()
|
||||
flag_ = True
|
||||
|
||||
# 日志管理器
|
||||
# 给过滤器使用的判断
|
||||
|
||||
|
||||
class RequireDebugTrue(logging.Filter):
|
||||
# 实现filter方法
|
||||
def filter(self, record):
|
||||
return DEBUG
|
||||
|
||||
|
||||
log_file_path = os.path.join(BASE_DIR, 'runserver_log')
|
||||
if not os.path.exists(log_file_path):
|
||||
os.makedirs(log_file_path)
|
||||
print("日志文件夹创建成功~~~~~~~~~~~~~~~~~~~")
|
||||
|
||||
|
||||
LOGGING = {
|
||||
# 基本设置
|
||||
'version': 1, # 日志级别
|
||||
'disable_existing_loggers': False, # 是否禁用现有的记录器
|
||||
|
||||
# 日志格式集合
|
||||
'formatters': {
|
||||
# 标准输出格式
|
||||
'standard': {
|
||||
# [具体时间][日志名字:日志级别名称(日志级别ID)] [输出的模块:输出的函数]:调用日志输出函数的语句所在的代码行-日志内容
|
||||
'format': '具体时间:[%(asctime)s][%(name)s:%(levelname)s(%(lineno)d)]\n当前文件位置:[%(pathname)s]'
|
||||
'模块名:[%(module)s:]函数名:[%(funcName)s]:\n[第%(lineno)d行]-%(message)s\n'
|
||||
}
|
||||
},
|
||||
|
||||
# 过滤器
|
||||
'filters': {
|
||||
'require_debug_true': {
|
||||
'()': RequireDebugTrue,
|
||||
}
|
||||
},
|
||||
|
||||
# 处理器集合
|
||||
'handlers': {
|
||||
# 输出到控制台
|
||||
'console': {
|
||||
'level': 'DEBUG', # 输出信息的最低级别
|
||||
'class': 'logging.StreamHandler',
|
||||
'formatter': 'standard', # 使用standard格式
|
||||
'filters': ['require_debug_true', ], # 仅当 DEBUG = True 该处理器才生效
|
||||
},
|
||||
# 输出到文件
|
||||
'log': {
|
||||
'level': 'DEBUG',
|
||||
'class': 'logging.handlers.RotatingFileHandler',
|
||||
'formatter': 'standard',
|
||||
# 输出位置
|
||||
# 'filename': os.path.join(BASE_DIR, 'runserver_log/%s.log' % time.strftime('%Y_%m_%d')),
|
||||
'filename': os.path.join(log_file_path, '%s.log' % time.strftime('%Y_%m_%d')),
|
||||
'maxBytes': 1024*1024*5, # 文件大小 5M
|
||||
'backupCount': 5, # 备份份数
|
||||
'encoding': 'utf8', # 文件编码
|
||||
|
||||
},
|
||||
},
|
||||
|
||||
# 日志管理器集合
|
||||
'loggers': {
|
||||
# 管理器
|
||||
'default': {
|
||||
'handlers': ['console', 'log'],
|
||||
'level': 'DEBUG',
|
||||
'propagate': True, # 是否传递给父记录器
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
from Common.SupervisionWarning import SupervisionWarning
|
||||
SupervisionWarning().supervision_start()
|
@ -1,33 +0,0 @@
|
||||
"""YY_RMS_Multiple_Manage URL Configuration
|
||||
|
||||
The `urlpatterns` list routes URLs to views. For more information please see:
|
||||
https://docs.djangoproject.com/en/2.2/topics/http/urls/
|
||||
Examples:
|
||||
Function views
|
||||
1. Add an import: from my_app import views
|
||||
2. Add a URL to urlpatterns: path('', views.home, name='home')
|
||||
Class-based views
|
||||
1. Add an import: from other_app.views import Home
|
||||
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
|
||||
Including another URLconf
|
||||
1. Import the include() function: from django.urls import include, path
|
||||
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
|
||||
"""
|
||||
from django.contrib import admin
|
||||
from django.urls import path, re_path
|
||||
from django.conf.urls import include
|
||||
from django.conf.urls.static import static
|
||||
from django.conf import settings
|
||||
|
||||
from . import views
|
||||
urlpatterns = [
|
||||
# path('admin/', admin.site.urls),
|
||||
path("^$", view=views.home, name="home"),
|
||||
# 登录相关接口
|
||||
re_path('^account/', include("account.urls")),
|
||||
|
||||
|
||||
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
|
||||
|
||||
|
||||
handler404 = 'YY_RMS_Multiple_Manage.views.page_not_found'
|
@ -1,76 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- encoding: utf-8 -*-
|
||||
'''
|
||||
@Date:2022/07/13 17:03:20
|
||||
'''
|
||||
from django.views.decorators.http import require_http_methods
|
||||
from django.shortcuts import HttpResponse, render, redirect
|
||||
|
||||
|
||||
from Business.Warning import BllWarning
|
||||
from Common.utils import Utils, logger
|
||||
from Business.User import BllUser
|
||||
|
||||
|
||||
|
||||
|
||||
@Utils.log_exception
|
||||
@require_http_methods(['GET'])
|
||||
def home(request):
|
||||
# 获取预警数量
|
||||
visitType = ''
|
||||
try:
|
||||
|
||||
user_ = request.session['login_user']
|
||||
user_id = user_["UserId"]
|
||||
user = BllUser().findEntity(user_id)
|
||||
role_id = user.RoleId
|
||||
SQL = """
|
||||
|
||||
SELECT c.module_id, c.module_code, c.sort_index, c.module_name from(SELECT a.module_id, b.module_code,
|
||||
b.sort_index, b.module_name FROM `rms_module_relation` as a LEFT JOIN rms_module as b on a.module_id =
|
||||
b.module_id WHERE object_id = :user_id and object_type = 2 and a.module_type=2 UNION
|
||||
SELECT a.module_id, b.module_code, b.sort_index, b.module_name FROM `rms_module_relation` as a
|
||||
LEFT JOIN rms_module as b on a.module_id = b.module_id WHERE object_id = :role_id and object_type = 1 and a.module_type=2)
|
||||
as c ORDER BY c.sort_index asc;
|
||||
"""
|
||||
module_relation_obj_list = BllUser().execute(
|
||||
SQL, {'user_id': user_id, 'role_id': role_id}).fetchall()
|
||||
module_relation_obj_list = Utils.mysqlTable2Model(
|
||||
module_relation_obj_list)
|
||||
|
||||
# 用列表推导式生成一个ModuleCode列表
|
||||
object_id_list = [x['module_code']
|
||||
for x in module_relation_obj_list]
|
||||
|
||||
print(object_id_list)
|
||||
#SQL = 'SELECT count(*) as number_ FROM `RMS_Warning` WHERE IsSolve = 0 and now() > WarningDate;'
|
||||
SQL = 'SELECT count(*) as number_ FROM `rms_warning` WHERE is_solve = 0'
|
||||
warning_obj = BllWarning().execute(SQL).fetchone()
|
||||
warning_nb = warning_obj.number_
|
||||
try:
|
||||
user = request.session['login_user']
|
||||
roleName = user['RoleName']
|
||||
visitType = request.GET.get('visitType')
|
||||
request.session['visitType'] = visitType
|
||||
# if(((visitType=='1') or (visitType=='2'))):
|
||||
# request.session['visitType']='1'
|
||||
# else:
|
||||
# request.session['visitType']=''
|
||||
request.session.set_expiry(0)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
roleName = ''
|
||||
return render(request, 'home.html', locals())
|
||||
except Exception as e:
|
||||
BllWarning().session.rollback()
|
||||
logger.debug('数据为空', e)
|
||||
return render(request, 'home.html', locals())
|
||||
finally:
|
||||
BllWarning().session.close()
|
||||
|
||||
|
||||
# 404页面处理方案
|
||||
def page_not_found(request, exception):
|
||||
logger.debug('页面没有找到')
|
||||
return HttpResponse('地址错误')
|
@ -1,16 +0,0 @@
|
||||
"""
|
||||
WSGI config for YY_RMS_Multiple_Manage project.
|
||||
|
||||
It exposes the WSGI callable as a module-level variable named ``application``.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.wsgi import get_wsgi_application
|
||||
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'YY_RMS_Multiple_Manage.settings')
|
||||
|
||||
application = get_wsgi_application()
|
@ -1,3 +0,0 @@
|
||||
from django.contrib import admin
|
||||
|
||||
# Register your models here.
|
@ -1,5 +0,0 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class AccountConfig(AppConfig):
|
||||
name = 'account'
|
@ -1,3 +0,0 @@
|
||||
from django.db import models
|
||||
|
||||
# Create your models here.
|
@ -1,3 +0,0 @@
|
||||
from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
@ -1,23 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- encoding: utf-8 -*-
|
||||
'''
|
||||
@Date:2022/07/13 11:04:24
|
||||
'''
|
||||
|
||||
|
||||
from django.urls import path, re_path
|
||||
from django.conf.urls import include
|
||||
from django.conf.urls.static import static
|
||||
from django.conf import settings
|
||||
|
||||
from . import views
|
||||
|
||||
app_name = 'account'
|
||||
|
||||
urlpatterns = [
|
||||
# 登录
|
||||
re_path(r'login/$', views.account_login, name='account_login'),
|
||||
re_path(r'barcode/$', views.account_barcode, name='account_barcode'),
|
||||
# 退出系统
|
||||
re_path(r'logout/$', views.account_logout, name='account_logout'),
|
||||
]
|
@ -1,108 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- encoding: utf-8 -*-
|
||||
'''
|
||||
@Date:2022/07/13 09:32:40
|
||||
'''
|
||||
import datetime
|
||||
import json
|
||||
from django.shortcuts import render, redirect
|
||||
from django.http import JsonResponse
|
||||
from django.views.decorators.http import require_http_methods
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
|
||||
from Common.utils import Utils, logger
|
||||
from Business.User import BllUser
|
||||
from Business.Log import BllLog
|
||||
|
||||
from DataEntity.UserModels import EntityUser
|
||||
from DataEntity.LogInfoModels import EntityLog
|
||||
|
||||
|
||||
def get_user_ip(request):
|
||||
"""
|
||||
获取访问用户ip
|
||||
:param request:
|
||||
:return:
|
||||
"""
|
||||
if 'HTTP_X_FORWARDED_FOR' in request.META:
|
||||
return request.META['HTTP_X_FORWARDED_FOR']
|
||||
else:
|
||||
return request.META['REMOTE_ADDR']
|
||||
|
||||
|
||||
@require_http_methods(['GET', 'POST'])
|
||||
@csrf_exempt
|
||||
def account_login(request):
|
||||
if request.method == 'GET':
|
||||
try:
|
||||
del request.session['login_user']
|
||||
except Exception as e:
|
||||
pass
|
||||
return render(request, 'account/login.html', locals())
|
||||
elif request.method == 'POST':
|
||||
# try:
|
||||
userAccount = request.POST['userAccount']
|
||||
userPassword = Utils.MD5(request.POST['userPassword'])
|
||||
print(userAccount, '-'+userPassword)
|
||||
user = BllUser().login(userAccount, userPassword)
|
||||
print(user, "0000000000000000000000000000000000")
|
||||
if not user:
|
||||
logger.info('账号或密码不正确, 登录失败')
|
||||
return JsonResponse(Utils.resultData(0, '账号或密码不正确, 登录失败'))
|
||||
else:
|
||||
if user.is_enabled == 1:
|
||||
request.session['login_user'] = json.loads(
|
||||
Utils.resultAlchemyData(user))
|
||||
visitType = request.GET.get('visitType')
|
||||
request.session['visitType'] = visitType
|
||||
request.session.set_expiry(0)
|
||||
logger.info('登录成功')
|
||||
user.last_visit_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||
BllUser().update(user)
|
||||
ip_ = get_user_ip(request)
|
||||
|
||||
if ip_ is None:
|
||||
ip_ = ''
|
||||
log_obj = EntityLog(log_id=str(Utils.UUID()), customer_id=user.customer_id, log_type=1,
|
||||
operate_user_id=user.user_id, operate_account=user.account, operate_user_name=user.real_name,
|
||||
operate_type_code='登录后台成功', operate_type='登录成功', ip_address=ip_,
|
||||
execute_result='用户登录后台成功', operate_date=datetime.datetime.now(),
|
||||
is_add=1)
|
||||
BllLog().insert(log_obj)
|
||||
return JsonResponse(Utils.resultData(1, '登录成功', json.loads(Utils.resultAlchemyData(user))))
|
||||
|
||||
else:
|
||||
logger.info(user.role_name + '正在尝试登陆后台管理')
|
||||
return JsonResponse(Utils.resultData(0, '您不是管理员或该账户已被禁用, 暂时无法登陆, 请联系管理员'))
|
||||
|
||||
|
||||
@require_http_methods(['GET'])
|
||||
def account_logout(request):
|
||||
# path = request.META.get('HTTP_REFERER', '/')
|
||||
del request.session['login_user']
|
||||
visitType = request.session.get('visitType')
|
||||
# if(((visitType=='1') or (visitType=='2'))):
|
||||
# return redirect('/account/login?visitType=1')
|
||||
# else:
|
||||
# return redirect('/account/login')
|
||||
if(visitType):
|
||||
return redirect('/account/login?visitType='+visitType)
|
||||
else:
|
||||
return redirect('/account/login')
|
||||
|
||||
|
||||
# 条码登录
|
||||
@require_http_methods(['GET'])
|
||||
def account_barcode(request):
|
||||
barcode = request.GET.get('barCode')
|
||||
user_obj = BllUser().findEntity(EntityUser.bar_code == barcode)
|
||||
if user_obj:
|
||||
if user_obj.IsEnabled == 1:
|
||||
request.session['login_user'] = json.loads(
|
||||
Utils.resultAlchemyData(user_obj))
|
||||
return JsonResponse(Utils.resultData(1, '登录成功'))
|
||||
else:
|
||||
logger.info(user_obj.role_name + '正在尝试登陆后台管理')
|
||||
return JsonResponse(Utils.resultData(0, '该账户已被禁用, 暂时无法登陆, 请联系管理员'))
|
||||
else:
|
||||
return JsonResponse(Utils.resultData(0, '该条码用户不存在!'))
|
@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- encoding: utf-8 -*-
|
||||
'''
|
||||
@Date:2022/07/18 16:28:44
|
||||
'''
|
||||
|
||||
from flask import Blueprint
|
||||
from apps.home import home_router
|
||||
|
||||
all_router = Blueprint('all_router', __name__)
|
||||
all_router.register_blueprint(home_router, url_prefix="/home")
|
@ -0,0 +1,4 @@
|
||||
from flask import Blueprint
|
||||
|
||||
|
||||
home_router = Blueprint('home', __name__)
|
@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- encoding: utf-8 -*-
|
||||
'''
|
||||
@Date:2022/07/18 16:19:33
|
||||
'''
|
||||
|
||||
|
||||
from . import home_router
|
@ -0,0 +1,36 @@
|
||||
# import configparser
|
||||
# import os
|
||||
# from PyQt5.QtCore import *
|
||||
# class SystemConfig(QObject):
|
||||
# """系统配置参数"""
|
||||
# config = configparser.ConfigParser()
|
||||
# configPath=os.getcwd()+'/Config/system.conf'
|
||||
# config.read(configPath)
|
||||
# #获取配置文件值
|
||||
# @classmethod
|
||||
# def getConfig(cls,key):
|
||||
# return cls.config.get('System',key)
|
||||
|
||||
# #设置配置文件值
|
||||
# @classmethod
|
||||
# def setConfig(cls,key,value):
|
||||
# cls.config.set('System',key,value)
|
||||
# cls.config.write(open(cls.configPath,'w'))
|
||||
|
||||
import os
|
||||
import configparser
|
||||
|
||||
class SystemConfig:
|
||||
config = configparser.ConfigParser()
|
||||
configPath = os.getcwd() + '/Config/system.conf'
|
||||
config.read(configPath)
|
||||
|
||||
@classmethod
|
||||
def getConfig(cls, key):
|
||||
return cls.config.get('system', key)
|
||||
|
||||
@classmethod
|
||||
def setConfig(cls, key, value):
|
||||
cls.config.set('system', key, value)
|
||||
cls.config.write(open(cls.configPath, 'w'))
|
||||
|
@ -0,0 +1,77 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- encoding: utf-8 -*-
|
||||
'''
|
||||
@Date:2022/07/18 15:02:28
|
||||
'''
|
||||
import json
|
||||
import datetime
|
||||
import decimal
|
||||
|
||||
from flask import Flask as New_flask
|
||||
from flask.json import JSONEncoder as _JSONEncoder
|
||||
from flask_cors import CORS
|
||||
from sqlalchemy.ext.declarative import DeclarativeMeta
|
||||
|
||||
|
||||
#继承JSONEncoder处理sqlalchemy对象编码转换类
|
||||
class JSONEncoder(_JSONEncoder):
|
||||
def default(self, obj):
|
||||
# if isinstance(obj, decimal.Decimal):
|
||||
# return str(obj)
|
||||
# elif isinstance(obj, datetime.datetime):
|
||||
# return obj.isoformat()
|
||||
# elif isinstance(obj, datetime.date):
|
||||
# return obj.isoformat()
|
||||
if isinstance(obj, decimal.Decimal):
|
||||
return str(obj)
|
||||
elif isinstance(obj, (datetime.datetime, datetime.date)):
|
||||
return obj.isoformat()
|
||||
if isinstance(obj.__class__, DeclarativeMeta):
|
||||
#SQLAlchemy类
|
||||
fields = {}
|
||||
for field in [x for x in dir(obj) if not x.startswith('_') and x != 'metadata']:
|
||||
data = obj.__getattribute__(field)
|
||||
try:
|
||||
json.dumps(data) # 序列化对象
|
||||
fields[field] = data
|
||||
if data is None:
|
||||
fields[field] = ''
|
||||
except TypeError: # 添加了对datetime的处理
|
||||
# if isinstance(data, datetime.datetime):
|
||||
# fields[field] = data.isoformat()
|
||||
# elif isinstance(data, datetime.date):
|
||||
# fields[field] = data.isoformat()
|
||||
if isinstance(data, (datetime.datetime, datetime.date)):
|
||||
fields[field] = data.isoformat()
|
||||
elif isinstance(data, datetime.timedelta):
|
||||
fields[field] = (
|
||||
datetime.datetime.min + data).time().isoformat()
|
||||
elif isinstance(data, decimal.Decimal):
|
||||
fields[field] = float(data)
|
||||
else:
|
||||
fields[field] = None
|
||||
# Json编码字典
|
||||
return fields
|
||||
|
||||
return json.JSONEncoder.default(self, obj)
|
||||
|
||||
|
||||
|
||||
class Flask(New_flask):
|
||||
json_encoder = JSONEncoder
|
||||
|
||||
def register_blueprints(app):
|
||||
"""
|
||||
"""
|
||||
from apps import all_router
|
||||
app.register_blueprint(all_router, url_prefix="/api")
|
||||
|
||||
|
||||
def create_app():
|
||||
app = Flask(__name__)
|
||||
CORS(app)
|
||||
# app.config.from_object('setting')
|
||||
register_blueprints(app)
|
||||
return app
|
||||
|
||||
|
@ -0,0 +1,6 @@
|
||||
[system]
|
||||
clientid = 000
|
||||
serverip = 127.0.0.1
|
||||
port = 9001
|
||||
dbconntion = mysql+pymysql://root:123456@127.0.0.1/local_rms_db?charset=utf8
|
||||
|
@ -0,0 +1,14 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- encoding: utf-8 -*-
|
||||
'''
|
||||
@Date:2022/07/18 16:32:26
|
||||
'''
|
||||
from db_logic.db_base import Repository
|
||||
from models.client_models import EntityClient
|
||||
|
||||
|
||||
|
||||
#用户操作业务逻辑类
|
||||
class BllClient(Repository):
|
||||
def __init__(self, entityType=EntityClient):
|
||||
return super().__init__(entityType)
|
@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- encoding: utf-8 -*-
|
||||
'''
|
||||
@Date:2022/07/18 16:34:13
|
||||
'''
|
||||
from sqlalchemy import and_
|
||||
|
||||
from db_logic.db_base import Repository
|
||||
from models.client_models import EntityClient, EntityClientUser
|
||||
|
||||
#用户操作业务逻辑类
|
||||
class BllClientUser(Repository):
|
||||
|
||||
def __init__(self, entityType=EntityClient):
|
||||
return super().__init__(entityType)
|
||||
|
||||
def isJInZhiUser(self, userId, clientId):
|
||||
entity = self.findEntity(
|
||||
and_(EntityClientUser.user_id == userId, EntityClientUser.client_id == clientId))
|
||||
if(entity is None):
|
||||
return False
|
||||
else:
|
||||
return True
|
@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- encoding: utf-8 -*-
|
||||
'''
|
||||
@Date:2022/07/18 16:51:28
|
||||
'''
|
||||
import sys
|
||||
sys.path.append(".")
|
||||
|
||||
from db_logic.db_base import Repository
|
||||
from models.humiture_models import EntityHumitureRecord
|
||||
from common.utils import Utils
|
||||
|
||||
#日志信息业务逻辑类
|
||||
class BllHumitureRecord(Repository):
|
||||
#_instance_lock = threading.Lock()
|
||||
##实现单例模式
|
||||
#def __new__(cls, *args, **kwargs):
|
||||
# if not hasattr(BllHumitureRecord, "_instance"):
|
||||
# with BllHumitureRecord._instance_lock:
|
||||
# if not hasattr(BllHumitureRecord, "_instance"):
|
||||
# BllHumitureRecord._instance = object.__new__(cls)
|
||||
# return BllHumitureRecord._instance
|
||||
|
||||
def __init__(self, entityType=EntityHumitureRecord):
|
||||
return super().__init__(entityType)
|
||||
|
||||
# 获取温湿度列表
|
||||
|
||||
def getHumitureList(self, customerId, pageParam):
|
||||
queryStr = 'select * from ((select * from rms_humiture_record where client_id=:client_id) '
|
||||
queryStr += ' union all (select * from rms_humiture_record where client_id!=:client_id order by client_name ASC ) )t order by t.record_date DESC '
|
||||
|
||||
queryCountStr = 'select COUNT(*) from ((select * from rms_humiture_record where client_id=:client_id) '
|
||||
queryCountStr += ' union all (select * from rms_humiture_record where client_id!=:client_id order by client_name ASC ) )t order by t.record_date DESC '
|
||||
# queryParams = {"clientId": CurrentInfo.ClientInfo.client_id}
|
||||
queryParams = {"client_id": customerId}
|
||||
templateList = self.execute(queryStr + ' limit ' + str((pageParam.curPage - 1)
|
||||
* pageParam.pageRows) + ',' + str(pageParam.pageRows), queryParams).fetchall()
|
||||
pageParam.totalRecords = self.execute(
|
||||
queryCountStr, queryParams).fetchone()[0]
|
||||
jsonData = Utils.mysqlTable2Model(templateList)
|
||||
return jsonData
|
||||
|
||||
def insert_one(self, entity):
|
||||
self.insert(entity)
|
@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- encoding: utf-8 -*-
|
||||
'''
|
||||
@Date:2022/07/18 16:44:57
|
||||
'''
|
||||
|
||||
from sqlalchemy import and_, or_, desc
|
||||
from db_logic.db_base import Repository
|
||||
from models.user_models import EntityUser
|
||||
from common.utils import Utils
|
||||
|
||||
#用户操作业务逻辑类
|
||||
class BllUser(Repository):
|
||||
#_instance_lock = threading.Lock()
|
||||
##实现单例模式
|
||||
#def __new__(cls, *args, **kwargs):
|
||||
# if not hasattr(BllUser, "_instance"):
|
||||
# with BllUser._instance_lock:
|
||||
# if not hasattr(BllUser, "_instance"):
|
||||
# BllUser._instance = object.__new__(cls)
|
||||
# return BllUser._instance
|
||||
|
||||
def __init__(self, entityType=EntityUser):
|
||||
return super().__init__(entityType)
|
||||
|
||||
#用户账号密码登录
|
||||
def login(self, userAccount, userPwd):
|
||||
d = Utils.MD5(userPwd)
|
||||
print(d)
|
||||
return self.findEntity(and_(EntityUser.Account == userAccount, EntityUser.Password == Utils.MD5(userPwd)))
|
||||
|
||||
#根据条码获取用户
|
||||
def getUserByBarCode(self, barCode):
|
||||
return self.findEntity(EntityUser.BarCode == barCode)
|
||||
|
||||
#获取用户列表
|
||||
def getUserList(self, customerId, pageParam, keyWord=''):
|
||||
keyWord = '%' + keyWord + '%'
|
||||
orm_query = self.findList().filter(EntityUser.CustomerId == customerId
|
||||
).filter(or_(EntityUser.UserCode.like(keyWord), EntityUser.RealName.like(keyWord))).order_by(desc(EntityUser.CreateDate))
|
||||
return self.queryPage(orm_query, pageParam)
|
||||
|
||||
#获取用户详情信息
|
||||
def getUserInfo(self, userId):
|
||||
return self.findEntity(userId)
|
@ -0,0 +1,267 @@
|
||||
[2022-07-18 17:36:02,221] log_utlis.py->debug line:52 [DEBUG]Traceback (most recent call last):
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1819, in _execute_context
|
||||
self.dialect.do_execute(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\default.py", line 732, in do_execute
|
||||
cursor.execute(statement, parameters)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\cursors.py", line 148, in execute
|
||||
result = self._query(query)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\cursors.py", line 310, in _query
|
||||
conn.query(q)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 548, in query
|
||||
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 775, in _read_query_result
|
||||
result.read()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 1156, in read
|
||||
first_packet = self.connection._read_packet()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 725, in _read_packet
|
||||
packet.raise_for_error()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\protocol.py", line 221, in raise_for_error
|
||||
err.raise_mysql_exception(self._data)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\err.py", line 143, in raise_mysql_exception
|
||||
raise errorclass(errno, errval)
|
||||
pymysql.err.DataError: (1265, "Data truncated for column 'temperature' at row 1")
|
||||
|
||||
The above exception was the direct cause of the following exception:
|
||||
|
||||
Traceback (most recent call last):
|
||||
File ".\db_logic\db_base.py", line 68, in insert
|
||||
self.session.commit()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 1451, in commit
|
||||
self._transaction.commit(_to_root=self.future)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 829, in commit
|
||||
self._prepare_impl()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 808, in _prepare_impl
|
||||
self.session.flush()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3383, in flush
|
||||
self._flush(objects)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3523, in _flush
|
||||
transaction.rollback(_capture_exception=True)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
|
||||
compat.raise_(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\util\compat.py", line 208, in raise_
|
||||
raise exception
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3483, in _flush
|
||||
flush_context.execute()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 456, in execute
|
||||
rec.execute(self)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 630, in execute
|
||||
util.preloaded.orm_persistence.save_obj(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\persistence.py", line 245, in save_obj
|
||||
_emit_insert_statements(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\persistence.py", line 1238, in _emit_insert_statements
|
||||
result = connection._execute_20(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1631, in _execute_20
|
||||
return meth(self, args_10style, kwargs_10style, execution_options)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\sql\elements.py", line 332, in _execute_on_connection
|
||||
return connection._execute_clauseelement(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1498, in _execute_clauseelement
|
||||
ret = self._execute_context(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1862, in _execute_context
|
||||
self._handle_dbapi_exception(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2043, in _handle_dbapi_exception
|
||||
util.raise_(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\util\compat.py", line 208, in raise_
|
||||
raise exception
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1819, in _execute_context
|
||||
self.dialect.do_execute(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\default.py", line 732, in do_execute
|
||||
cursor.execute(statement, parameters)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\cursors.py", line 148, in execute
|
||||
result = self._query(query)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\cursors.py", line 310, in _query
|
||||
conn.query(q)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 548, in query
|
||||
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 775, in _read_query_result
|
||||
result.read()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 1156, in read
|
||||
first_packet = self.connection._read_packet()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 725, in _read_packet
|
||||
packet.raise_for_error()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\protocol.py", line 221, in raise_for_error
|
||||
err.raise_mysql_exception(self._data)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\err.py", line 143, in raise_mysql_exception
|
||||
raise errorclass(errno, errval)
|
||||
sqlalchemy.exc.DataError: (pymysql.err.DataError) (1265, "Data truncated for column 'temperature' at row 1")
|
||||
[SQL: INSERT INTO rms_humiture_record (device_id, client_id, client_name, customer_id, temperature, humidity, record_date, is_add) VALUES (%(device_id)s, %(client_id)s, %(client_name)s, %(customer_id)s, %(temperature)s, %(humidity)s, %(record_date)s, %(is_add)s)]
|
||||
[parameters: {'device_id': '', 'client_id': '', 'client_name': '', 'customer_id': '', 'temperature': '', 'humidity': '', 'record_date': '', 'is_add': 1}]
|
||||
(Background on this error at: https://sqlalche.me/e/14/9h9h)
|
||||
|
||||
[2022-07-18 17:38:46,709] log_utlis.py->debug line:52 [DEBUG]Traceback (most recent call last):
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1819, in _execute_context
|
||||
self.dialect.do_execute(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\default.py", line 732, in do_execute
|
||||
cursor.execute(statement, parameters)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\cursors.py", line 148, in execute
|
||||
result = self._query(query)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\cursors.py", line 310, in _query
|
||||
conn.query(q)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 548, in query
|
||||
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 775, in _read_query_result
|
||||
result.read()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 1156, in read
|
||||
first_packet = self.connection._read_packet()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 725, in _read_packet
|
||||
packet.raise_for_error()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\protocol.py", line 221, in raise_for_error
|
||||
err.raise_mysql_exception(self._data)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\err.py", line 143, in raise_mysql_exception
|
||||
raise errorclass(errno, errval)
|
||||
pymysql.err.DataError: (1265, "Data truncated for column 'temperature' at row 1")
|
||||
|
||||
The above exception was the direct cause of the following exception:
|
||||
|
||||
Traceback (most recent call last):
|
||||
File ".\db_logic\db_base.py", line 68, in insert
|
||||
self.session.commit()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 1451, in commit
|
||||
self._transaction.commit(_to_root=self.future)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 829, in commit
|
||||
self._prepare_impl()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 808, in _prepare_impl
|
||||
self.session.flush()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3383, in flush
|
||||
self._flush(objects)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3523, in _flush
|
||||
transaction.rollback(_capture_exception=True)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
|
||||
compat.raise_(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\util\compat.py", line 208, in raise_
|
||||
raise exception
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3483, in _flush
|
||||
flush_context.execute()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 456, in execute
|
||||
rec.execute(self)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 630, in execute
|
||||
util.preloaded.orm_persistence.save_obj(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\persistence.py", line 245, in save_obj
|
||||
_emit_insert_statements(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\persistence.py", line 1238, in _emit_insert_statements
|
||||
result = connection._execute_20(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1631, in _execute_20
|
||||
return meth(self, args_10style, kwargs_10style, execution_options)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\sql\elements.py", line 332, in _execute_on_connection
|
||||
return connection._execute_clauseelement(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1498, in _execute_clauseelement
|
||||
ret = self._execute_context(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1862, in _execute_context
|
||||
self._handle_dbapi_exception(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2043, in _handle_dbapi_exception
|
||||
util.raise_(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\util\compat.py", line 208, in raise_
|
||||
raise exception
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1819, in _execute_context
|
||||
self.dialect.do_execute(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\default.py", line 732, in do_execute
|
||||
cursor.execute(statement, parameters)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\cursors.py", line 148, in execute
|
||||
result = self._query(query)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\cursors.py", line 310, in _query
|
||||
conn.query(q)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 548, in query
|
||||
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 775, in _read_query_result
|
||||
result.read()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 1156, in read
|
||||
first_packet = self.connection._read_packet()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 725, in _read_packet
|
||||
packet.raise_for_error()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\protocol.py", line 221, in raise_for_error
|
||||
err.raise_mysql_exception(self._data)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\err.py", line 143, in raise_mysql_exception
|
||||
raise errorclass(errno, errval)
|
||||
sqlalchemy.exc.DataError: (pymysql.err.DataError) (1265, "Data truncated for column 'temperature' at row 1")
|
||||
[SQL: INSERT INTO rms_humiture_record (record_id, device_id, client_id, client_name, customer_id, temperature, humidity, record_date, is_add) VALUES (%(record_id)s, %(device_id)s, %(client_id)s, %(client_name)s, %(customer_id)s, %(temperature)s, %(humidity)s, %(record_date)s, %(is_add)s)]
|
||||
[parameters: {'record_id': '6bc0c3f0-067d-11ed-83be-f47b094925e1', 'device_id': '', 'client_id': '', 'client_name': '', 'customer_id': '', 'temperature': '', 'humidity': '', 'record_date': '', 'is_add': 1}]
|
||||
(Background on this error at: https://sqlalche.me/e/14/9h9h)
|
||||
|
||||
[2022-07-18 17:40:56,208] log_utlis.py->debug line:52 [DEBUG]Traceback (most recent call last):
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1819, in _execute_context
|
||||
self.dialect.do_execute(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\default.py", line 732, in do_execute
|
||||
cursor.execute(statement, parameters)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\cursors.py", line 148, in execute
|
||||
result = self._query(query)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\cursors.py", line 310, in _query
|
||||
conn.query(q)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 548, in query
|
||||
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 775, in _read_query_result
|
||||
result.read()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 1156, in read
|
||||
first_packet = self.connection._read_packet()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 725, in _read_packet
|
||||
packet.raise_for_error()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\protocol.py", line 221, in raise_for_error
|
||||
err.raise_mysql_exception(self._data)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\err.py", line 143, in raise_mysql_exception
|
||||
raise errorclass(errno, errval)
|
||||
pymysql.err.DataError: (1265, "Data truncated for column 'humidity' at row 1")
|
||||
|
||||
The above exception was the direct cause of the following exception:
|
||||
|
||||
Traceback (most recent call last):
|
||||
File ".\db_logic\db_base.py", line 68, in insert
|
||||
self.session.commit()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 1451, in commit
|
||||
self._transaction.commit(_to_root=self.future)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 829, in commit
|
||||
self._prepare_impl()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 808, in _prepare_impl
|
||||
self.session.flush()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3383, in flush
|
||||
self._flush(objects)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3523, in _flush
|
||||
transaction.rollback(_capture_exception=True)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
|
||||
compat.raise_(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\util\compat.py", line 208, in raise_
|
||||
raise exception
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3483, in _flush
|
||||
flush_context.execute()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 456, in execute
|
||||
rec.execute(self)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 630, in execute
|
||||
util.preloaded.orm_persistence.save_obj(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\persistence.py", line 245, in save_obj
|
||||
_emit_insert_statements(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\persistence.py", line 1238, in _emit_insert_statements
|
||||
result = connection._execute_20(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1631, in _execute_20
|
||||
return meth(self, args_10style, kwargs_10style, execution_options)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\sql\elements.py", line 332, in _execute_on_connection
|
||||
return connection._execute_clauseelement(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1498, in _execute_clauseelement
|
||||
ret = self._execute_context(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1862, in _execute_context
|
||||
self._handle_dbapi_exception(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2043, in _handle_dbapi_exception
|
||||
util.raise_(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\util\compat.py", line 208, in raise_
|
||||
raise exception
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1819, in _execute_context
|
||||
self.dialect.do_execute(
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\default.py", line 732, in do_execute
|
||||
cursor.execute(statement, parameters)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\cursors.py", line 148, in execute
|
||||
result = self._query(query)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\cursors.py", line 310, in _query
|
||||
conn.query(q)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 548, in query
|
||||
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 775, in _read_query_result
|
||||
result.read()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 1156, in read
|
||||
first_packet = self.connection._read_packet()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 725, in _read_packet
|
||||
packet.raise_for_error()
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\protocol.py", line 221, in raise_for_error
|
||||
err.raise_mysql_exception(self._data)
|
||||
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\err.py", line 143, in raise_mysql_exception
|
||||
raise errorclass(errno, errval)
|
||||
sqlalchemy.exc.DataError: (pymysql.err.DataError) (1265, "Data truncated for column 'humidity' at row 1")
|
||||
[SQL: INSERT INTO rms_humiture_record (record_id, device_id, client_id, client_name, customer_id, temperature, humidity, record_date, is_add) VALUES (%(record_id)s, %(device_id)s, %(client_id)s, %(client_name)s, %(customer_id)s, %(temperature)s, %(humidity)s, %(record_date)s, %(is_add)s)]
|
||||
[parameters: {'record_id': 'b8ed0b2c-067d-11ed-ba8f-f47b094925e1', 'device_id': '', 'client_id': '', 'client_name': '', 'customer_id': '', 'temperature': '0.2', 'humidity': '', 'record_date': '', 'is_add': 1}]
|
||||
(Background on this error at: https://sqlalche.me/e/14/9h9h)
|
||||
|
@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- encoding: utf-8 -*-
|
||||
'''
|
||||
@Date:2022/07/18 15:00:54
|
||||
'''
|
||||
|
||||
from config.server import create_app
|
||||
from common.exception_base import APIException
|
||||
from config.SystemConfig import SystemConfig
|
||||
app = create_app()
|
||||
|
||||
|
||||
@app.errorhandler(Exception)
|
||||
def framework_error(e):
|
||||
# 1、APIException
|
||||
# 2、Exception
|
||||
if isinstance(e, APIException):
|
||||
return e
|
||||
else:
|
||||
if not app.config['DEBUG']:
|
||||
return APIException(msg="系统异常错误: {}".format(e))
|
||||
else:
|
||||
return e
|
||||
|
||||
|
||||
|
||||
def main():
|
||||
HOST = SystemConfig.getConfig("serverip")
|
||||
PORT = int(SystemConfig.getConfig("port"))
|
||||
# CORS(app)
|
||||
# HOST = '127.0.0.1'
|
||||
# PORT = 8080
|
||||
app.run(host=HOST, port=PORT, debug=True)
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
import sys
|
||||
sys.exit(main())
|
||||
except Exception as error:
|
||||
import traceback
|
||||
traceback.print_exc()
|
@ -1,21 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
"""Django's command-line utility for administrative tasks."""
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'YY_RMS_Multiple_Manage.settings')
|
||||
try:
|
||||
from django.core.management import execute_from_command_line
|
||||
except ImportError as exc:
|
||||
raise ImportError(
|
||||
"Couldn't import Django. Are you sure it's installed and "
|
||||
"available on your PYTHONPATH environment variable? Did you "
|
||||
"forget to activate a virtual environment?"
|
||||
) from exc
|
||||
execute_from_command_line(sys.argv)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- encoding: utf-8 -*-
|
||||
'''
|
||||
@Date:2022/07/18 15:21:25
|
||||
'''
|
||||
import uuid
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
|
||||
def get_uuid():
|
||||
return str(uuid.uuid1())
|
||||
|
||||
|
||||
def gen_id():
|
||||
|
||||
return uuid.uuid4().hex
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print(type(gen_id))
|
||||
print(type(gen_id()))
|
Before Width: | Height: | Size: 6.3 KiB |
@ -1,429 +0,0 @@
|
||||
/* NUGET: BEGIN LICENSE TEXT
|
||||
*
|
||||
* Microsoft grants you the right to use these script files for the sole
|
||||
* purpose of either: (i) interacting through your browser with the Microsoft
|
||||
* website or online service, subject to the applicable licensing or use
|
||||
* terms; or (ii) using the files as included with a Microsoft product subject
|
||||
* to that product's license terms. Microsoft reserves all other rights to the
|
||||
* files not expressly granted by Microsoft, whether by implication, estoppel
|
||||
* or otherwise. Insofar as a script file is dual licensed under GPL,
|
||||
* Microsoft neither took the code under GPL nor distributes it thereunder but
|
||||
* under the terms set out in this paragraph. All notices and licenses
|
||||
* below are for informational purposes only.
|
||||
*
|
||||
* NUGET: END LICENSE TEXT */
|
||||
/*!
|
||||
** Unobtrusive validation support library for jQuery and jQuery Validate
|
||||
** Copyright (C) Microsoft Corporation. All rights reserved.
|
||||
*/
|
||||
|
||||
/*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: false */
|
||||
/*global document: false, jQuery: false */
|
||||
|
||||
(function ($) {
|
||||
var $jQval = $.validator,
|
||||
adapters,
|
||||
data_validation = "unobtrusiveValidation";
|
||||
|
||||
function setValidationValues(options, ruleName, value) {
|
||||
options.rules[ruleName] = value;
|
||||
if (options.message) {
|
||||
options.messages[ruleName] = options.message;
|
||||
}
|
||||
}
|
||||
|
||||
function splitAndTrim(value) {
|
||||
return value.replace(/^\s+|\s+$/g, "").split(/\s*,\s*/g);
|
||||
}
|
||||
|
||||
function escapeAttributeValue(value) {
|
||||
// As mentioned on http://api.jquery.com/category/selectors/
|
||||
return value.replace(/([!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~])/g, "\\$1");
|
||||
}
|
||||
|
||||
function getModelPrefix(fieldName) {
|
||||
return fieldName.substr(0, fieldName.lastIndexOf(".") + 1);
|
||||
}
|
||||
|
||||
function appendModelPrefix(value, prefix) {
|
||||
if (value.indexOf("*.") === 0) {
|
||||
value = value.replace("*.", prefix);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function onError(error, inputElement) { // 'this' is the form element
|
||||
var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[0].name) + "']"),
|
||||
replaceAttrValue = container.attr("data-valmsg-replace"),
|
||||
replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) !== false : null;
|
||||
|
||||
container.removeClass("field-validation-valid").addClass("field-validation-error");
|
||||
error.data("unobtrusiveContainer", container);
|
||||
|
||||
if (replace) {
|
||||
container.empty();
|
||||
error.removeClass("input-validation-error").appendTo(container);
|
||||
}
|
||||
else {
|
||||
error.hide();
|
||||
}
|
||||
}
|
||||
|
||||
function onErrors(event, validator) { // 'this' is the form element
|
||||
var container = $(this).find("[data-valmsg-summary=true]"),
|
||||
list = container.find("ul");
|
||||
|
||||
if (list && list.length && validator.errorList.length) {
|
||||
list.empty();
|
||||
container.addClass("validation-summary-errors").removeClass("validation-summary-valid");
|
||||
|
||||
$.each(validator.errorList, function () {
|
||||
$("<li />").html(this.message).appendTo(list);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function onSuccess(error) { // 'this' is the form element
|
||||
var container = error.data("unobtrusiveContainer"),
|
||||
replaceAttrValue = container.attr("data-valmsg-replace"),
|
||||
replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) : null;
|
||||
|
||||
if (container) {
|
||||
container.addClass("field-validation-valid").removeClass("field-validation-error");
|
||||
error.removeData("unobtrusiveContainer");
|
||||
|
||||
if (replace) {
|
||||
container.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function onReset(event) { // 'this' is the form element
|
||||
var $form = $(this),
|
||||
key = '__jquery_unobtrusive_validation_form_reset';
|
||||
if ($form.data(key)) {
|
||||
return;
|
||||
}
|
||||
// Set a flag that indicates we're currently resetting the form.
|
||||
$form.data(key, true);
|
||||
try {
|
||||
$form.data("validator").resetForm();
|
||||
} finally {
|
||||
$form.removeData(key);
|
||||
}
|
||||
|
||||
$form.find(".validation-summary-errors")
|
||||
.addClass("validation-summary-valid")
|
||||
.removeClass("validation-summary-errors");
|
||||
$form.find(".field-validation-error")
|
||||
.addClass("field-validation-valid")
|
||||
.removeClass("field-validation-error")
|
||||
.removeData("unobtrusiveContainer")
|
||||
.find(">*") // If we were using valmsg-replace, get the underlying error
|
||||
.removeData("unobtrusiveContainer");
|
||||
}
|
||||
|
||||
function validationInfo(form) {
|
||||
var $form = $(form),
|
||||
result = $form.data(data_validation),
|
||||
onResetProxy = $.proxy(onReset, form),
|
||||
defaultOptions = $jQval.unobtrusive.options || {},
|
||||
execInContext = function (name, args) {
|
||||
var func = defaultOptions[name];
|
||||
func && $.isFunction(func) && func.apply(form, args);
|
||||
}
|
||||
|
||||
if (!result) {
|
||||
result = {
|
||||
options: { // options structure passed to jQuery Validate's validate() method
|
||||
errorClass: defaultOptions.errorClass || "input-validation-error",
|
||||
errorElement: defaultOptions.errorElement || "span",
|
||||
errorPlacement: function () {
|
||||
onError.apply(form, arguments);
|
||||
execInContext("errorPlacement", arguments);
|
||||
},
|
||||
invalidHandler: function () {
|
||||
onErrors.apply(form, arguments);
|
||||
execInContext("invalidHandler", arguments);
|
||||
},
|
||||
messages: {},
|
||||
rules: {},
|
||||
success: function () {
|
||||
onSuccess.apply(form, arguments);
|
||||
execInContext("success", arguments);
|
||||
}
|
||||
},
|
||||
attachValidation: function () {
|
||||
$form
|
||||
.off("reset." + data_validation, onResetProxy)
|
||||
.on("reset." + data_validation, onResetProxy)
|
||||
.validate(this.options);
|
||||
},
|
||||
validate: function () { // a validation function that is called by unobtrusive Ajax
|
||||
$form.validate();
|
||||
return $form.valid();
|
||||
}
|
||||
};
|
||||
$form.data(data_validation, result);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
$jQval.unobtrusive = {
|
||||
adapters: [],
|
||||
|
||||
parseElement: function (element, skipAttach) {
|
||||
/// <summary>
|
||||
/// Parses a single HTML element for unobtrusive validation attributes.
|
||||
/// </summary>
|
||||
/// <param name="element" domElement="true">The HTML element to be parsed.</param>
|
||||
/// <param name="skipAttach" type="Boolean">[Optional] true to skip attaching the
|
||||
/// validation to the form. If parsing just this single element, you should specify true.
|
||||
/// If parsing several elements, you should specify false, and manually attach the validation
|
||||
/// to the form when you are finished. The default is false.</param>
|
||||
var $element = $(element),
|
||||
form = $element.parents("form")[0],
|
||||
valInfo, rules, messages;
|
||||
|
||||
if (!form) { // Cannot do client-side validation without a form
|
||||
return;
|
||||
}
|
||||
|
||||
valInfo = validationInfo(form);
|
||||
valInfo.options.rules[element.name] = rules = {};
|
||||
valInfo.options.messages[element.name] = messages = {};
|
||||
|
||||
$.each(this.adapters, function () {
|
||||
var prefix = "data-val-" + this.name,
|
||||
message = $element.attr(prefix),
|
||||
paramValues = {};
|
||||
|
||||
if (message !== undefined) { // Compare against undefined, because an empty message is legal (and falsy)
|
||||
prefix += "-";
|
||||
|
||||
$.each(this.params, function () {
|
||||
paramValues[this] = $element.attr(prefix + this);
|
||||
});
|
||||
|
||||
this.adapt({
|
||||
element: element,
|
||||
form: form,
|
||||
message: message,
|
||||
params: paramValues,
|
||||
rules: rules,
|
||||
messages: messages
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
$.extend(rules, { "__dummy__": true });
|
||||
|
||||
if (!skipAttach) {
|
||||
valInfo.attachValidation();
|
||||
}
|
||||
},
|
||||
|
||||
parse: function (selector) {
|
||||
/// <summary>
|
||||
/// Parses all the HTML elements in the specified selector. It looks for input elements decorated
|
||||
/// with the [data-val=true] attribute value and enables validation according to the data-val-*
|
||||
/// attribute values.
|
||||
/// </summary>
|
||||
/// <param name="selector" type="String">Any valid jQuery selector.</param>
|
||||
|
||||
// $forms includes all forms in selector's DOM hierarchy (parent, children and self) that have at least one
|
||||
// element with data-val=true
|
||||
var $selector = $(selector),
|
||||
$forms = $selector.parents()
|
||||
.addBack()
|
||||
.filter("form")
|
||||
.add($selector.find("form"))
|
||||
.has("[data-val=true]");
|
||||
|
||||
$selector.find("[data-val=true]").each(function () {
|
||||
$jQval.unobtrusive.parseElement(this, true);
|
||||
});
|
||||
|
||||
$forms.each(function () {
|
||||
var info = validationInfo(this);
|
||||
if (info) {
|
||||
info.attachValidation();
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
adapters = $jQval.unobtrusive.adapters;
|
||||
|
||||
adapters.add = function (adapterName, params, fn) {
|
||||
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation.</summary>
|
||||
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
|
||||
/// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
|
||||
/// <param name="params" type="Array" optional="true">[Optional] An array of parameter names (strings) that will
|
||||
/// be extracted from the data-val-nnnn-mmmm HTML attributes (where nnnn is the adapter name, and
|
||||
/// mmmm is the parameter name).</param>
|
||||
/// <param name="fn" type="Function">The function to call, which adapts the values from the HTML
|
||||
/// attributes into jQuery Validate rules and/or messages.</param>
|
||||
/// <returns type="jQuery.validator.unobtrusive.adapters" />
|
||||
if (!fn) { // Called with no params, just a function
|
||||
fn = params;
|
||||
params = [];
|
||||
}
|
||||
this.push({ name: adapterName, params: params, adapt: fn });
|
||||
return this;
|
||||
};
|
||||
|
||||
adapters.addBool = function (adapterName, ruleName) {
|
||||
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
|
||||
/// the jQuery Validate validation rule has no parameter values.</summary>
|
||||
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
|
||||
/// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
|
||||
/// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
|
||||
/// of adapterName will be used instead.</param>
|
||||
/// <returns type="jQuery.validator.unobtrusive.adapters" />
|
||||
return this.add(adapterName, function (options) {
|
||||
setValidationValues(options, ruleName || adapterName, true);
|
||||
});
|
||||
};
|
||||
|
||||
adapters.addMinMax = function (adapterName, minRuleName, maxRuleName, minMaxRuleName, minAttribute, maxAttribute) {
|
||||
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
|
||||
/// the jQuery Validate validation has three potential rules (one for min-only, one for max-only, and
|
||||
/// one for min-and-max). The HTML parameters are expected to be named -min and -max.</summary>
|
||||
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
|
||||
/// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
|
||||
/// <param name="minRuleName" type="String">The name of the jQuery Validate rule to be used when you only
|
||||
/// have a minimum value.</param>
|
||||
/// <param name="maxRuleName" type="String">The name of the jQuery Validate rule to be used when you only
|
||||
/// have a maximum value.</param>
|
||||
/// <param name="minMaxRuleName" type="String">The name of the jQuery Validate rule to be used when you
|
||||
/// have both a minimum and maximum value.</param>
|
||||
/// <param name="minAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
|
||||
/// contains the minimum value. The default is "min".</param>
|
||||
/// <param name="maxAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
|
||||
/// contains the maximum value. The default is "max".</param>
|
||||
/// <returns type="jQuery.validator.unobtrusive.adapters" />
|
||||
return this.add(adapterName, [minAttribute || "min", maxAttribute || "max"], function (options) {
|
||||
var min = options.params.min,
|
||||
max = options.params.max;
|
||||
|
||||
if (min && max) {
|
||||
setValidationValues(options, minMaxRuleName, [min, max]);
|
||||
}
|
||||
else if (min) {
|
||||
setValidationValues(options, minRuleName, min);
|
||||
}
|
||||
else if (max) {
|
||||
setValidationValues(options, maxRuleName, max);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
adapters.addSingleVal = function (adapterName, attribute, ruleName) {
|
||||
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
|
||||
/// the jQuery Validate validation rule has a single value.</summary>
|
||||
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
|
||||
/// in the data-val-nnnn HTML attribute(where nnnn is the adapter name).</param>
|
||||
/// <param name="attribute" type="String">[Optional] The name of the HTML attribute that contains the value.
|
||||
/// The default is "val".</param>
|
||||
/// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
|
||||
/// of adapterName will be used instead.</param>
|
||||
/// <returns type="jQuery.validator.unobtrusive.adapters" />
|
||||
return this.add(adapterName, [attribute || "val"], function (options) {
|
||||
setValidationValues(options, ruleName || adapterName, options.params[attribute]);
|
||||
});
|
||||
};
|
||||
|
||||
$jQval.addMethod("__dummy__", function (value, element, params) {
|
||||
return true;
|
||||
});
|
||||
|
||||
$jQval.addMethod("regex", function (value, element, params) {
|
||||
var match;
|
||||
if (this.optional(element)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
match = new RegExp(params).exec(value);
|
||||
return (match && (match.index === 0) && (match[0].length === value.length));
|
||||
});
|
||||
|
||||
$jQval.addMethod("nonalphamin", function (value, element, nonalphamin) {
|
||||
var match;
|
||||
if (nonalphamin) {
|
||||
match = value.match(/\W/g);
|
||||
match = match && match.length >= nonalphamin;
|
||||
}
|
||||
return match;
|
||||
});
|
||||
|
||||
if ($jQval.methods.extension) {
|
||||
adapters.addSingleVal("accept", "mimtype");
|
||||
adapters.addSingleVal("extension", "extension");
|
||||
} else {
|
||||
// for backward compatibility, when the 'extension' validation method does not exist, such as with versions
|
||||
// of JQuery Validation plugin prior to 1.10, we should use the 'accept' method for
|
||||
// validating the extension, and ignore mime-type validations as they are not supported.
|
||||
adapters.addSingleVal("extension", "extension", "accept");
|
||||
}
|
||||
|
||||
adapters.addSingleVal("regex", "pattern");
|
||||
adapters.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url");
|
||||
adapters.addMinMax("length", "minlength", "maxlength", "rangelength").addMinMax("range", "min", "max", "range");
|
||||
adapters.addMinMax("minlength", "minlength").addMinMax("maxlength", "minlength", "maxlength");
|
||||
adapters.add("equalto", ["other"], function (options) {
|
||||
var prefix = getModelPrefix(options.element.name),
|
||||
other = options.params.other,
|
||||
fullOtherName = appendModelPrefix(other, prefix),
|
||||
element = $(options.form).find(":input").filter("[name='" + escapeAttributeValue(fullOtherName) + "']")[0];
|
||||
|
||||
setValidationValues(options, "equalTo", element);
|
||||
});
|
||||
adapters.add("required", function (options) {
|
||||
// jQuery Validate equates "required" with "mandatory" for checkbox elements
|
||||
if (options.element.tagName.toUpperCase() !== "INPUT" || options.element.type.toUpperCase() !== "CHECKBOX") {
|
||||
setValidationValues(options, "required", true);
|
||||
}
|
||||
});
|
||||
adapters.add("remote", ["url", "type", "additionalfields"], function (options) {
|
||||
var value = {
|
||||
url: options.params.url,
|
||||
type: options.params.type || "GET",
|
||||
data: {}
|
||||
},
|
||||
prefix = getModelPrefix(options.element.name);
|
||||
|
||||
$.each(splitAndTrim(options.params.additionalfields || options.element.name), function (i, fieldName) {
|
||||
var paramName = appendModelPrefix(fieldName, prefix);
|
||||
value.data[paramName] = function () {
|
||||
var field = $(options.form).find(":input").filter("[name='" + escapeAttributeValue(paramName) + "']");
|
||||
// For checkboxes and radio buttons, only pick up values from checked fields.
|
||||
if (field.is(":checkbox")) {
|
||||
return field.filter(":checked").val() || field.filter(":hidden").val() || '';
|
||||
}
|
||||
else if (field.is(":radio")) {
|
||||
return field.filter(":checked").val() || '';
|
||||
}
|
||||
return field.val();
|
||||
};
|
||||
});
|
||||
|
||||
setValidationValues(options, "remote", value);
|
||||
});
|
||||
adapters.add("password", ["min", "nonalphamin", "regex"], function (options) {
|
||||
if (options.params.min) {
|
||||
setValidationValues(options, "minlength", options.params.min);
|
||||
}
|
||||
if (options.params.nonalphamin) {
|
||||
setValidationValues(options, "nonalphamin", options.params.nonalphamin);
|
||||
}
|
||||
if (options.params.regex) {
|
||||
setValidationValues(options, "regex", options.params.regex);
|
||||
}
|
||||
});
|
||||
|
||||
$(function () {
|
||||
$jQval.unobtrusive.parse(document);
|
||||
});
|
||||
}(jQuery));
|
@ -1,340 +0,0 @@
|
||||
/* NUGET: BEGIN LICENSE TEXT
|
||||
*
|
||||
* Microsoft grants you the right to use these script files for the sole
|
||||
* purpose of either: (i) interacting through your browser with the Microsoft
|
||||
* website or online service, subject to the applicable licensing or use
|
||||
* terms; or (ii) using the files as included with a Microsoft product subject
|
||||
* to that product's license terms. Microsoft reserves all other rights to the
|
||||
* files not expressly granted by Microsoft, whether by implication, estoppel
|
||||
* or otherwise. Insofar as a script file is dual licensed under GPL,
|
||||
* Microsoft neither took the code under GPL nor distributes it thereunder but
|
||||
* under the terms set out in this paragraph. All notices and licenses
|
||||
* below are for informational purposes only.
|
||||
*
|
||||
* NUGET: END LICENSE TEXT */
|
||||
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
|
||||
/*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */
|
||||
window.matchMedia = window.matchMedia || (function(doc, undefined){
|
||||
|
||||
var bool,
|
||||
docElem = doc.documentElement,
|
||||
refNode = docElem.firstElementChild || docElem.firstChild,
|
||||
// fakeBody required for <FF4 when executed in <head>
|
||||
fakeBody = doc.createElement('body'),
|
||||
div = doc.createElement('div');
|
||||
|
||||
div.id = 'mq-test-1';
|
||||
div.style.cssText = "position:absolute;top:-100em";
|
||||
fakeBody.style.background = "none";
|
||||
fakeBody.appendChild(div);
|
||||
|
||||
return function(q){
|
||||
|
||||
div.innerHTML = '­<style media="'+q+'"> #mq-test-1 { width: 42px; }</style>';
|
||||
|
||||
docElem.insertBefore(fakeBody, refNode);
|
||||
bool = div.offsetWidth == 42;
|
||||
docElem.removeChild(fakeBody);
|
||||
|
||||
return { matches: bool, media: q };
|
||||
};
|
||||
|
||||
})(document);
|
||||
|
||||
|
||||
|
||||
|
||||
/*! Respond.js v1.2.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs */
|
||||
(function( win ){
|
||||
//exposed namespace
|
||||
win.respond = {};
|
||||
|
||||
//define update even in native-mq-supporting browsers, to avoid errors
|
||||
respond.update = function(){};
|
||||
|
||||
//expose media query support flag for external use
|
||||
respond.mediaQueriesSupported = win.matchMedia && win.matchMedia( "only all" ).matches;
|
||||
|
||||
//if media queries are supported, exit here
|
||||
if( respond.mediaQueriesSupported ){ return; }
|
||||
|
||||
//define vars
|
||||
var doc = win.document,
|
||||
docElem = doc.documentElement,
|
||||
mediastyles = [],
|
||||
rules = [],
|
||||
appendedEls = [],
|
||||
parsedSheets = {},
|
||||
resizeThrottle = 30,
|
||||
head = doc.getElementsByTagName( "head" )[0] || docElem,
|
||||
base = doc.getElementsByTagName( "base" )[0],
|
||||
links = head.getElementsByTagName( "link" ),
|
||||
requestQueue = [],
|
||||
|
||||
//loop stylesheets, send text content to translate
|
||||
ripCSS = function(){
|
||||
var sheets = links,
|
||||
sl = sheets.length,
|
||||
i = 0,
|
||||
//vars for loop:
|
||||
sheet, href, media, isCSS;
|
||||
|
||||
for( ; i < sl; i++ ){
|
||||
sheet = sheets[ i ],
|
||||
href = sheet.href,
|
||||
media = sheet.media,
|
||||
isCSS = sheet.rel && sheet.rel.toLowerCase() === "stylesheet";
|
||||
|
||||
//only links plz and prevent re-parsing
|
||||
if( !!href && isCSS && !parsedSheets[ href ] ){
|
||||
// selectivizr exposes css through the rawCssText expando
|
||||
if (sheet.styleSheet && sheet.styleSheet.rawCssText) {
|
||||
translate( sheet.styleSheet.rawCssText, href, media );
|
||||
parsedSheets[ href ] = true;
|
||||
} else {
|
||||
if( (!/^([a-zA-Z:]*\/\/)/.test( href ) && !base)
|
||||
|| href.replace( RegExp.$1, "" ).split( "/" )[0] === win.location.host ){
|
||||
requestQueue.push( {
|
||||
href: href,
|
||||
media: media
|
||||
} );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
makeRequests();
|
||||
},
|
||||
|
||||
//recurse through request queue, get css text
|
||||
makeRequests = function(){
|
||||
if( requestQueue.length ){
|
||||
var thisRequest = requestQueue.shift();
|
||||
|
||||
ajax( thisRequest.href, function( styles ){
|
||||
translate( styles, thisRequest.href, thisRequest.media );
|
||||
parsedSheets[ thisRequest.href ] = true;
|
||||
makeRequests();
|
||||
} );
|
||||
}
|
||||
},
|
||||
|
||||
//find media blocks in css text, convert to style blocks
|
||||
translate = function( styles, href, media ){
|
||||
var qs = styles.match( /@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi ),
|
||||
ql = qs && qs.length || 0,
|
||||
//try to get CSS path
|
||||
href = href.substring( 0, href.lastIndexOf( "/" )),
|
||||
repUrls = function( css ){
|
||||
return css.replace( /(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g, "$1" + href + "$2$3" );
|
||||
},
|
||||
useMedia = !ql && media,
|
||||
//vars used in loop
|
||||
i = 0,
|
||||
j, fullq, thisq, eachq, eql;
|
||||
|
||||
//if path exists, tack on trailing slash
|
||||
if( href.length ){ href += "/"; }
|
||||
|
||||
//if no internal queries exist, but media attr does, use that
|
||||
//note: this currently lacks support for situations where a media attr is specified on a link AND
|
||||
//its associated stylesheet has internal CSS media queries.
|
||||
//In those cases, the media attribute will currently be ignored.
|
||||
if( useMedia ){
|
||||
ql = 1;
|
||||
}
|
||||
|
||||
|
||||
for( ; i < ql; i++ ){
|
||||
j = 0;
|
||||
|
||||
//media attr
|
||||
if( useMedia ){
|
||||
fullq = media;
|
||||
rules.push( repUrls( styles ) );
|
||||
}
|
||||
//parse for styles
|
||||
else{
|
||||
fullq = qs[ i ].match( /@media *([^\{]+)\{([\S\s]+?)$/ ) && RegExp.$1;
|
||||
rules.push( RegExp.$2 && repUrls( RegExp.$2 ) );
|
||||
}
|
||||
|
||||
eachq = fullq.split( "," );
|
||||
eql = eachq.length;
|
||||
|
||||
for( ; j < eql; j++ ){
|
||||
thisq = eachq[ j ];
|
||||
mediastyles.push( {
|
||||
media : thisq.split( "(" )[ 0 ].match( /(only\s+)?([a-zA-Z]+)\s?/ ) && RegExp.$2 || "all",
|
||||
rules : rules.length - 1,
|
||||
hasquery: thisq.indexOf("(") > -1,
|
||||
minw : thisq.match( /\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ),
|
||||
maxw : thisq.match( /\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" )
|
||||
} );
|
||||
}
|
||||
}
|
||||
|
||||
applyMedia();
|
||||
},
|
||||
|
||||
lastCall,
|
||||
|
||||
resizeDefer,
|
||||
|
||||
// returns the value of 1em in pixels
|
||||
getEmValue = function() {
|
||||
var ret,
|
||||
div = doc.createElement('div'),
|
||||
body = doc.body,
|
||||
fakeUsed = false;
|
||||
|
||||
div.style.cssText = "position:absolute;font-size:1em;width:1em";
|
||||
|
||||
if( !body ){
|
||||
body = fakeUsed = doc.createElement( "body" );
|
||||
body.style.background = "none";
|
||||
}
|
||||
|
||||
body.appendChild( div );
|
||||
|
||||
docElem.insertBefore( body, docElem.firstChild );
|
||||
|
||||
ret = div.offsetWidth;
|
||||
|
||||
if( fakeUsed ){
|
||||
docElem.removeChild( body );
|
||||
}
|
||||
else {
|
||||
body.removeChild( div );
|
||||
}
|
||||
|
||||
//also update eminpx before returning
|
||||
ret = eminpx = parseFloat(ret);
|
||||
|
||||
return ret;
|
||||
},
|
||||
|
||||
//cached container for 1em value, populated the first time it's needed
|
||||
eminpx,
|
||||
|
||||
//enable/disable styles
|
||||
applyMedia = function( fromResize ){
|
||||
var name = "clientWidth",
|
||||
docElemProp = docElem[ name ],
|
||||
currWidth = doc.compatMode === "CSS1Compat" && docElemProp || doc.body[ name ] || docElemProp,
|
||||
styleBlocks = {},
|
||||
lastLink = links[ links.length-1 ],
|
||||
now = (new Date()).getTime();
|
||||
|
||||
//throttle resize calls
|
||||
if( fromResize && lastCall && now - lastCall < resizeThrottle ){
|
||||
clearTimeout( resizeDefer );
|
||||
resizeDefer = setTimeout( applyMedia, resizeThrottle );
|
||||
return;
|
||||
}
|
||||
else {
|
||||
lastCall = now;
|
||||
}
|
||||
|
||||
for( var i in mediastyles ){
|
||||
var thisstyle = mediastyles[ i ],
|
||||
min = thisstyle.minw,
|
||||
max = thisstyle.maxw,
|
||||
minnull = min === null,
|
||||
maxnull = max === null,
|
||||
em = "em";
|
||||
|
||||
if( !!min ){
|
||||
min = parseFloat( min ) * ( min.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 );
|
||||
}
|
||||
if( !!max ){
|
||||
max = parseFloat( max ) * ( max.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 );
|
||||
}
|
||||
|
||||
// if there's no media query at all (the () part), or min or max is not null, and if either is present, they're true
|
||||
if( !thisstyle.hasquery || ( !minnull || !maxnull ) && ( minnull || currWidth >= min ) && ( maxnull || currWidth <= max ) ){
|
||||
if( !styleBlocks[ thisstyle.media ] ){
|
||||
styleBlocks[ thisstyle.media ] = [];
|
||||
}
|
||||
styleBlocks[ thisstyle.media ].push( rules[ thisstyle.rules ] );
|
||||
}
|
||||
}
|
||||
|
||||
//remove any existing respond style element(s)
|
||||
for( var i in appendedEls ){
|
||||
if( appendedEls[ i ] && appendedEls[ i ].parentNode === head ){
|
||||
head.removeChild( appendedEls[ i ] );
|
||||
}
|
||||
}
|
||||
|
||||
//inject active styles, grouped by media type
|
||||
for( var i in styleBlocks ){
|
||||
var ss = doc.createElement( "style" ),
|
||||
css = styleBlocks[ i ].join( "\n" );
|
||||
|
||||
ss.type = "text/css";
|
||||
ss.media = i;
|
||||
|
||||
//originally, ss was appended to a documentFragment and sheets were appended in bulk.
|
||||
//this caused crashes in IE in a number of circumstances, such as when the HTML element had a bg image set, so appending beforehand seems best. Thanks to @dvelyk for the initial research on this one!
|
||||
head.insertBefore( ss, lastLink.nextSibling );
|
||||
|
||||
if ( ss.styleSheet ){
|
||||
ss.styleSheet.cssText = css;
|
||||
}
|
||||
else {
|
||||
ss.appendChild( doc.createTextNode( css ) );
|
||||
}
|
||||
|
||||
//push to appendedEls to track for later removal
|
||||
appendedEls.push( ss );
|
||||
}
|
||||
},
|
||||
//tweaked Ajax functions from Quirksmode
|
||||
ajax = function( url, callback ) {
|
||||
var req = xmlHttp();
|
||||
if (!req){
|
||||
return;
|
||||
}
|
||||
req.open( "GET", url, true );
|
||||
req.onreadystatechange = function () {
|
||||
if ( req.readyState != 4 || req.status != 200 && req.status != 304 ){
|
||||
return;
|
||||
}
|
||||
callback( req.responseText );
|
||||
}
|
||||
if ( req.readyState == 4 ){
|
||||
return;
|
||||
}
|
||||
req.send( null );
|
||||
},
|
||||
//define ajax obj
|
||||
xmlHttp = (function() {
|
||||
var xmlhttpmethod = false;
|
||||
try {
|
||||
xmlhttpmethod = new XMLHttpRequest();
|
||||
}
|
||||
catch( e ){
|
||||
xmlhttpmethod = new ActiveXObject( "Microsoft.XMLHTTP" );
|
||||
}
|
||||
return function(){
|
||||
return xmlhttpmethod;
|
||||
};
|
||||
})();
|
||||
|
||||
//translate CSS
|
||||
ripCSS();
|
||||
|
||||
//expose update for re-running respond later on
|
||||
respond.update = ripCSS;
|
||||
|
||||
//adjust on resize
|
||||
function callMedia(){
|
||||
applyMedia( true );
|
||||
}
|
||||
if( win.addEventListener ){
|
||||
win.addEventListener( "resize", callMedia, false );
|
||||
}
|
||||
else if( win.attachEvent ){
|
||||
win.attachEvent( "onresize", callMedia );
|
||||
}
|
||||
})(this);
|
@ -1,20 +0,0 @@
|
||||
/* NUGET: BEGIN LICENSE TEXT
|
||||
*
|
||||
* Microsoft grants you the right to use these script files for the sole
|
||||
* purpose of either: (i) interacting through your browser with the Microsoft
|
||||
* website or online service, subject to the applicable licensing or use
|
||||
* terms; or (ii) using the files as included with a Microsoft product subject
|
||||
* to that product's license terms. Microsoft reserves all other rights to the
|
||||
* files not expressly granted by Microsoft, whether by implication, estoppel
|
||||
* or otherwise. Insofar as a script file is dual licensed under GPL,
|
||||
* Microsoft neither took the code under GPL nor distributes it thereunder but
|
||||
* under the terms set out in this paragraph. All notices and licenses
|
||||
* below are for informational purposes only.
|
||||
*
|
||||
* NUGET: END LICENSE TEXT */
|
||||
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
|
||||
/*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */
|
||||
window.matchMedia=window.matchMedia||(function(e,f){var c,a=e.documentElement,b=a.firstElementChild||a.firstChild,d=e.createElement("body"),g=e.createElement("div");g.id="mq-test-1";g.style.cssText="position:absolute;top:-100em";d.style.background="none";d.appendChild(g);return function(h){g.innerHTML='­<style media="'+h+'"> #mq-test-1 { width: 42px; }</style>';a.insertBefore(d,b);c=g.offsetWidth==42;a.removeChild(d);return{matches:c,media:h}}})(document);
|
||||
|
||||
/*! Respond.js v1.2.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs */
|
||||
(function(e){e.respond={};respond.update=function(){};respond.mediaQueriesSupported=e.matchMedia&&e.matchMedia("only all").matches;if(respond.mediaQueriesSupported){return}var w=e.document,s=w.documentElement,i=[],k=[],q=[],o={},h=30,f=w.getElementsByTagName("head")[0]||s,g=w.getElementsByTagName("base")[0],b=f.getElementsByTagName("link"),d=[],a=function(){var D=b,y=D.length,B=0,A,z,C,x;for(;B<y;B++){A=D[B],z=A.href,C=A.media,x=A.rel&&A.rel.toLowerCase()==="stylesheet";if(!!z&&x&&!o[z]){if(A.styleSheet&&A.styleSheet.rawCssText){m(A.styleSheet.rawCssText,z,C);o[z]=true}else{if((!/^([a-zA-Z:]*\/\/)/.test(z)&&!g)||z.replace(RegExp.$1,"").split("/")[0]===e.location.host){d.push({href:z,media:C})}}}}u()},u=function(){if(d.length){var x=d.shift();n(x.href,function(y){m(y,x.href,x.media);o[x.href]=true;u()})}},m=function(I,x,z){var G=I.match(/@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi),J=G&&G.length||0,x=x.substring(0,x.lastIndexOf("/")),y=function(K){return K.replace(/(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g,"$1"+x+"$2$3")},A=!J&&z,D=0,C,E,F,B,H;if(x.length){x+="/"}if(A){J=1}for(;D<J;D++){C=0;if(A){E=z;k.push(y(I))}else{E=G[D].match(/@media *([^\{]+)\{([\S\s]+?)$/)&&RegExp.$1;k.push(RegExp.$2&&y(RegExp.$2))}B=E.split(",");H=B.length;for(;C<H;C++){F=B[C];i.push({media:F.split("(")[0].match(/(only\s+)?([a-zA-Z]+)\s?/)&&RegExp.$2||"all",rules:k.length-1,hasquery:F.indexOf("(")>-1,minw:F.match(/\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/)&&parseFloat(RegExp.$1)+(RegExp.$2||""),maxw:F.match(/\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/)&&parseFloat(RegExp.$1)+(RegExp.$2||"")})}}j()},l,r,v=function(){var z,A=w.createElement("div"),x=w.body,y=false;A.style.cssText="position:absolute;font-size:1em;width:1em";if(!x){x=y=w.createElement("body");x.style.background="none"}x.appendChild(A);s.insertBefore(x,s.firstChild);z=A.offsetWidth;if(y){s.removeChild(x)}else{x.removeChild(A)}z=p=parseFloat(z);return z},p,j=function(I){var x="clientWidth",B=s[x],H=w.compatMode==="CSS1Compat"&&B||w.body[x]||B,D={},G=b[b.length-1],z=(new Date()).getTime();if(I&&l&&z-l<h){clearTimeout(r);r=setTimeout(j,h);return}else{l=z}for(var E in i){var K=i[E],C=K.minw,J=K.maxw,A=C===null,L=J===null,y="em";if(!!C){C=parseFloat(C)*(C.indexOf(y)>-1?(p||v()):1)}if(!!J){J=parseFloat(J)*(J.indexOf(y)>-1?(p||v()):1)}if(!K.hasquery||(!A||!L)&&(A||H>=C)&&(L||H<=J)){if(!D[K.media]){D[K.media]=[]}D[K.media].push(k[K.rules])}}for(var E in q){if(q[E]&&q[E].parentNode===f){f.removeChild(q[E])}}for(var E in D){var M=w.createElement("style"),F=D[E].join("\n");M.type="text/css";M.media=E;f.insertBefore(M,G.nextSibling);if(M.styleSheet){M.styleSheet.cssText=F}else{M.appendChild(w.createTextNode(F))}q.push(M)}},n=function(x,z){var y=c();if(!y){return}y.open("GET",x,true);y.onreadystatechange=function(){if(y.readyState!=4||y.status!=200&&y.status!=304){return}z(y.responseText)};if(y.readyState==4){return}y.send(null)},c=(function(){var x=false;try{x=new XMLHttpRequest()}catch(y){x=new ActiveXObject("Microsoft.XMLHTTP")}return function(){return x}})();a();respond.update=a;function t(){j(true)}if(e.addEventListener){e.addEventListener("resize",t,false)}else{if(e.attachEvent){e.attachEvent("onresize",t)}}})(this);
|
@ -1,65 +0,0 @@
|
||||
/* Style For Suggestions */
|
||||
|
||||
/*
|
||||
For creating side border like this
|
||||
| item 1 |
|
||||
| item 2 |
|
||||
*/
|
||||
.suggestions .suggest_item{
|
||||
padding-bottom: 2px;
|
||||
padding-top: 2px;
|
||||
background-color:#EEEEEE;
|
||||
border-left:1px solid #CCCCCC;
|
||||
border-right:1px solid #CCCCCC;
|
||||
}
|
||||
|
||||
/*
|
||||
For creating top border like this
|
||||
------------
|
||||
item 1
|
||||
...
|
||||
*/
|
||||
.suggestions .suggest_item.first{
|
||||
border-top:1px solid #CCCCCC;
|
||||
}
|
||||
|
||||
/*
|
||||
For creating bottom border like this
|
||||
...
|
||||
item 2
|
||||
------------
|
||||
*/
|
||||
.suggestions .suggest_item.last{
|
||||
border-bottom:1px solid #CCCCCC;
|
||||
}
|
||||
|
||||
/*
|
||||
For coloring the selected item
|
||||
*/
|
||||
.suggestions .suggest_item.selected, .suggestions .suggest_item.selected .description{
|
||||
background-color:#999999;
|
||||
color:#FFFFFF;
|
||||
cursor:pointer;
|
||||
}
|
||||
|
||||
/*
|
||||
Image thumbnail
|
||||
*/
|
||||
.suggestions .suggest_item .thumbnail{
|
||||
background-color: transparent;
|
||||
background-position: top center;
|
||||
background-repeat: no-repeat;
|
||||
margin: 1px 2px 1px 2px;
|
||||
float: left;
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
}
|
||||
|
||||
/*
|
||||
Description
|
||||
*/
|
||||
.suggestions .suggest_item .description{
|
||||
font-style: italic;
|
||||
font-size: 11px;
|
||||
color: #777;
|
||||
}
|
@ -1,2 +0,0 @@
|
||||
/** layui-v2.5.6 MIT License By https://www.layui.com */
|
||||
html #layuicss-skincodecss{display:none;position:absolute;width:1989px}.layui-code-h3,.layui-code-view{position:relative;font-size:12px}.layui-code-view{display:block;margin:10px 0;padding:0;border:1px solid #e2e2e2;border-left-width:6px;background-color:#F2F2F2;color:#333;font-family:Courier New}.layui-code-h3{padding:0 10px;height:32px;line-height:32px;border-bottom:1px solid #e2e2e2}.layui-code-h3 a{position:absolute;right:10px;top:0;color:#999}.layui-code-view .layui-code-ol{position:relative;overflow:auto}.layui-code-view .layui-code-ol li{position:relative;margin-left:45px;line-height:20px;padding:0 5px;border-left:1px solid #e2e2e2;list-style-type:decimal-leading-zero;*list-style-type:decimal;background-color:#fff}.layui-code-view pre{margin:0}.layui-code-notepad{border:1px solid #0C0C0C;border-left-color:#3F3F3F;background-color:#0C0C0C;color:#C2BE9E}.layui-code-notepad .layui-code-h3{border-bottom:none}.layui-code-notepad .layui-code-ol li{background-color:#3F3F3F;border-left:none}
|
Before Width: | Height: | Size: 5.8 KiB |
Before Width: | Height: | Size: 11 KiB |
Before Width: | Height: | Size: 5.7 KiB |
Before Width: | Height: | Size: 701 B |
Before Width: | Height: | Size: 1.7 KiB |
Before Width: | Height: | Size: 299 KiB |
Before Width: | Height: | Size: 2.6 KiB |
Before Width: | Height: | Size: 5.4 KiB |
Before Width: | Height: | Size: 2.7 KiB |
Before Width: | Height: | Size: 4.0 KiB |
Before Width: | Height: | Size: 3.3 KiB |
Before Width: | Height: | Size: 7.3 KiB |
Before Width: | Height: | Size: 2.3 KiB |
Before Width: | Height: | Size: 1.8 KiB |
Before Width: | Height: | Size: 6.6 KiB |