ahserver_g/ahserver/filestorage.py

49 lines
1.1 KiB
Python
Raw Normal View History

2019-07-10 17:34:45 +08:00
# fileUpload.py
import os
import time
import tempfile
import aiofile
from appPublic.folderUtils import _mkdir
from appPublic.jsonConfig import getConfig
class FileStorage:
def __init__(self):
config = getConfig()
self.root = config.filesroot or tempfile.gettempdir()
def realPath(self,path):
if path[0] == '/':
path = path[1:]
p = os.path.join(self.root,path)
return p
2019-08-28 10:15:35 +08:00
def _name2path(self,name):
2019-07-10 17:34:45 +08:00
name = os.path.basename(name)
paths=[191,193,197,199,97]
v = int(time.time()*1000000)
# b = name.encode('utf8') if not isinstance(name,bytes) else name
# v = int.from_bytes(b,byteorder='big',signed=False)
path = os.path.abspath(os.path.join(self.root,
2019-08-28 10:15:35 +08:00
str(v % paths[0]),
str(v % paths[1]),
str(v % paths[2]),
str(v % paths[3]),
str(v % paths[4]),
2019-07-10 17:34:45 +08:00
name))
return path
2019-08-28 10:15:35 +08:00
async def save(self,name,read_data):
p = self._name2path(name)
2019-07-10 17:34:45 +08:00
_mkdir(os.path.dirname(p))
2019-08-28 10:15:35 +08:00
async with aiofile.AIOFile(p,'wb') as f:
2019-07-10 17:34:45 +08:00
while 1:
d = await read_data()
if not d:
break
await f.write(d)
2019-08-28 10:15:35 +08:00
await f.fsync()
2019-07-10 17:34:45 +08:00
return p[len(self.root):]