This commit is contained in:
yumoqing 2023-02-22 22:16:41 +08:00
parent eaef8dfc5f
commit a14b95abd7
5 changed files with 61 additions and 29 deletions

View File

@ -40,14 +40,13 @@ class ObjectCache:
class BaseProcessor(AppLogger): class BaseProcessor(AppLogger):
def __init__(self):
super().__init__()
@classmethod @classmethod
def isMe(self,name): def isMe(self,name):
return name=='base' return name=='base'
def __init__(self,path,resource): def __init__(self,path,resource):
super().__init__()
self.env_set = False
self.path = path self.path = path
self.resource = resource self.resource = resource
self.retResponse = None self.retResponse = None
@ -60,6 +59,8 @@ class BaseProcessor(AppLogger):
self.content = '' self.content = ''
async def set_run_env(self, request): async def set_run_env(self, request):
if self.env_set:
return
self.real_path = self.resource.url2file(self.resource.entireUrl(request, self.path)) self.real_path = self.resource.url2file(self.resource.entireUrl(request, self.path))
g = ServerEnv() g = ServerEnv()
self.run_ns = {} self.run_ns = {}
@ -71,6 +72,7 @@ class BaseProcessor(AppLogger):
self.run_ns.update(kw) self.run_ns.update(kw)
self.run_ns['ref_real_path'] = self.real_path self.run_ns['ref_real_path'] = self.real_path
self.run_ns['processor'] = self self.run_ns['processor'] = self
self.env_set = True
async def execute(self,request): async def execute(self,request):
await self.set_run_env(request) await self.set_run_env(request)

View File

@ -5,7 +5,7 @@ import mimetypes
from aiohttp.web_exceptions import HTTPNotFound from aiohttp.web_exceptions import HTTPNotFound
from aiohttp.web import StreamResponse from aiohttp.web import StreamResponse
from aiohttp import web from aiohttp import web
import aiofile import aiofiles
from appPublic.rc4 import RC4 from appPublic.rc4 import RC4
@ -18,6 +18,9 @@ def path_decode(dpath):
rc4 = RC4() rc4 = RC4()
return rc4.decode(dpath,crypto_aim) return rc4.decode(dpath,crypto_aim)
async def file_upload(request):
pass
async def file_download(request, filepath, content_type=None): async def file_download(request, filepath, content_type=None):
filename = os.path.basename(filepath) filename = os.path.basename(filepath)
r = web.FileResponse(filepath) r = web.FileResponse(filepath)
@ -41,12 +44,11 @@ async def file_download(request, filepath, content_type=None):
) )
await response.prepare(request) await response.prepare(request)
cnt = 0 cnt = 0
with open(filepath, 'rb') as f: async with aiofiles.open(filepath, 'rb') as f:
chunk = f.read(10240000) chunk = await f.read(10240000)
cnt = cnt + len(chunk) cnt = cnt + len(chunk)
await response.write(chunk) await response.write(chunk)
await response.fsyn() await response.fsyn()
await response.write_eof() await response.write_eof()
return response return response
raise HTTPNotFound raise HTTPNotFound

View File

@ -3,7 +3,7 @@
import os import os
import time import time
import tempfile import tempfile
import aiofile import aiofiles
from appPublic.folderUtils import _mkdir from appPublic.folderUtils import _mkdir
from appPublic.jsonConfig import getConfig from appPublic.jsonConfig import getConfig
@ -35,14 +35,19 @@ class FileStorage:
return path return path
async def save(self,name,read_data): async def save(self,name,read_data):
# print(f'FileStorage():save():{name=}')
p = self._name2path(name) p = self._name2path(name)
fpath = p[len(self.root):]
_mkdir(os.path.dirname(p)) _mkdir(os.path.dirname(p))
async with aiofile.AIOFile(p,'wb') as f: async with aiofiles.open(p,'wb') as f:
siz = 0
while 1: while 1:
d = await read_data() d = await read_data()
if not d: if not d:
break break
siz += len(d);
await f.write(d) await f.write(d)
await f.fsync() await f.flush()
print(f'{name=} file({fpath}) write {siz} bytes')
return p[len(self.root):] return fpath

View File

@ -2,6 +2,7 @@ import os
import re import re
import codecs import codecs
from traceback import print_exc from traceback import print_exc
# from showcallstack import showcallstack
import asyncio import asyncio
@ -108,24 +109,34 @@ class ProcessorResource(AppLogger, StaticResource,Url2File):
return ns return ns
ns = {} ns = {}
while 1: while 1:
field = await reader.next() try:
if not field: field = await reader.next()
break if not field:
value = '' break
if hasattr(field,'filename'): value = ''
saver = FileStorage() if hasattr(field,'filename') and field.filename is not None:
value = await saver.save(field.filename,field.read_chunk) saver = FileStorage()
else: value = await saver.save(field.filename,field.read_chunk)
value = await field.read(decode=True)
ov = ns.get(field.name)
if ov:
if type(ov) == type([]):
ov.append(value)
else: else:
ov = [ov,value] value = await field.read(decode=True)
else: value = value.decode('utf-8')
ov = value ov = ns.get(field.name)
ns.update({field.name:ov}) if ov:
if type(ov) == type([]):
ov.append(value)
else:
ov = [ov,value]
else:
ov = value
ns.update({field.name:ov})
# print(f'getPostData():{ns=}')
except Exception as e:
print(e)
print_exc()
print('-----------except out ------------')
break;
print(f'getPostData():{ns=}')
# showcallstack()
return ns return ns
async def _handle(self,request:Request) -> StreamResponse: async def _handle(self,request:Request) -> StreamResponse:
@ -182,10 +193,15 @@ class ProcessorResource(AppLogger, StaticResource,Url2File):
async def getArgs(): async def getArgs():
print(f'getArgs, url={str(request.url)}')
if hasattr(request, 'params_kw'):
return request.params_kw
print('request.params=', request.get('params_kw'))
ns = DictObject() ns = DictObject()
if request.method == 'POST': if request.method == 'POST':
return await self.getPostData(request) return await self.getPostData(request)
ns = multiDict2Dict(request.query) ns = multiDict2Dict(request.query)
request.params_kw = ns
return ns return ns
self.y_env.i18n = serveri18n self.y_env.i18n = serveri18n

View File

@ -34,7 +34,7 @@ class Url2File:
def url2file(self, url: str) -> str: def url2file(self, url: str) -> str:
url = url.split('?')[0] url = url.split('?')[0]
real_path = self.url2ospath(url) real_path = self.url2ospath(url)
if os.path.isdir(real_path): if os.path.isdir(real_path):
for idx in self.indexes: for idx in self.indexes:
p = os.path.join(real_path,idx) p = os.path.join(real_path,idx)
@ -90,6 +90,13 @@ class TmplUrl2File:
return fp return fp
return None return None
def relatedurl(self,url: str, name: str) -> str:
for u2f in self.u2fs:
fp = u2f.relatedurl(url, name)
if fp:
return fp
return None
def list_tmpl(self): def list_tmpl(self):
ret = [] ret = []
for rp,_ in self.paths: for rp,_ in self.paths: