from Info.models import Company, User, Message from .model_handler import UserHandler, CompanyHandler from django.conf import settings from datetime import datetime import os from django.http import FileResponse def is_login(request): if request.session.get('user_id') and request.session.get('company_id'): user = UserHandler.get_by_id(request.session.get('user_id')) if user.company.id == request.session.get('company_id'): return True else: return False else: return False def is_admin(request): user = UserHandler.get_by_id(request.session.get('user_id')) company = CompanyHandler.get_by_id(request.session.get('company_id')) if not user.admin or user.company != company: return False else: return True def file_upload(request, group: list): # group 参数表示上传文件的分类,会体现在上传的文件夹 result = {'code':1, 'target_file_path':None, 'target_file_name':None, 'result':'fail'} target_dir = settings.BASE_DIR.parent target_file_path = '/upload/' for g in group: target_file_path += g target_file_path += '/' user = UserHandler.get_by_id(request.session.get('user_id')) company = CompanyHandler.get_by_id(request.session.get('company_id')) target_file_path = target_file_path + str(company.id) + '/' target_file_path = target_file_path + str(user.id) + '/' target_file_path = target_file_path + datetime.now().strftime('%Y%m%d_%H%M%S') + '/' target_dir = str(target_dir).replace('\\', '/') + target_file_path target_file_name = request.FILES['files'].name if not os.path.isdir(target_dir): os.makedirs(target_dir) result = {'code':1, 'target_file_path':target_file_path, 'target_file_name':target_file_name, 'result':'fail'} try: destination = open(target_dir+target_file_name, 'wb+') for chunk in request.FILES['files'].chunks(): destination.write(chunk) destination.close() result['code'] = 0 result['result'] = 'pass' except: pass return result def get_file(request): target_dir = settings.BASE_DIR.parent target_file_path = request.get_full_path() target_file = str(target_dir).replace('\\', '/') + target_file_path return FileResponse(open(target_file, 'rb'), as_attachment=True) def delete_file(url): target_dir = settings.BASE_DIR.parent target_file = str(target_dir).replace('\\', '/') + url if os.path.exists(target_file): os.remove(target_file) return True else: return False def file_host(request): return request.get_host() + '/upload/' def send_message(from_user:User, to_user:User, title:str, content:str = None): # 未来可能扩展出短信,微信等多个功能 message = Message() if from_user: message.user_from = from_user message.user_to = to_user # message.company = company message.title = title if content: message.body = content message.save()