ahserver_g/ahserver/globalEnv.py

268 lines
5.1 KiB
Python
Raw Normal View History

2019-07-10 17:34:45 +08:00
# -*- coding:utf8 -*-
import os
import sys
import codecs
from urllib.parse import quote
import json
import random
import time
import datetime
from openpyxl import Workbook
from tempfile import mktemp
from appPublic.jsonConfig import getConfig
from appPublic.Singleton import GlobalEnv
from appPublic.argsConvert import ArgsConvert
2020-08-02 11:20:17 +08:00
from appPublic.timeUtils import str2Date,str2Datetime,curDatetime,getCurrentTimeStamp,curDateString, curTimeString
2019-07-10 17:34:45 +08:00
from appPublic.folderUtils import folderInfo
from appPublic.uniqueID import setNode,getID
from appPublic.unicoding import unicoding,uDict,uObject
from appPublic.Singleton import SingletonDecorator
2023-04-04 10:34:02 +08:00
from appPublic.rc4 import password
2019-07-10 17:34:45 +08:00
2019-12-07 07:16:42 +08:00
from sqlor.dbpools import DBPools,runSQL,runSQLPaging
2019-08-30 21:02:34 +08:00
from sqlor.crud import CRUD
2019-07-10 17:34:45 +08:00
from .xlsxData import XLSXData
from .uriop import URIOp
2023-04-04 10:34:02 +08:00
from .error import Success, Error, NeedLogin, NoPermission
2023-12-18 18:39:23 +08:00
from .filetest import current_fileno
2019-07-10 17:34:45 +08:00
from .serverenv import ServerEnv
def data2xlsx(rows,headers=None):
wb = Workbook()
ws = wb.active
i = 1
if headers is not None:
for j in range(len(headers)):
v = headers[j].title if headers[j].get('title',False) else headers[j].name
ws.cell(column=j+1,row=i,value=v)
i += 1
for r in rows:
for j in range(len(r)):
v = r[headers[j].name]
ws.cell(column=j+1,row=i,value=v)
i += 1
name = mktemp(suffix='.xlsx')
wb.save(filename = name)
wb.close()
return name
class FileOutZone(Exception):
def __init__(self,fp,*args,**kwargs):
super(FileOutZone,self).__init__(*args,**kwargs)
self.openfilename = fp
def __str__(self):
return self.openfilename + ': not allowed to open'
2024-03-01 13:19:46 +08:00
def get_config_value(kstr):
keys = kstr.split('.')
config = getConfig()
2024-03-12 18:33:17 +08:00
if config is None:
raise Exception('getConfig() error')
2024-03-01 13:19:46 +08:00
for k in keys:
config = config.get(k)
if not config:
return None
return config
def get_definition(k):
2024-03-12 18:33:17 +08:00
k = f'definitions.{k}'
return get_config_value(k)
2024-03-01 13:19:46 +08:00
2019-07-10 17:34:45 +08:00
def openfile(url,m):
fp = abspath(url)
if fp is None:
2022-06-23 14:58:03 +08:00
print(f'openfile({url},{m}),url is not match a file')
2019-07-10 17:34:45 +08:00
raise Exception('url can not mathc a file')
config = getConfig()
paths = [ os.path.abspath(p) for p in config.website.paths ]
fs = config.get('allow_folders',[])
fs = [ os.path.abspath(i) for i in fs + paths ]
r = False
for f in fs:
if fp.startswith(f):
r = True
break
if not r:
raise FileOutZone(fp)
return open(fp,m)
def isNone(a):
return a is None
def abspath(path):
config = getConfig()
paths = [ os.path.abspath(p) for p in config.website.paths ]
for root in paths:
p = root + path
if os.path.exists(root+path):
return p
return None
def appname():
config = getConfig()
try:
return config.license.app
except:
return "test app"
def configValue(ks):
config = getConfig()
try:
a = eval('config' + ks)
return a
except:
return None
def visualcoding():
return configValue('.website.visualcoding');
def file_download(request,path,name,coding='utf8'):
f = openfile(path,'rb')
b = f.read()
f.close()
fname = quote(name).encode(coding)
hah = b"attachment; filename=" + fname
# print('file head=',hah.decode(coding))
request.setHeader(b'Content-Disposition',hah)
request.setHeader(b'Expires',0)
request.setHeader(b'Cache-Control',b'must-revalidate, post-check=0, pre-check=0')
request.setHeader(b'Content-Transfer-Encoding',b'binary')
request.setHeader(b'Pragma',b'public')
request.setHeader(b'Content-Length',len(b))
request.write(b)
request.finish()
def initEnv():
pool = DBPools()
g = ServerEnv()
g.configValue = configValue
g.visualcoding = visualcoding
g.uriop = URIOp
g.isNone = isNone
2024-04-09 18:10:52 +08:00
g.len = len
g.print = print
2019-07-10 17:34:45 +08:00
g.json = json
g.int = int
g.str = str
g.float = float
2024-04-09 18:10:52 +08:00
g.complex = complex
2019-07-10 17:34:45 +08:00
g.type = type
g.ArgsConvert = ArgsConvert
g.time = time
2020-08-02 11:20:17 +08:00
g.curDateString = curDateString
g.curTimeString = curTimeString
2019-07-10 17:34:45 +08:00
g.datetime = datetime
g.random = random
g.str2date = str2Date
g.str2datetime = str2Datetime
g.curDatetime = curDatetime
g.uObject = uObject
g.uuid = getID
2019-12-07 07:16:42 +08:00
g.runSQL = runSQL
g.runSQLPaging = runSQLPaging
2019-07-10 17:34:45 +08:00
g.runSQLIterator = pool.runSQL
g.runSQLResultFields = pool.runSQLResultFields
g.getTables = pool.getTables
g.getTableFields = pool.getTableFields
g.getTablePrimaryKey = pool.getTablePrimaryKey
g.getTableForignKeys = pool.getTableForignKeys
g.folderInfo = folderInfo
g.abspath = abspath
g.data2xlsx = data2xlsx
g.xlsxdata = XLSXData
g.openfile = openfile
2019-08-30 21:02:34 +08:00
g.CRUD = CRUD
2020-07-12 16:08:50 +08:00
g.DBPools = DBPools
2023-04-04 10:34:02 +08:00
g.Error = Error
g.Success = Success
g.NeedLogin = NeedLogin
g.NoPermission = NoPermission
2023-04-14 11:39:36 +08:00
g.password_encode = password
2023-12-18 18:39:23 +08:00
g.current_fileno = current_fileno
2024-03-01 13:19:46 +08:00
g.get_config_value = get_config_value
g.get_definition = get_definition
2024-04-09 18:10:52 +08:00
def set_builtins():
all_f="""abs
aiter
all
anext
any
ascii
bin
bool
breakpoint
bytearray
bytes
callable
chr
classmethod
compile
complex
delattr
dict
dir
divmod
enumerate
eval
exec
filter
float
format
frozenset
getattr
globals
hasattr
hash
help
hex
id
input
int
isinstance
issubclass
iter
len
list
locals
map
max
memoryview
min
next
object
oct
open
ord
pow
print
property
range
repr
reversed
round
set
setattr
slice
sorted
staticmethod
str
sum
super
tuple
type
vars
zip"""
g = ServerEnv()
for l in all_f.aplit('\n'):
if l != '':
g[l] = l