async def get_project_id(id: int = Query(...)) -> BaseRes: _, error = verify_project_deleted(id) if error: return error try: project: AtpProject = Db.select_by_primary_key(AtpProject, id) member_relation_list: List[AtpProjectMember] = Db.select_by_condition( AtpProjectMember, [ AtpProjectMember.project_id == id, AtpProjectMember.is_delete == 2 ] ) if project.img: file: AtpFileSystemFile = Db.select_by_primary_key(AtpFileSystemFile, project.img) project.img = { 'id': file.id, 'url': get_settings().archive_host + file.name } else: project.img = { 'id': 0, 'url': 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png' } project.member = [] for member_relation in member_relation_list: user: SysUser = Db.select_by_primary_key(SysUser, member_relation.member_id) project.member.append({ 'id': user.id, 'cname': user.cname, }) return BaseRes(data=project) except Exception as e: logger.error(traceback.format_exc()) return BaseRes(status=0, error=str(e))
async def del_project_img( file_id: int = Body(..., embed=True), task_id: int = Body(None, embed=True), token_user: TokenUser = Depends(auth_token) ) -> BaseRes: session = Db.get_session() file: AtpFileSystemFile = session.query(AtpFileSystemFile).get(file_id) if not file: return BaseRes(status=0, error='file not found') file_path = get_settings().static_path + file.name if not os.path.exists(file_path): return BaseRes(status=0, error='file not found') os.remove(file_path) if task_id: task: AtpOverviewTask = session.query(AtpOverviewTask).get(task_id) _, error = verify_project_filed(task.project_id) if error: return error _, error = verify_project_member(token_user.user_id, task.project_id) if error: return error img_list = json.loads(task.img) img_list.remove(file_id) task.img = json.dumps(img_list) session.commit() return BaseRes()
async def get_workstation_projects(token_user: TokenUser = Depends( auth_token)) -> BaseRes: try: project_list: List[AtpProject] = Db.select_by_condition( AtpProject, [AtpProject.type == 1, AtpProject.is_delete == 2], AtpProject.create_time.desc()) parted_project_list = [] for project in project_list: is_part_in = Db.select_by_condition( AtpProjectMember, [ AtpProjectMember.is_delete == 2, AtpProjectMember.project_id == project.id, AtpProjectMember.member_id.in_([token_user.user_id]) ], ) if is_part_in: parted_project_list.append(project) if project.img: file: AtpFileSystemFile = Db.select_by_primary_key( AtpFileSystemFile, project.img) project.img = { 'id': file.id, 'url': get_settings().archive_host + file.name } else: project.img = { 'id': 0, 'url': 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png' } session = Db.get_session() report_list: List[AtpProjectTestReport] = session.query( AtpProjectTestReport).join( AtpProject, AtpProject.id == AtpProjectTestReport.project_id).filter( AtpProjectTestReport.is_delete == 2, AtpProjectTestReport.creator == token_user.user_id, AtpProject.is_delete == 2).limit(10).all() total_projects_num = Db.select_count_by_condition( AtpProject.id, [AtpProject.is_delete == 2]) return BaseRes( data={ 'underway_projects': project_list[:6], 'parted_projects': parted_project_list[:6], 'my_reports': report_list, 'total_projects_num': total_projects_num, 'total_underway_projects_num': len(project_list) }) except Exception as e: logger.error(e) return BaseRes(status=0, error=str(e))
async def upload_project_img( projectImg: UploadFile = File(...), project_id=Body(None, embed=True), token_user: TokenUser = Depends(auth_token) ) -> BaseRes: encrypt_filename: str = hashlib.md5((projectImg.filename + str(time.time())).encode()).hexdigest() suffix = projectImg.content_type.split('/')[1] filename = encrypt_filename + '.' + suffix try: with open(get_settings().static_path + filename, 'wb+') as f: f.write(await projectImg.read()) session = Db.get_session() file = AtpFileSystemFile( name=filename, creator=token_user.user_id, create_time=datetime.datetime.now() ) session.add(file) session.commit() if project_id: _, error = verify_project_filed(project_id) if error: return error _, error = verify_project_owner(token_user.user_id, project_id) if error: return error session.query(AtpProject) \ .filter(*[AtpProject.id == project_id, AtpProject.is_delete == 2]) \ .update({ # AtpProject.img: 'http://localhost:8900/static/' + filename, AtpProject.img: file.id, AtpProject.updator: token_user.user_id, AtpProject.update_time: datetime.datetime.now() }) session.commit() return BaseRes(data={'id': file.id, 'fileName': filename, 'url': get_settings().archive_host + filename}) except Exception as e: logger.error(traceback.format_exc()) return BaseRes(status=0, error=str(e))
async def upload_task_img(projectImg: UploadFile = File(...), project_id=Body(..., embed=True), task_id=Body(None, embed=True), token_user: TokenUser = Depends( auth_token)) -> BaseRes: _, error = verify_project_filed(project_id) if error: return error _, error = verify_project_owner(token_user.user_id, project_id) if error: return error encrypt_filename: str = hashlib.md5( (projectImg.filename + str(time.time())).encode()).hexdigest() suffix = projectImg.content_type.split('/')[1] filename = encrypt_filename + '.' + suffix try: with open(get_settings().static_path + filename, 'wb+') as f: f.write(await projectImg.read()) session = Db.get_session() file = AtpFileSystemFile(name=filename, creator=token_user.user_id, create_time=datetime.datetime.now()) session.add(file) session.commit() if task_id: task: AtpOverviewTask = session.query(AtpOverviewTask).get(task_id) file_ids = json.loads(task.img) if task.img else [] file_ids.append(file.id) task.img = json.dumps(file_ids) session.commit() return BaseRes( data={ 'fileName': filename, 'id': file.id, 'url': get_settings().archive_host + filename }) except Exception as e: logger.error(e) return BaseRes(status=0, error=str(e))
async def get_all_project(type: int = Query(...)) -> BaseRes: try: project_list: List[AtpProject] = Db.select_by_condition( AtpProject, [AtpProject.is_delete == 2, AtpProject.type == type], AtpProject.create_time.desc() ) for project in project_list: if project.img: file: AtpFileSystemFile = Db.select_by_primary_key(AtpFileSystemFile, project.img) project.img = { 'id': file.id, 'url': get_settings().archive_host + file.name } else: project.img = { 'id': 0, 'url': 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png' } return BaseRes(data=project_list) except Exception as e: logger.error(traceback.format_exc()) return BaseRes(status=0, error=str(e))
async def get_task_by_condition(project_id: int = Query(...), task_id: int = Query(...), token_user: TokenUser = Depends( auth_token)) -> BaseRes: _, error = verify_project_deleted(project_id) if error: return error session = Db.get_session() try: task: AtpOverviewTask = session.query(AtpOverviewTask).get(task_id) followers: List[SysUser] = session.query(SysUser).filter(*[ SysUser.is_delete == 2, SysUser.id.in_(json.loads(task.follower)) ]).all() imgs: List[AtpFileSystemFile] = session.query( AtpFileSystemFile).filter(*[ AtpFileSystemFile.is_delete == 2, AtpFileSystemFile.id.in_(json.loads(task.img)) ]).all() cases: List[AtpProjectCase] = session.query(AtpProjectCase).filter(*[ AtpProjectCase.is_delete == 2, AtpProjectCase.id.in_(json.loads(task.relevance_case)) ]).all() img_list = [] for i in imgs: img_list.append({ 'id': i.id, 'name': i.name, 'url': get_settings().archive_host + i.name }) task.follower = followers task.img = img_list task.relevance_case = cases return BaseRes(data=task) except Exception as e: logger.error(traceback.format_exc()) return BaseRes(status=0, error=str(e))
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/6/11 6:30 下午 # @Author : yxChen import sqlalchemy from sqlalchemy.orm import sessionmaker, Session from sqlalchemy.ext.declarative import declarative_base from typing import List from sqlalchemy import func from env_config.settings import get_settings mysql_config = get_settings().mysql_config DATABASE_URL = f"mysql+pymysql://{mysql_config['username']}:{mysql_config['password']}@{mysql_config['host']}:{mysql_config['port']}/{mysql_config['database']}" engine = sqlalchemy.create_engine(DATABASE_URL, pool_recycle=1) SessionLocal = sessionmaker(autoflush=False, autocommit=False, bind=engine) Base = declarative_base() class Db: @classmethod def select_by_condition(cls, model: Base, condition: list, order_by=None, offset: int = None, limit: int = None) -> List[Base]: session = SessionLocal() res = session.query(model).filter( *condition).order_by(order_by).offset(offset).limit(limit).all() session.close()
def start(): db_init() if not os.path.exists(get_settings().static_path): os.mkdir(get_settings().static_path) app = create_app() uvicorn.run(app, **get_settings().config)
from env_config.settings import get_settings import optparse if __name__ == '__main__': usage = "python start.py -e/--environment <local|prod|dev> " parser = optparse.OptionParser(usage) parser.add_option('-e', '--environment', dest='env', type='string', help='environment', default='local') options, args = parser.parse_args() get_settings(options.env) from run import start start()