def B(): '''测试所用''' wb = Excel(PathManage.db_path('btc.xlsx')) sheet_btc = wb.get_sheet_method('btc') wb.add_sheet_method('2016', 1) sheet_new = wb.get_sheet_method('2016') sheet_new.cell(row=1, column=1).value = sheet_btc.cell(row=1, column=1).value sheet_new.cell(row=1, column=2).value = sheet_btc.cell(row=1, column=2).value print(sheet_new.max_row) list_row = [] for row in range(2, sheet_btc.max_row + 1): date = sheet_btc.cell(row=row, column=1).value regex = re.compile('^(2016)') match = regex.match(date) if match: # print(row) list_row.append(row) print(list_row[0]) a = list_row[0] - 2 for column in range(1, sheet_btc.max_column + 1): sheet_new.cell(row=row - a, column=column).value = sheet_btc.cell( row=row, column=column).value print(sheet_new.max_row) wb.excel_save(PathManage.db_path('btc.xlsx'))
def create_pdf(user,data_list): '''字典生成pdf文件''' c = canvas.Canvas(PathManage.download_path(f'{user}.pdf')) pdfmetrics.registerFont(TTFont('msyh', PathManage.db_path('msyh.ttf'))) c.setFont('msyh', 12) textobject = c.beginText() textobject.setTextOrigin(inch, 11 * inch) now = datetime.datetime.today() # 设定日期格式 date = now.strftime('%Y-%m-%d %H:%M:%S') # 设置下载时间 textobject.textLines(f'下载时间:{date}'.center(80, '-')) for i in range(0, len(data_list)): data_dict = data_list[i] text_memo = f'{i+1}' + '. ' num = 1 for k, v in data_dict.items(): if num == len(data_dict): text_memo += f'{k}: {v} 。' num += 1 else: text_memo += f'{k}: {v} ,' num += 1 textobject.textLines(text_memo) c.drawText(textobject) c.showPage() c.save()
def create_input_pdf(user, data_list): '''列表生成pdf文件''' c = canvas.Canvas(PathManage.doc_path(f'{user}.pdf')) pdfmetrics.registerFont(TTFont('msyh', PathManage.db_path('msyh.ttf'))) c.setFont('msyh', 12) textobject = c.beginText() textobject.setTextOrigin(inch, 11 * inch) now = datetime.datetime.today() # 设定日期格式 date = now.strftime('%Y-%m-%d %H:%M:%S') # 设置下载时间 textobject.textLines(f'下载时间:{date}'.center(80, '-')) for i in range(0, len(data_list)): data_str = data_list[i] text_memo = f'{i+1}' + '. ' + data_str # num = 1 # for k, v in data_dict.items(): # if num == len(data_dict): # text_memo += f'{k}: {v} 。' # num += 1 # else: # text_memo += f'{k}: {v} ,' # num += 1 getDate = GetDate() getDate.get_data(text_memo, 60) text_list = getDate.text_list for text in text_list: textobject.textLines(text) c.drawText(textobject) c.showPage() c.save()
def main(): exAdmin = ExcelAdmin(PathManage.db_path('btc.xlsx')) for i in range(3, 9): # 作业需要没有放在项目main.py下执行,相应年份的数据放到的相应的工作表中 exAdmin.split_data(f'201{i}') exAdmin.add_average(f'201{i}') # 数据拆分完还可删除,方便循环测试,只要打开下面注释就可 # exAdmin.del_sheet_method(f'201{i}') exAdmin.save_method(PathManage.db_path('btc.xlsx'))
def get_users_data(self): '''获取users.pkl数据''' try: with open(PathManage.db_path('users.pkl'), 'rb') as f: users_dict = pickle.load(f) except Exception: data = {} self.save_users_data(data) with open(PathManage.db_path('users.pkl'), 'rb') as f: users_dict = pickle.load(f) return users_dict
def A(): '''测试所用''' wb_new = Excel() wb2 = Excel(PathManage.db_path('btc.xlsx')) sh1 = wb2.get_sheet_method('btc') wb_new.add_sheet_method('test', 0) sh_new = wb_new.get_sheet_method('test') for row in range(1, sh1.max_row + 1): date = sh1.cell(row=row, column=1).value sh_new.cell(row=row, column=1).value = date wb_new.excel_save(PathManage.db_path('btc_new.xlsx'))
def create_config(self, user, config_file='memo.ini'): '''添加配置文件''' configAdmin = ConfigAdmin() # configAdmin.add_config_section(user) # configAdmin.add_config_option(user,'db_name',r'${DEFAULT:base_dir}'+f'/{user}.pkl') # configAdmin.add_config_option(user,'db_type','pkl') dict_val = {} dict_val['db_name'] = self.base_dir + f'/{user}.db' dict_val['db_type'] = 'db' self.data[user] = dict_val configAdmin.write_config(PathManage.config_path(config_file), self.data) configAdmin.read_config(PathManage.config_path(config_file))
def save_to_excel(self, excel_filename): excel = Excel() excel.add_sheet_method('pic data', 0) sheet = excel.get_sheet_method('pic data') sheet.cell(row=1, column=1).value = '文件名' sheet.cell(row=1, column=2).value = '文件大小' file_name = [] file_size = [] for file in self.files: print(file) if re.match('(.*png)|(.*bmp)|(.*jpg)$', file): name = file.split('\\')[-1] file_name.append(name) size = DirUtil.get_file_size(file) file_size.append(size) if len(file_name): if len(file_name) > 2: for row in range(2, len(file_name) + 2): sheet.cell(row=row, column=1).value = file_name[row - 2] sheet.cell(row=row, column=2).value = file_size[row - 2] else: sheet.cell(row=2, column=1).value = file_name[0] sheet.cell(row=2, column=2).value = file_size[0] excel.excel_save(PathManage.doc_path(excel_filename))
def __init__(self, log_file='Joker', logger='Joker-Log'): '''指定保存日志的文件路径,日志级别,以及调用文件,日志存入到指定的文件中''' # logging.basicConfig(filemode='a', datefmt='%a, %d %b %Y %H:%M:%S') # 创建一个logger self.logger = logging.getLogger(logger) self.logger.setLevel(logging.INFO) # 添加时间戳 rq = time.strftime('%Y-%m-%d', time.localtime(time.time())) if log_file: log_file = log_file + '-' + rq + '.log' else: log_file = rq + '.log' # 这里进行判断,如果logger.handlers列表为空,则添加,否则,直接去写日志 if not self.logger.handlers: log_file = PathManage.log_path(log_file) # 创建文件 handler fh = logging.FileHandler(filename=log_file, encoding='utf-8') fh.setLevel(logging.DEBUG) # 创建控制台 handler ch = logging.StreamHandler() ch.setLevel(logging.WARNING) # 创建 formatter formatter = logging.Formatter( '%(asctime)s [%(levelname)s] %(name)s {%(filename)s line:%(lineno)d} ->>>>> %(message)s' ) fh.setFormatter(formatter) ch.setFormatter(formatter) # 把 ch, fh 添加到 logger self.logger.addHandler(fh) self.logger.addHandler(ch)
def save_userinfo(self): '''保存处理过的用户信息''' for user in self.users: data = self.user_info[user] with open(PathManage.db_path(f'{user}.json'), 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=4)
def main(): love = LoveLetter() love.add_title_method('这是一个love模板') love.add_lover_method('玲玲') love.add_paragraph_method('正文' * 10) love.add_heart_method() love.add_sign_method('张三') love.save_method(PathManage.doc_path('love.docx'))
def findback_password(self, user): '''通过已有用户名,找回密码''' try: with open(PathManage(f'{user}.json'), 'r', encoding='utf-8') as f: data = f.read() data = json.loads(data) return data['password'] except Exception as e: mylog.error(e)
def main(): docAdmin = Word() # print(docAdmin.ret) docAdmin.add_head_method('这是标题', 0) # print(docAdmin.ret) heart_path = PathManage.pic_path('heart.jpg') docAdmin.add_pic_method(heart_path) # print(docAdmin.ret) docAdmin.add_paragraph_method('这是副标题', 'Subtitle') p2 = docAdmin.add_paragraph_method('这是普通文字,这是普通文字,这是普通文字,这是普通文字,这是普通文字') docAdmin.add_style_method(p2, 'Title') print(type(p2)) p2_words = docAdmin.add_paragraph_words_method(p2, '这是追加的文字') # docAdmin.add_fontSize_method(p2,33) print(type(p2_words)) print(docAdmin.ret) doc_path = PathManage.doc_path('loveletter.docx') docAdmin.save_method(doc_path)
def get_users_info(self): '''获取所有用户信息''' data_users = {} for user in self.users: with open(PathManage.db_path(f'{user}.json'), 'r', encoding='utf-8') as f: data = f.read() data = json.loads(data) data_users[f'{user}'] = data return data_users
def csv(self, filename, fields, row_list): '''保存到CSV''' try: with open(PathManage.crawler_path(filename), 'w', newline='') as f: writer = csv.writer(f) writer.writerow(fields) for row in row_list: writer.writerow(row) return {'status': 0, 'statusText': 'csv saved'} except Exception: return {'status': 1, 'statusText': 'csv error'}
def __init__(self): '''初始化''' self.dirob = DirUtil() data = { 'username': '******', 'password': '******', 'type': "admin", 'operation': ['权限管理', 'crawler', 'office', 'image'] } with open(PathManage.db_path('admin.json'), 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=4)
def image_page(self): '''图片处理页面''' print('欢迎来到图片处理页面'.center(100, '*')) # TODO 完成两个相关方法 menu=['文件夹下所有图片缩略功能','获取件夹下所有图片大小数据并且保存到excel'] for i in range(len(menu)): print(i+1,menu[i]) id=input('请选择功能序号') if id.isdigit(): id=int(id) if id==1: self.imageutil.thumbnail_all() elif id==2: self.imageutil.save_to_excel(PathManage('pc_size.xls')) else: print('输入有误!')
def jump_background(self): '''方法注释:进入应用界面''' print('欢迎来到应用界面'.center(100, '*')) try: user = self.get_user_session() with open(PathManage.db_path(f'{user}.json'), 'r', encoding='utf-8') as f: data = f.read() data = json.loads(data) # print(data['operation']) # print(user) menu_list = data['operation'] print('菜单展示:') if len(menu_list) > 0: for i in range(len(menu_list)): print(i + 1, menu_list[i]) else: print('您还没开通权限,请联系管理员!') exit() id_str = input('请选择要进入的页面(选择对应序号)') id = int(id_str) if menu_list[id - 1] == '权限管理': authority = AuthorityManage() authority.authority_page() mylog.info(f'进入{menu_list[id-1]}页面') elif menu_list[id - 1] == 'crawler': crawler_manage = CrawlerManage() crawler_manage.crawler_page() mylog.info(f'进入{menu_list[id-1]}页面') elif menu_list[id - 1] == 'office': office_manage = OfficeManage(user) office_manage.office_page() mylog.info(f'进入{menu_list[id-1]}页面') elif menu_list[id - 1] == 'image': image_manage = ImageManage() image_manage.image_page() mylog.info(f'进入{menu_list[id-1]}页面') else: print('请输入正确的序号') except Exception as e: mylog.error(e)
def wrapper(*args, **kw): print('欢迎来到51备忘录登录页面'.center(100, '*')) username = input('用户名:') password = self.input_pw('密码:') # password=input('密码:') try: users = self.get_users() if username in users: with open(PathManage.db_path(f'{username}.json'), 'r', encoding='utf-8') as f: data = f.read() data = json.loads(data) if data['password'] == password: user_session = [] user = data['username'] user_session.append(user) if data['type'] == 'user': if data['enabled'] == 1: # 当做session用了 self.set_user_session(user_session, 'session.pkl') func(*args, **kw) else: print('你已被拉黑,请联系管理员!') else: # 当做session用了 self.set_user_session(user_session, 'session.pkl') func(*args, **kw) else: print('密码错误') exit() else: print('用户不存在,请注册!') reg = Register() reg.register_user() except Exception as e: mylog.error(e)
def save_images(self, image_list): for img in image_list[:self.limit]: print('保存:', img.get_attribute('alt')) filename = img.get_attribute('alt') + '.jpg' with open(PathManage.crawler_path(filename), 'wb') as f: f.write(requests.get(img.get_attribute('src')).content)
def save_users_data(self, data): '''保存用户注册信息''' with open(PathManage.db_path('users.pkl'), 'wb') as f: pickle.dump(data, f, 0)
def main(): # send_email() send_email_attach('这是测试附件的邮件', PathManage.download_path('jokerwatemark.pdf'))
#默认大小为21cm*29.7cm c = canvas.Canvas(file) #移动坐标原点(坐标系左下为(0,0)) c.translate(13 * cm, 2 * cm) #设置字体 c.setFont("Helvetica", 80) #指定描边的颜色 # c.setStrokeColorRGB(0, 1, 0) #指定填充颜色 # c.setFillColorRGB(0, 1, 0) #画一个矩形 # c.rect(cm, cm, 7*cm, 17*cm, fill=1) #旋转45度,坐标系被旋转 c.rotate(60) #指定填充颜色 c.setFillColorRGB(0.6, 0, 0) #设置透明度,1为不透明 c.setFillAlpha(0.1) #画几个文本,注意坐标系旋转的影响 c.drawString(3 * cm, 9 * cm, content) # c.setFillAlpha(0.6) # c.drawString(3*cm, 9*cm, content) #关闭并保存pdf文件 c.save() create_watermark(PathManage.db_path('watemark.pdf'))
def get_user_session(self): '''读取session文件''' with open(PathManage.db_path('session.pkl'), 'rb') as f: data = pickle.load(f) return data[0]
def del_data(sheet_name): '''测试删除工作表所用''' excel = Excel(PathManage.db_path('btc.xlsx')) excel.delete_sheet_method(sheet_name) excel.excel_save(PathManage.db_path('btc.xlsx'))
def save_users_json(self,data): '''保存到用户.json''' user=data['username'] with open(PathManage.db_path(f'{user}.json'),'w',encoding='utf-8') as f: json.dump(data,f,ensure_ascii=False,indent=4)
def remove_user_session(self): '''删除session文件''' if os.path.exists(PathManage.db_path('session.pkl')): os.remove(PathManage.db_path('session.pkl'))
def query_memo(self, from_month, to_month, user='******'): '''根据月份查询备忘录记录''' ret = {'staus': 0, 'message': 'success', 'data': {}} flag = True if isinstance(from_month, int): if not from_month in range(1, 13): ret['staus'] = 2 ret['message'] = 'from_month not in [1,12]' flag = False mylog.error(ret['message']) else: ret['staus'] = 3 ret['message'] = 'from_month data type error' flag = False mylog.error(ret['message']) if isinstance(to_month, int): if not to_month in range(1, 13): ret['staus'] = 2 ret['message'] = 'to_month not in [1,12]' flag = False mylog.error(ret['message']) else: ret['staus'] = 3 ret['message'] = 'to_month data type error' flag = False mylog.error(ret['message']) if from_month > to_month: ret['staus'] = 4 ret['message'] = 'from_month should not greater than to_month' flag = False mylog.error(ret['message']) with open(PathManage.db_path('users.pkl'), 'rb') as f: users_dict = pickle.load(f) users_list = users_dict.keys() if not user in users_list: ret['staus'] = 1 ret['message'] = 'user not exists' flag = False mylog.error(ret['message']) if flag: memoAdmin = MemoAdmin(user) memo_list = memoAdmin.memo_list target_list = [] for memo in memo_list: # print(memo) if memo['date']: memo_date_month = memo['date'].split('-')[1] memo_date_month = int(memo_date_month) # print(memo_date_moth) if memo_date_month >= from_month and memo_date_month <= to_month: target_list.append(memo) # print(target_list) ret['data'] = target_list mylog.info('query success.result:%s' % (ret['data'])) return ret
import os import sys dir_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(dir_path) from docx.enum.style import WD_STYLE_TYPE from docx import * from utils.path_manage import PathManage document = Document() styles = document.styles #生成所有段落样式 for s in styles: if s.type == WD_STYLE_TYPE.PARAGRAPH: document.add_paragraph('Paragraph style is : ' + s.name, style=s) document.save(PathManage.doc_path('para_style.docx'))
import os import sys dir_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(dir_path) from docx.enum.style import WD_STYLE_TYPE from docx import * from utils.path_manage import PathManage document = Document() styles = document.styles para = document.add_paragraph() #生成所有字符样式 for s in styles: if s.type == WD_STYLE_TYPE.CHARACTER: run = para.add_run("Character style is: " + s.name + "\n") run.style = s document.save(PathManage.doc_path('character_style.docx'))