def get_emp_seat_docs(emp_seat, sub_emp): docs_from_path = [{ 'id': path.document_id, 'type': path.document.document_type.description, 'date': datetime.strftime(path.timestamp, '%d.%m.%Y'), 'author': path.employee_seat.employee.pip, 'is_active': path.document.is_active, 'main_field': get_main_field(path.document), } for path in Document_Path.objects.filter(mark_id=1).filter( employee_seat_id=sub_emp).filter(document__testing=testing).filter( document__closed=False)] docs_from_nark_demand = [{ 'id': md.document_id, 'type': md.document.document_type.description, 'date': datetime.strftime(md.document_path.timestamp, '%d.%m.%Y'), 'author': md.document_path.employee_seat.employee.pip, 'is_active': md.document.is_active, 'main_field': get_main_field(md.document), } for md in Mark_Demand.objects.filter(recipient=sub_emp).filter( document__testing=testing).filter(document__closed=False)] docs = docs_from_path + docs_from_nark_demand docs = [dict(t) for t in {tuple(d.items()) for d in docs}] # Видаляємо дублікати return docs
def index(request): update_require = False # 是否需要更新 time_of_now = datetime.strftime(now(), "%Y-%m-%d %H:%M:%S") # 现在的时间 timestamp_of_now = time.mktime( time.strptime(time_of_now, "%Y-%m-%d %H:%M:%S")) # 现在时间对应的时间戳 last_update_time = data_dict.get("update_time") # 上次更新的时间 if last_update_time: # 能获取到上次的更新时间,则将上次更新时间和现在的时间进行比较 timestamp_of_last_update = time.mktime( time.strptime(last_update_time, "%Y-%m-%d %H:%M:%S")) # 上次更新对应的时间戳 if timestamp_of_now - timestamp_of_last_update >= 5 * 60: # 间隔五分钟则会更新数据 update_require = True else: date_of_now = datetime.strftime(now(), "%Y-%m-%d") # 现在的日期 last_update_date = data_dict.get("update_time").split(" ")[ 0] # 上次更新的日期 if date_of_now != last_update_date: # 上次更新日期和现在的日期不相等则更新数据 data_dict["message"] = "数据正在更新中,请稍后!" update_require = True else: # 获取不到上次更新时间,则说明服务器第一次启动,需要进行更新数据操作 update_require = True # print(data_dict) # print(time_of_now, last_update_time, update_require) if update_require: # 需要更新,才会更新数据 data_dict["update_time"] = time_of_now # 记录本次更新时间 data_dict["message"] = "数据正在更新中,请稍后!" t = threading.Thread(target=get_home_page_data) # 生成一个用来更新数据的线程 t.start() # 启动线程 return render(request, "automatic_index.html", {"data_dict": data_dict})
def get_doc_type_docs(emp_seat, doc_meta_type): # Отримуємо ід посади з ід людинопосади seat_id = Employee_Seat.objects.filter( id=emp_seat).values_list('seat_id')[0][0] # Список всіх підлеглих користувача: subs_list = get_sub_seats(int(seat_id)) # Шукаємо документи кожного підлеглого subs = [] if subs_list: for sub in subs_list: subs.append(sub['id']) docs_from_path = [{ 'id': path.document_id, 'type': path.document.document_type.description, 'date': datetime.strftime(path.timestamp, '%d.%m.%Y'), 'author': path.employee_seat.employee.pip, 'is_active': path.document.is_active, 'main_field': get_main_field(path.document), } for path in Document_Path.objects.filter(mark_id=1).filter( document__document_type__meta_doc_type_id=doc_meta_type).filter( employee_seat__seat_id__in=subs).filter( document__testing=testing).filter(document__closed=False)] docs_from_nark_demand = [{ 'id': md.document_id, 'type': md.document.document_type.description, 'date': datetime.strftime(md.document_path.timestamp, '%d.%m.%Y'), 'author': md.document_path.employee_seat.employee.pip, 'is_active': md.document.is_active, 'main_field': get_main_field(md.document), } for md in Mark_Demand.objects.filter( document__document_type__meta_doc_type_id=doc_meta_type).filter( recipient__seat_id__in=subs).filter( document__testing=testing).filter(document__closed=False)] docs = docs_from_path + docs_from_nark_demand docs = [dict(t) for t in {tuple(d.items()) for d in docs}] # Видаляємо дублікати return docs
def my_custom_sql(): with connection.cursor() as cursor: try: row = ("Time Report Run At " + str(datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M')) + ".","\n") row += ("This report was run for the following dates: " + str(start) + " through " + str(end) + ".", "\n") if form3.cleaned_data['report_Type'] == '1': row += ("<th>Employee Name</th><th>Clocked In</th><th>Lunch Start</th><th>Lunch End</th><th>Clocked Out</th><th>Time Type</th><th>Manual Entry</th>", "\n") else: row += ("Employee Name, ", " Clocked In , ", " Lunch Start, "," Lunch End, "," Clocked Out , ", " Time Type, ", "Manual Entry", "\n") cursor.execute("select concat(au.first_name, ' ', au.last_name), DATE_FORMAT(DATE_SUB(in_time, INTERVAL 6 HOUR), %s),DATE_FORMAT(DATE_SUB(lunchin_time, INTERVAL 6 HOUR), %s), DATE_FORMAT(DATE_SUB(lunchout_time, INTERVAL 6 HOUR), %s), DATE_FORMAT(DATE_SUB(out_time, INTERVAL 6 HOUR), %s), timeType, is_Manual FROM times_timekeep tt JOIN auth_user au ON au.id = tt.user_id WHERE tt.in_time BETWEEN DATE_ADD(%s, INTERVAL 6 HOUR) AND DATE_ADD(%s, INTERVAL 30 HOUR) AND tt.user_id LIKE %s ORDER BY 2,1", [dF, dF, dF, dF, start, end, user_id]) if form3.cleaned_data['report_Type'] == '1': for rows in cursor.fetchall(): if rows[6] == 0: row += ("<td>" + str(rows[0]) + "</td>" + "<td>" + str(rows[1])+ "</td>" + "<td>" + str(rows[2]) + "</td>" + "<td>" + str(rows[3]) + "</td>" + "<td>" + str(rows[4]) + "</td>" + "<td>" + str(rows[5]) + "</td>" + "<td>" + "False" + "</td>", "\n") else: row += ("<td>" + str(rows[0]) + "</td>" + "<td>" + str(rows[1])+ "</td>" + "<td>" + str(rows[2]) + "</td>" + "<td>" + str(rows[3]) + "</td>" + "<td>" + str(rows[4]) + "</td>" + "<td>" + str(rows[5]) + "</td>" + "<td>" + "True" + "</td>", "\n") else: for rows in cursor.fetchall(): if rows[6] == 0: row += (rows[0], ",",rows[1],",",rows[2],",",rows[3],",", rows[4], ",",rows[5],",","False", "\n") else: row += (rows[0], ",",rows[1],", ",rows[2],",",rows[3],",", rows[4], ", ",rows[5],",","True", "\n") row += ("\n",) row += ("The decimal is a percentage of an hour (ex .5 = 30minutes).",) row += ("Please press the back arrow in your browser to return to the application.",) except Exception as e: row += ("There was an error while processing the request." + "error: " + str(e),) finally: cursor.close() return row
def user_login(request): Task.objects.all().delete() CompletedTask.objects.all().delete() job1(repeat=30) tenhour(repeat=36000) si = "" t = datetime.strftime(datetime.now(), '%H:%M') print(t) if request.user.is_authenticated: return redirect('upload') elif request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): user = form.get_user() login(request, user) if request.user.is_authenticated: return redirect('upload') else: s = "incorret password" return render(request, 'todo/login.html', { 'form': form, 'si': s }) else: return render(request, 'todo/login.html', {'form': form, 'si': si}) else: form = AuthenticationForm() return render(request, 'todo/login.html', {'form': form})
def get_delegated_docs(emp, sub=0, doc_meta_type=0): docs = Mark_Demand.objects\ .filter(document__testing=testing)\ .filter(document__closed=False)\ .filter(delegated_from_id=emp) if sub != '0': docs = docs.filter(recipient=sub) else: seat = Employee_Seat.objects.values_list('seat_id', flat=True).filter(id=emp)[0] subs = get_sub_emps(seat, True) subs = [sub['id'] for sub in subs] docs = docs.filter(recipient__in=subs) if doc_meta_type != '0': docs = docs.filter( document__document_type__meta_doc_type=doc_meta_type) docs_list = [{ 'id': md.document_id, 'type': md.document.document_type.description, 'date': datetime.strftime(md.document_path.timestamp, '%d.%m.%Y'), 'author': md.document_path.employee_seat.employee.pip, 'md_is_active': md.is_active, 'main_field': get_main_field(md.document), } for md in docs] return docs_list
def audit_log_detail(request, session_id): """ 详细审计日志查看页面 :param request: :param session_id: session对象ID :return: """ condition_dict = { "list_per_page": request.GET.get("list_per_page", 100), "parse_mark": request.GET.get("parse_mark") } audit_log_detail_form_obj = forms.AuditLogDetailForm(data=condition_dict) session_obj = models.Session.objects.filter( id=session_id).first() # 获取session对象 audit_log_detail_path = os.path.join( settings.AUDIT_LOG_DIR, datetime.strftime(session_obj.date, "%Y-%m-%d"), f"strace_{session_obj.id}.log") if os.path.exists(audit_log_detail_path): audit_log_parser = audit.AuditLogHandler( audit_log_detail_path, condition_dict.get("parse_mark")) cmd_list = audit_log_parser.parse() cmd_list = utils.get_paginator_query_sets( request, cmd_list, condition_dict.get("list_per_page")) return render( request, "audit_log_detail.html", { "audit_log_detail_form_obj": audit_log_detail_form_obj, "cmd_list": cmd_list }) else: return HttpResponse("Sorry the file is not exist!")
def get_wdzj_info(request): """获取网贷之家数据信息并存入数据库""" if request.method == "GET": headers = {"User-Agent": random.choice(utils.user_agent)} # 访问网贷之家数据接口,获取昨天各平台数据信息 response = requests.post("http://shuju.wdzj.com/plat-data-custom.html", headers=headers) data = response.json() # 用json解析数据 qdate = datetime.strftime(datetime.now() + timedelta(-1), "%Y-%m-%d") # 获取昨天日期 # 循环在数据库创建每个平台信息 for msg_dic in data: models.WDZJInfo.objects.using("default").create( qdate=qdate, # 日期 platName=msg_dic.get("platName"), # 平台名称 amount=msg_dic.get("amount"), # 成交量(万元) incomeRate=msg_dic.get("incomeRate"), # 平均预期收益率(%) loanPeriod=msg_dic.get("loanPeriod"), # 平均借款期限(月) regCapital=msg_dic.get("regCapital"), # 注册资本(万元) fullloanTime=msg_dic.get("fullloanTime"), # 满标用时(分) stayStillOfTotal=msg_dic.get("stayStillOfTotal"), # 待还余额(万元) netInflowOfThirty=msg_dic.get("netInflowOfThirty"), # 资金净流入(万元) timeOperation=msg_dic.get("timeOperation"), # 运营时间(月) bidderNum=msg_dic.get("bidderNum"), # 投资人数(人) borrowerNum=msg_dic.get("borrowerNum"), # 借款人数(人) totalLoanNum=msg_dic.get("totalLoanNum"), # 借款标数(个) top10DueInProportion=msg_dic.get("top10DueInProportion"), # 前十大土豪待收金额占比(%) avgBidMoney=msg_dic.get("avgBidMoney"), # 人均投资金额(万元) top10StayStillProportion=msg_dic.get("top10StayStillProportion"), # 前十大借款人待还金额占比(%) avgBorrowMoney=msg_dic.get("avgBorrowMoney"), # 人均借款金额(万元) developZhishu=msg_dic.get("developZhishu") # 发展指数排名 ) logger.info("%s网贷之家数据已经更新!" % (qdate,)) return HttpResponse("网贷之家数据填入完毕!")
def cmd_run(multi_task_detail_obj_id): """连上远程主机并执行命令""" import django django.setup() from web import models from django.utils.timezone import datetime # 获取批量任务详细信息对象 multi_task_detail_obj = models.MultiTaskDetail.objects.filter( id=multi_task_detail_obj_id).first() try: # 创建SSH对象 ssh = paramiko.SSHClient() # 允许连接不在know_hosts文件中的主机 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 连接服务器 ssh.connect( hostname=multi_task_detail_obj.bind_host.host.ip_adr, port=multi_task_detail_obj.bind_host.host.port, username=multi_task_detail_obj.bind_host.remote_user.username, password=multi_task_detail_obj.bind_host.remote_user.password, timeout=10 # 10秒超时时间 ) # 执行命令 stdin, stdout, stderr = ssh.exec_command( multi_task_detail_obj.multi_task.content) # 获取命令结果(包含标准输出和标准错误) result = f"{stdout.read().decode()}\n{stderr.read().decode()}" multi_task_detail_obj.result = result multi_task_detail_obj.status = 1 # 修改状态为执行成功 end_time = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S") multi_task_detail_obj.end_time = end_time # 命令执行的终止时间 multi_task_detail_obj.save() # 关闭连接 ssh.close() except Exception as e: multi_task_detail_obj.result = e multi_task_detail_obj.status = 2 end_time = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S") multi_task_detail_obj.end_time = end_time multi_task_detail_obj.save()
def gather(self): self.logger.info("Starting archiving operations") # First find the devices current epoh self.dev_bootup = self.spsp.get_time_of_bootup() read_freq = self.spsp.settings.get_measurement_frequency() # Now get the date of the lat measurement last_measure = Measurement.objects.filter( station=self.station).order_by('date').last() start_offset = None if not last_measure or self.dev_bootup > last_measure.date: start_offset = 1 else: start_offset = int(last_measure.date.timestamp()) - int( self.dev_bootup.timestamp()) + read_freq self.logger.info( "Calculated the device bootup time: " + datetime.strftime(self.dev_bootup, "%Y-%m-%d %H:%M:%S")) self.logger.debug("Using start offset: " + str(start_offset)) output = [] offset = start_offset # get the data, 500 records at a time while offset and len(output) < 500 and offset < int( timezone.now().timestamp() - self.dev_bootup.timestamp()): data = None try: data = self.spsp.get_archived_reading(offset) except BTHandler.CommandTimeout: self.logger.error( "Warning, could not get stored for offset: %d" % offset) self.logger.error("Trying to reconnect...") # and retry try: self.spsp.disconnect() self.spsp.connect() data = self.spsp.get_archived_reading(offset) except Exception as e: self.logger.critical( "Failed twice, giving up, trying to store what we've got so far, final failure reason: " + repr(e)) break if data: output += data offset = data[-1]['timestamp'] + read_freq else: # try finding a new offset from the place we finished at self.logger.error("Timer drift detected at " + str(offset)) offset = self.spsp.find_starting_offset(offset) self.logger.debug("Fetching done.") return output
def get_profile_pic_upload_location(instance, filename): """Save profile pictures in object store""" extension = filename.split(".")[-1] # Get the name with all special characters removed name_str = "".join(e for e in instance.get_full_name() if e.isalnum()) year = datetime.now().year # Assemble file location and insert date data location = f"ProfilePics/{year}/{name_str}.{extension}" location = datetime.strftime(datetime.now(), location) return location
def edit(request, usr, tid): if request.user.is_authenticated: s = request.user.username a = Document.objects.filter(todo_id=tid) if request.method == 'POST': b = a[0] b.userid = s b.task = request.POST.get('task') b.date = request.POST.get('date') b.time = request.POST.get('time') print(request.POST.get('time')) x = request.POST.get('time') b.save() return redirect('files') else: if (len(a) > 0): b = a[0] else: return redirect('files') if (b.userid == s): print(b.time, b.date, "hiiiiiiiiiiiiii") k = str(b.date) k = k.split("-") p = k[0] + "-" + k[1] + "-" + k[2] k = str(b.time) k = k.split(":") p1 = k[0] + ":" + k[1] + ":" + k[2] today = str( datetime.strftime(datetime.now() - timedelta(0), '%Y-%m-%d')) q = today.split("-") q1 = str(q[2]).split(" ") d = q[0] + "-" + q[1] + "-" + q[2] today = str(datetime.today()) q = today.split(" ") h = str(q[1]).split(":") h = h[0] + ":" + h[1] return render(request, 'todo/edit.html', { 'l': b, 'p': p, 'p1': p1, 'd': d }) else: return redirect('files') else: return HttpResponse("<h1>please login to continue</h1>")
def get_wdty_info(request): """获取网贷天眼数据信息并存入数据库""" if request.method == "GET": headers = {"User-Agent": random.choice(utils.user_agent)} response = requests.get("http://www.p2peye.com/shuju/ptsj/", headers=headers) ret = response.content.decode("GBK") tbody = re.findall('<tbody[\s\S]*</tbody>', ret, re.S) # 获取tbody内容 name = re.findall('>(.{2,10})<\/a', tbody[0], re.S) # 获取平台名称 name = [i for i in name if i != "添加关注"] total = re.findall('<td class="total">(\d*.\d*)万</td>', tbody[0], re.S) # 获取平台成交额(万) rate = re.findall('<td class="rate">(\d*.\d*)%</td>', tbody[0], re.S) # 获取平台综合利率(%) pnum = re.findall('<td class="pnum">(\d*)人</td>', tbody[0], re.S) # 获取平台投资人数(人) cycle = re.findall('<td class="cycle">(\d*.\d*)月</td>', tbody[0], re.S) # 获取平台借款周期(月) p1num = re.findall('<td class="p1num">(\d*)人</td>', tbody[0], re.S) # 获取平台借款人(人) fuload = re.findall('<td class="fuload">(\d*.\d*)分钟</td>', tbody[0], re.S) # 获取平台满标速度(分钟) alltotal = re.findall('<td class="alltotal">(-?\d*.\d*)万</td>', tbody[0], re.S) # 获取平台累计贷款余额(万) capital = re.findall('<td class="capital">(-?\d*.\d*)万</td>', tbody[0], re.S) # 获取平台资金净流入(万) data_list = [] # 存放500万及以上平台数据信息包括人众金服 for index, temp_name in enumerate(name): if float(total[index]) >= 500 or temp_name == "人众金服": # 存放每一个平台的信息 temp_dict = {} temp_dict["name"] = temp_name # 平台名称 temp_dict["total"] = float(total[index]) # 平台成交额(万) temp_dict["rate"] = float(rate[index]) # 平台综合利率(%) temp_dict["pnum"] = int(pnum[index]) # 平台投资人数(人) temp_dict["cycle"] = float(cycle[index]) # 平台借款周期(月) temp_dict["p1num"] = int(p1num[index]) # 平台借款人(人) temp_dict["fuload"] = float(fuload[index]) # 平台满标速度(分钟) temp_dict["alltotal"] = float(alltotal[index]) # 平台累计贷款余额(万) temp_dict["capital"] = float(capital[index]) # 平台资金净流入(万) data_list.append(temp_dict) # 循环存入每个平台的信息 qdate = datetime.strftime(datetime.now() + timedelta(-1), "%Y-%m-%d") # 获取昨天日期 for msg_dict in data_list: models.WDTYInfo.objects.using("default").create( qdate=qdate, # 日期 name=msg_dict.get("name"), # 平台名称 total=msg_dict.get("total"), # 平台成交额(万) rate=msg_dict.get("rate"), # 平台综合利率(%) pnum=msg_dict.get("pnum"), # 平台投资人数(人) cycle=msg_dict.get("cycle"), # 平台借款周期(月) p1num=msg_dict.get("p1num"), # 平台借款人(人) fuload=msg_dict.get("fuload"), # 平台满标速度(分钟) alltotal=msg_dict.get("alltotal"), # 平台累计贷款余额(万) capital=msg_dict.get("capital") # 平台资金净流入(万) ) logger.info("%s网贷天眼数据已经更新!" % (qdate,)) return HttpResponse("网贷天眼数据填入完毕!")
def file_transfer_run(multi_task_detail_obj_id): """连上远程主机并传输文件""" import django import os django.setup() from web import models from django.utils.timezone import datetime from django.conf import settings # 获取批量任务详细信息对象 multi_task_detail_obj = models.MultiTaskDetail.objects.filter( id=multi_task_detail_obj_id).first() try: transport = paramiko.Transport( (multi_task_detail_obj.bind_host.host.ip_adr, multi_task_detail_obj.bind_host.host.port)) transport.connect( username=multi_task_detail_obj.bind_host.remote_user.username, password=multi_task_detail_obj.bind_host.remote_user.password, ) sftp = paramiko.SFTPClient.from_transport(transport) file_path = os.path.join(settings.MULTI_TASK_FILE_TRANSFER_DIR, multi_task_detail_obj.multi_task.content) sftp.put(file_path, f'{os.path.basename(file_path)}') transport.close() multi_task_detail_obj.result = "文件上传成功" multi_task_detail_obj.status = 1 # 修改状态为执行成功 end_time = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S") multi_task_detail_obj.end_time = end_time # 命令执行的终止时间 multi_task_detail_obj.save() except Exception as e: multi_task_detail_obj.result = e multi_task_detail_obj.status = 2 end_time = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S") multi_task_detail_obj.end_time = end_time multi_task_detail_obj.save()
def end_time(cls): field = fields.DateField( label="终止日期", widget=widgets.TextInput(attrs={ "class": "form-control date-picker", "id": "end_time", "value": datetime.strftime(datetime.now() - timedelta(1), "%Y-%m-%d"), "placeholder": "终止日期" }), error_messages={ "required": "日期不能为空!", "invalid": "请输入正确的日期格式!" } ) return field
def upload(request): if request.user.is_authenticated: s = request.user.username a = "" form = DocumentForm() today = datetime.strftime(datetime.now() - timedelta(0), '%Y-%m-%d') print(today) q = today.split("-") q1 = str(q[2]).split(" ") d = q[0] + "-" + q[1] + "-" + q[2] print(localtime(now()), "fassak") today = str(datetime.today()) q = today.split(" ") h = str(q[1]).split(":") h = h[0] + ":" + h[1] if request.method == 'POST': print(a, "upload") b = Document() b.userid = s b.task = request.POST.get('task') b.date = request.POST.get('date') b.time = request.POST.get('time') x = request.POST.get('time') b.save() return render(request, 'todo/upload.html', { 'form': form, 's': s, 'l': a, 'd': d, 'h': h }) else: form = DocumentForm() print("d", d) return render(request, 'todo/upload.html', { 'form': form, 's': s, 'l': a, 'd': d, 'h': h }) else: return HttpResponse("<h1>please login to continue</h1>")
def get_context(self): jianfang_total = JianFangInfo.objects.exclude(state=10).count() yinji_total = YinJiZhengGai.objects.count() yinji_wait = YinJiZhengGai.objects.filter(state=1).count() yinji_over = YinJiZhengGai.objects.filter(state=2).count() this_month = datetime.strftime(datetime.now(), '%Y-%m') yinji_this_month = YinJiZhengGai.objects.filter( date__startswith=this_month) yinji_this_month_total = yinji_this_month.count() state_list = [] yingji_state_list = [] for k, v in JIAN_STATE: if k == 0 or k == 10: continue count = JianFangInfo.objects.filter(state=k).count() state_list.append({'label': v, 'count': count, 'key': k}) for k, v in YINGJI_STATE: count = yinji_this_month.filter(state=k).count() yingji_state_list.append({'label': v, 'count': count}) dc = { 'jianfang_total': jianfang_total, 'name': 'hello', 'state_list': state_list, 'yinji': { 'total': yinji_total, 'state_list': [{ 'label': '待处理', 'count': yinji_wait, }, { 'label': '已处理', 'count': yinji_over }], 'this_month_total': yinji_this_month_total, 'this_month_state_list': yingji_state_list } } return dc
def job1(repeat=30): t = str(datetime.strftime(datetime.now(), '%H:%M')) t = t + ":00" print("t=", t) today = str(datetime.today()) q = today.split("-") q1 = str(q[2]).split(" ") d = q[0] + "-" + q[1] + "-" + q1[0] query = Document.objects.filter(date=d, time=t) print("date=", d, "time=", t, "query len=", len(query)) for b in query: msg = b.task mail = User.objects.filter(username=b.userid) mail = mail[0].email sub = "todo upGrad remainder" email = EmailMessage(sub, msg, to=[mail]) print("sending mail", msg, email) email.send() print("mail send")
def get_table_rows(request, row): """获取表格每一行数据""" """ {% for v in row.values %} <td>{{ v }}</td> {% endfor %} """ td_ele = "" detaile_jurisdiction_flag = True # 有详细信息查看权限 download_status = False # 是否有下载权限 # 循环用户的角色,看用户是否有角色具有下载权限 for role_obj in request.user.roles.all(): if role_obj.download_status: download_status = True break if not download_status: # 用户不具备下载权限则部分敏感信息进行打码 detaile_jurisdiction_flag = False # 用户没有一个角色在详细信息查看权限角色列表里面则将权限改为False for field, data in row.items(): # 循环每一行的数据 if isinstance(data, datetime): data = datetime.strftime(data, "%Y-%m-%d %H:%M:%S") if isinstance(data, date): data = date.strftime(data, "%Y-%m-%d") if not detaile_jurisdiction_flag: if field in ["姓名", "uname", "用户名", "un", "用户姓名", "被邀请人姓名"]: data = "%s%s" % (data[:1], "*" * len(data[1:])) if field in ["手机", "手机号", "mobile", "被邀请人手机号"]: real_data = re.findall("<a .*>(.*)</a>", data) # 如果有a标签则获取a标签包起来的数据 if len(real_data) == 0: data = "%s%s%s" % (data[0:3], "*" * 4, data[7:]) else: real_data = real_data[0] # a标签包起来的数据 # todo 希望做到只替换a标签包起来的数据 data = data.replace( real_data, "%s%s%s" % (real_data[0:3], "*" * 4, real_data[7:])) if field in ["身份证", "personid"]: data = "%s%s%s" % (data[0:5], "*" * 9, data[14:]) td_ele += "<td style='white-space:nowrap'>%s</td>" % data return mark_safe(td_ele)
def my_custom_sql(): with connection.cursor() as cursor: try: row = ("Time Report Run At " + str(datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M')) + ".","\n") row += ("This report was run for the following dates: " + str(start) + " through " + str(end) + ".", "\n") if form.cleaned_data['report_Type'] == '1': row += ("<th>Employee Name</th><th>Time Type</th><th>Total Hours Logged</th><th>Number of Time Entries</th>", "\n") else: row += ("Employee Name, ", " Time Type, ", " Total Hours Logged, "," Number of Time Entries ", "\n") cursor.execute("select concat(au.first_name, ' ', au.last_name), tt.timeType, CASE when tt.lunchin_time IS NULL AND tt.lunchout_time IS NULL THEN sum(TRUNCATE((timestampdiff(MINUTE, in_time, out_time)/60),2)) ELSE sum(TRUNCATE((timestampdiff(MINUTE, in_time, out_time)/60),2) - TRUNCATE((timestampdiff(MINUTE, tt.lunchin_time, tt.lunchout_time)/60),2)) END, count(timeType) FROM times_timekeep tt JOIN auth_user au ON au.id = tt.user_id WHERE tt.in_time BETWEEN DATE_ADD(%s, INTERVAL 6 HOUR) AND DATE_ADD(%s, INTERVAL 30 HOUR) AND tt.user_id LIKE %s GROUP BY 1, 2", [start, end, user_id]) if form2.cleaned_data['report_Type'] == '1': for rows in cursor.fetchall(): row += ("<td>" + str(rows[0]) + "</td>" + "<td>" + str(rows[1]) + "</td>" + "<td>" + str(rows[2]) + "</td>" + "<td>" + str(rows[3]) + "</td>", "\n") else: for rows in cursor.fetchall(): row += (rows[0],",", rows[1],",", rows[2],",", rows[3], "\n") row += ("\n",) row += ("The decimal is a percentage of an hour (ex .5 = 30minutes).",) row += ("Please press the back arrow in your browser to return to the application.",) except Exception as e: row += ("There was an error while processing the request." + "error: " + str(e),) finally: cursor.close() return row
def collect_job(self, name): job = self.server.get_job_info(name=name) try: last_success_build_num = job['lastSuccessfulBuild']['number'] except BaseException as error: last_success_build_num = None # print(last_success_build_num) try: last_build_num = job['lastBuild']['number'] except BaseException as error: return False # print(last_build_num) last_build_info = self.server.get_build_info(name, last_build_num) last_build_console = self.server.get_build_console_output( name, last_build_num) last_build_status = last_build_info['result'] if not last_build_status: last_build_status = "RUNNING" ts = last_build_info['timestamp'] sp = float(str(ts)[0:-3] + '.' + str(ts)[-3:]) last_build_time = datetime.strftime(datetime.fromtimestamp(sp), "%Y-%m-%d %H:%M:%S") return { 'app_name': name, 'build_status': last_build_status, 'last_build_time': last_build_time, 'build_console_output': last_build_console, 'last_success_build_num': last_success_build_num, 'last_build_num': last_build_num }
def interactive(self): print(action_show) # 程序启动画面 # 验证用户登录 count = 0 # 计数项 authenticate_status = False # 是否验证通过 user = None # 登录成功的用户对象 while count < 3: username = input("用户名:").strip() password = getpass.getpass("密码:").strip() user = authenticate(username=username, password=password) if user: authenticate_status = True break else: print( "\033[31;1mWrong Username or Password!Please try again!\033[0m" ) count += 1 else: logger.warning(f"用户{username}密码输错三次以上!") exit("\033[31;1mYou have tried too many times!\033[0m") if authenticate_status: # 登录成功 logger.info(f"用户{username}登录成功!") print("\033[32;1mWelcome KindFortressMachine\033[0m") error_message = None # 错误提示信息 # 展示用户可以选择的主机组 while True: subprocess.run("clear", shell=True) # 清屏 if error_message: # 有错误信息,则提示 print(error_message) print(f"用户[{username}]可使用主机组详情".center(30, "=")) print('%-6s %-7s %-13s' % ('选项', '主机组名', '主机数量')) print("%-8s %-7s %-13s" % (0, "未分组", user.bind_hosts.count())) for index, host_group in enumerate(user.host_groups.all()): print("%-8s %-7s %-13s" % (index + 1, host_group.name, host_group.bind_hosts.count())) print("".center(33, "=")) user_choice = input("Please chose one(q:exit):").strip() bind_host_objs = None # 用户要选择的组别下面的所有绑定账号的主机对象 if len(user_choice) == 0: error_message = None # 清空错误信息 continue if user_choice == "q": exit("Thanks for using it!") elif user_choice.isdigit(): # 用户输入的数字则为已分组的主机 user_choice = int(user_choice) host_groups_num = user.host_groups.count() # 用户所拥有的主机组数量 if user_choice > 0 and user_choice <= host_groups_num: bind_host_objs = user.host_groups.all()[ user_choice - 1].bind_hosts.all() elif user_choice == 0: # 说明用户选择的是未分组的机器 bind_host_objs = user.bind_hosts.all() else: error_message = "\033[31;1mWrong choice!\033[0m" continue else: error_message = "\033[31;1mWrong choice!\033[0m" continue # 展示用户可以选择的绑定账号的主机 error_message = None # 清空错误信息 while True: subprocess.run("clear", shell=True) # 清屏 if error_message: # 有错误信息,则提示 print(error_message) print(f"用户[{username}]可使用主机详情".center(60, "=")) print('%-6s %-7s %-10s %-7s %-7s' % ('选项', '主机名', '主机地址', '端口', '远程账户名')) for index, bind_host in enumerate(bind_host_objs): print("%-6s %-10s %-18s %-7s %-7s" % (index + 1, bind_host.host.host_name, bind_host.host.ip_adr, bind_host.host.port, bind_host.remote_user.username)) print("".center(63, "=")) user_choice = input("Please chose one(q:back):").strip() if len(user_choice) == 0: error_message = None # 清空错误信息 continue if user_choice == "q": error_message = None # 清空错误信息 break elif user_choice.isdigit(): user_choice = int(user_choice) if user_choice > 0 and user_choice <= len( bind_host_objs): error_message = None # 清空错误信息 select_bind_host = bind_host_objs[user_choice - 1] # 获取用户选中的主机 unique_id = str(uuid.uuid4()) # 生成一个唯一标识 temp_file_abs_path = os.path.join( settings.TEMP_FILES_DIR, unique_id) # 临时文件存放的绝对路径 current_date = datetime.strftime( datetime.now(), "%Y-%m-%d") # 获取当前日期 current_date_audit_log_path = os.path.join( settings.AUDIT_LOG_DIR, current_date) # 当前日期为名称的文件夹路径 # 创建或者确保以当前日期作为文件夹名称的文件夹存在 os.makedirs(current_date_audit_log_path, exist_ok=True) # 创建用户本次SSH操作记录的对象 session_obj = models.Session.objects.create( user=user, bind_host=select_bind_host, tag=str(temp_file_abs_path)) strace_log_path = os.path.join( current_date_audit_log_path, f"strace_{session_obj.id}.log") subprocess.Popen( f"bash {settings.SESSION_TRACKER_SCRIPT} {str(temp_file_abs_path)} {strace_log_path}", shell=True) # 连接远程主机 print( f"\033[32;1mGoing connect to {select_bind_host.host.ip_adr}\033[0m" ) logger.info( f"""用户{username}连接了{select_bind_host.host.ip_adr}, 使用远程账户{select_bind_host.remote_user.username}""" ) # 连接用户选择的主机 subprocess.run( "sshpass -p %s ssh %s@%s -o StrictHostKeyChecking=no -E %s" % (select_bind_host.remote_user.password, select_bind_host.remote_user.username, select_bind_host.host.ip_adr, temp_file_abs_path), shell=True) subprocess.run(f"rm -rf {temp_file_abs_path}", shell=True) # 将临时文件删除 logger.info(f"临时文件{temp_file_abs_path}删除成功!") else: error_message = "\033[31;1mWrong choice!\033[0m" continue else: error_message = "\033[31;1mWrong choice!\033[0m" continue
def _generate_xml(self): """ This were all is put together into an xml. """ namespaces = { # Default None: 'urn:iso:std:iso:20022:tech:xsd:pain.001.001.03', 'xsi': 'http://www.w3.org/2001/XMLSchema-instance' } document = Element('Document', nsmap=namespaces) if self._type is 'CT': main = SubElement(document, 'CstmrCdtTrfInitn') elif self._type is 'DD': main = SubElement(document, 'CstmrDrctDbtInitn') else: raise Exception('Unknown SepaDocument type, or type not set.') # Group Header grp_hdr = SubElement(main, 'GrpHdr') SubElement(grp_hdr, 'MsgId').text = str(self.message_identification) SubElement(grp_hdr, 'CreDtTm').text = datetime.strftime(datetime.now(), '%Y-%m-%dT%H:%I:%S') SubElement(grp_hdr, 'NbOfTxs').text = str(len(self._credit_transfers)) SubElement(grp_hdr, 'CtrlSum').text = str(self._header_control_sum) assert self.initiating_party initg_pty = SubElement(grp_hdr, 'InitgPty') SubElement(initg_pty, 'Nm').text = self.initiating_party.name # Credit Transfer Transactions Information # Rabobank wants only one transaction per payment info so we create multiple payment infos here. for transfer in self._credit_transfers: # PaymentInformation pmt_inf = SubElement(main, 'PmtInf') # PaymentInformationIdentification # PmtInfId SubElement(pmt_inf, 'PmtInfId').text = transfer.creditor_payment_id if self.category_purpose_code: cd = SubElement(pmt_inf, 'Cd') SubElement(cd, 'CtgyPurp').text = self.category_purpose_code # PaymentMethod SubElement(pmt_inf, 'PmtMtd').text = self._payment_method # BatchBooking [optional] # BtchBookg # NumberofTransactions SubElement(pmt_inf, 'NbOfTxs').text = "1" # ControlSum [optional] # CtrlSum # PaymentTypeInformation pmt_tp_inf = SubElement(pmt_inf, 'PmtTpInf') # InstructionPriority [optional] # InstrPrty # ServiceLevel svc_lvl = SubElement(pmt_tp_inf, 'SvcLvl') # Code SubElement(svc_lvl, 'Cd').text = 'SEPA' if self._local_instrument_code: # LocalInstrument lcl_instr = SubElement(pmt_inf, 'LclInstr') # Code SubElement(lcl_instr, 'Cd').text = self._local_instrument_code # Proprietary [otional] # Prtry # CategoryPurpose [optional # CtgyPurp # # - Cd Code # - Prtry Proprietary # RequestedExecutionDate SubElement(pmt_inf, 'ReqdExctnDt').text = datetime.strftime( datetime.now(), '%Y-%m-%d') # Debtor dbtr = SubElement(pmt_inf, 'Dbtr') # Name SubElement(dbtr, 'Nm').text = self.debtor.name # PostalAddress [optional] # PstlAdr # # - Country [optional] # - Ctry # # - AddressLine [optional] # - AdrLine # Identification [optional] # Id # DebtorAccount dbtr_acct = SubElement(pmt_inf, 'DbtrAcct') # Identification dbtr_id = SubElement(dbtr_acct, 'Id') # IBAN SubElement(dbtr_id, 'IBAN').text = self.debtor.iban # Currency SubElement(dbtr_acct, 'Ccy').text = self.currency # DebtorAgent dbtr_agt = SubElement(pmt_inf, 'DbtrAgt') # FinancialInstitutionIdentification fin_isnstn_id = SubElement(dbtr_agt, 'FinInstnId') # BIC SubElement(fin_isnstn_id, 'BIC').text = self.debtor.bic # UltimateDebtor [optional] # UltmtDbtr # - Name # - Nm # # - Identification # - Id # ChargeBearer SubElement(pmt_inf, 'ChrgBr').text = 'SLEV' # CTTransactionInformation cd_trf_tx_inf = SubElement(pmt_inf, 'CdtTrfTxInf') # PaymentIdentification pmt_id = SubElement(cd_trf_tx_inf, 'PmtId') # InstructionIdentification # InstrId [optional] # End to End Identification SubElement(pmt_id, 'EndToEndId').text = transfer.end_to_end_id # PaymentTypeInformation [optional] # PmtTpInf # ServiceLevel # SvcLvl [optional] # # - Code # - Cd # LocalInstrument [optional] # LclInstrm # # - Code # - Cd # # - Proprietary # - Prtry # CategoryPurpose [optional] # CtgyPurp # # - Code # - Cd # Amount amt = SubElement(cd_trf_tx_inf, 'Amt') # InstructedAmount instd_amt = SubElement(amt, 'InstdAmt', {'Ccy': transfer.currency}) instd_amt.text = str(transfer.amount) # Charge Bearer [optional] # ChrgBr # UltimateDebtor [optional] # UltmtDbtr # - Name # - Nm # # - Identification # - Id # Creditor Agent cdtr_agt = SubElement(cd_trf_tx_inf, 'CdtrAgt') # FinancialInstitutionIdentification fin_inst_id = SubElement(cdtr_agt, 'FinInstnId') # BIC bic = SubElement(fin_inst_id, 'BIC') bic.text = transfer.creditor.bic # Creditor cdrt = SubElement(cd_trf_tx_inf, 'Cdtr') # Name SubElement(cdrt, 'Nm').text = transfer.creditor.name # PostalAddress [optional] # PstlAdr # # - Country [optional] # - Ctry # # - AddressLine [optional] # - AdrLine # Identification [optional] # Id # Creditor Account cdtr_acct = SubElement(cd_trf_tx_inf, 'CdtrAcct') # Id cdtr_id = SubElement(cdtr_acct, 'Id') # IBAN SubElement(cdtr_id, 'IBAN').text = transfer.creditor.iban # Currency [optional] # Ccy # Name [optional] # Nm # UltimateDebtor [optional] # UltmtDbtr # - Name # - Nm # # - Identification # - Id # Purpose [optional] # Purp # # - Code # - Cd # RemittanceInformation rmt_inf = SubElement(cd_trf_tx_inf, 'RmtInf') # Unstructured if transfer.remittance_information: SubElement(rmt_inf, 'Ustrd').text = transfer.remittance_information # Structured (optional) # # - CreditorReferenceInformation (optional) # # - - Type # - - Tp # # - - - CodeOrProprietary # - - - CdOrPrtry # - - - - Code # - - - Issuer # - - Reference return document
def generate_result_as_excel(request, quiz, quizTaker, responses): output = io.BytesIO() workbook = xlsxwriter.Workbook(output) worksheet = workbook.add_worksheet(name="Result") worksheet.set_column("A:A", 20) worksheet.set_column("B:B", 60) worksheet.set_column("D:H", 20) worksheet.set_column("J:K", 30) bold_format = workbook.add_format({"bold": True, "text_wrap": True,}) bold_y_format = workbook.add_format({"bold": True, "top": 1, "bottom": 1,}) green_format = workbook.add_format( {"bg_color": "#C6EFCE", "font_color": "#006100", "text_wrap": "true",} ) green_y_format = workbook.add_format( { "bg_color": "#C6EFCE", "font_color": "#006100", "text_wrap": "true", "top": 1, "bottom": 1, } ) green_bold_format = workbook.add_format( { "bold": True, "bg_color": "#C6EFCE", "font_color": "#006100", "text_wrap": "true", } ) red_format = workbook.add_format( {"bg_color": "#FFC7CE", "font_color": "#9C0006", "text_wrap": True,} ) red_y_format = workbook.add_format( { "bg_color": "#FFC7CE", "font_color": "#9C0006", "text_wrap": "true", "top": 1, "bottom": 1, } ) red_bold_format = workbook.add_format( { "bold": True, "bg_color": "#FFC7CE", "font_color": "#9C0006", "text_wrap": "true", } ) blue_format = workbook.add_format( {"bg_color": "#b4daff", "font_color": "#003171", "text_wrap": True,} ) blue_y_format = workbook.add_format( { "bg_color": "#b4daff", "font_color": "#003171", "text_wrap": "true", "top": 1, "bottom": 1, } ) blue_bold_format = workbook.add_format( { "bold": True, "bg_color": "#b4daff", "font_color": "#003171", "text_wrap": "true", } ) rNo = 1 worksheet.merge_range(f"A{rNo}:B{rNo}", request.user.full_name, bold_format) rNo += 1 worksheet.merge_range( f"A{rNo}:B{rNo}", f"{request.user.email.upper()}", bold_format ) rNo += 1 worksheet.merge_range(f"A{rNo}:B{rNo}", f"Quiz: {quiz.title}", bold_format) rNo += 1 worksheet.merge_range(f"A{rNo}:B{rNo}", "") rNo += 1 descLength = len(quiz.description.split("\n")) worksheet.merge_range( f"A{rNo}:B{rNo + descLength - 1}", f"{quiz.description}", bold_format ) rNo += descLength + 1 extra = json.loads(quizTaker.extra) for key, value in extra.items(): worksheet.write(f"A{rNo}", f"{key}:", bold_format) worksheet.write(f"B{rNo}", f"{value}", bold_format) rNo += 1 rNo += 1 started = quizTaker.started.astimezone(tz=pytz.timezone(request.user.timeZone)) try: started = datetime.strftime(started, "%Y-%m-%d %-I:%M:%S %p") except ValueError: started = datetime.strftime(started, "%Y-%m-%d %#I:%M:%S %p") worksheet.write(f"A{rNo}", "Started At:", bold_format) worksheet.write(f"B{rNo}", f"{started}", bold_format) rNo += 1 ended = quizTaker.completed.astimezone(tz=pytz.timezone(request.user.timeZone)) try: ended = datetime.strftime(ended, "%Y-%m-%d %-I:%M:%S %p") except ValueError: ended = datetime.strftime(ended, "%Y-%m-%d %#I:%M:%S %p") worksheet.write(f"A{rNo}", "Submitted At:", bold_format) worksheet.write(f"B{rNo}", f"{ended}", bold_format) rNo += 2 total_marks = sum([r.question.marks for r in responses]) marks_obtained = sum([q.marks for q in responses]) worksheet.merge_range(f"A{rNo}:B{rNo}", f"Total Marks: {total_marks}", bold_format) rNo += 1 worksheet.merge_range( f"A{rNo}:B{rNo}", f"Marks Obtained: {marks_obtained}", bold_format ) rNo += 2 if 100 * marks_obtained / total_marks > 33: worksheet.merge_range(f"A{rNo}:B{rNo}", f"Status: Passed", green_bold_format) else: worksheet.merge_range(f"A{rNo}:B{rNo}", f"Status: Failed", red_bold_format) rNo += 2 worksheet.write(f"A{rNo}", "Que No.", bold_y_format) worksheet.write(f"B{rNo}", "Question Statement", bold_y_format) worksheet.write(f"C{rNo}", "", bold_y_format) worksheet.write(f"D{rNo}", "Option 1", bold_y_format) worksheet.write(f"E{rNo}", "Option 2", bold_y_format) worksheet.write(f"F{rNo}", "Option 3", bold_y_format) worksheet.write(f"G{rNo}", "Option 4", bold_y_format) worksheet.write(f"H{rNo}", "Option 5", bold_y_format) worksheet.write(f"I{rNo}", "", bold_y_format) worksheet.write(f"J{rNo}", "Correct Answer", bold_y_format) worksheet.write(f"K{rNo}", "Your Answer", bold_y_format) worksheet.write(f"L{rNo}", "Is Correct", bold_y_format) worksheet.write(f"M{rNo}", "Marks", bold_y_format) for i, response in enumerate(responses): rNo += 1 if response.isCorrect: format = green_y_format else: if response.answer == "": format = blue_y_format else: format = red_y_format worksheet.write(f"A{rNo}", i + 1, format) worksheet.write(f"B{rNo}", f"{response.question.title}", format) worksheet.write(f"C{rNo}", "", format) worksheet.write(f"D{rNo}", f"{response.question.choice_1}", format) worksheet.write(f"E{rNo}", f"{response.question.choice_2}", format) worksheet.write(f"F{rNo}", f"{response.question.choice_3}", format) worksheet.write(f"G{rNo}", f"{response.question.choice_4}", format) worksheet.write(f"H{rNo}", f"{response.question.choice_5}", format) worksheet.write(f"I{rNo}", "", format) worksheet.write(f"J{rNo}", f"{response.question.correct}", format) worksheet.write(f"K{rNo}", f"{response.answer}", format) worksheet.write(f"L{rNo}", f"{response.isCorrect}", format) worksheet.write(f"M{rNo}", response.marks, format) workbook.close() output.seek(0) return output
def get_form(self, form_class=None): form = super(AddWorkoutView, self).get_form(form_class) form.fields['date'].input_formats = ['%d/%m/%Y'] form.fields['date'].initial = datetime.strftime(datetime.today(), '%d/%m/%Y') return form
def timeEntry_view(request, *args, **kwargs): current = getTimeKeepFromKeys(request.user, 'Standard Time', timezone.now()) if current == "MultiObj": return HttpResponseServerError( "Can't have more than one time entry per day, Please Contact Management/Supervisors. /n Hit the back button to go back" ) if request.method == 'POST': currentReqForm = timeForm(request.POST, user=request.user) if currentReqForm.is_valid(): #currentReqForm.save() if 'manual' in request.POST and currentReqForm.is_valid(): if 'in_time' in currentReqForm.changed_data: in_time = currentReqForm.cleaned_data['in_time'] inCurrent = getTimeKeepFromKeys(request.user, 'Standard Time', in_time, True) inCurrent.in_time = in_time inCurrent.dateTimeEntered = in_time #inCurrent.week_number = in_time.isocalendar().week inCurrent.clocked_in = True inCurrent.is_Manual = True leave_time = in_time + timedelta(hours=8) messages.success( request, "you have successfully clocked in, clock out time must be %s" % datetime.strftime(leave_time, '%d/%m/%Y %H:%M')) inCurrent.save() if 'lunchin_time' in currentReqForm.changed_data: lunchin_time = currentReqForm.cleaned_data['lunchin_time'] inCurrent = getTimeKeepFromKeys(request.user, 'Standard Time', lunchin_time, True) inCurrent.lunchin_time = lunchin_time inCurrent.dateTimeEntered = lunchin_time #inCurrent.week_number = lunchin_time.isocalendar().week inCurrent.clocked_in = False inCurrent.is_Manual = True messages.success( request, "you have successfully clocked in for lunch") inCurrent.save() if 'lunchout_time' in currentReqForm.changed_data: lunchout_time = currentReqForm.cleaned_data[ 'lunchout_time'] inCurrent = getTimeKeepFromKeys(request.user, 'Standard Time', lunchout_time, True) inCurrent.lunchout_time = lunchout_time inCurrent.dateTimeEntered = lunchout_time #inCurrent.week_number = lunchout_time.isocalendar().week inCurrent.clocked_in = True inCurrent.is_Manual = True messages.success( request, "you have successfully clocked out for lunch") inCurrent.save() if 'out_time' in currentReqForm.changed_data: out_time = currentReqForm.cleaned_data['out_time'] inCurrent = getTimeKeepFromKeys(request.user, 'Standard Time', out_time, True) inCurrent.out_time = out_time inCurrent.dateTimeEntered = out_time #inCurrent.week_number = out_time.isocalendar().week inCurrent.clocked_in = False inCurrent.is_Manual = True messages.success(request, "you have successfully clocked out") inCurrent.save() else: # Error area current = getTimeKeepFromKeys(request.user, 'Standard Time', timezone.now(), True) date = timezone.now() if 'autoIn' in request.POST or 'lunchIn' in request.POST or 'lunchOut' in request.POST or 'autoOut' in request.POST: if 'autoIn' in request.POST: current.in_time = date current.dateTimeEntered = date - timedelta(hours=6) current.clocked_in = True leave_time = current.in_time + timedelta(hours=2) messages.success( request, "you have successfully clocked in, clock out time must be %s" % datetime.strftime(leave_time, '%d/%m/%Y %H:%M')) print("autoin") current.save() elif 'lunchIn' in request.POST: current.lunchin_time = date current.dateTimeEntered = date - timedelta(hours=6) current.clocked_in = False messages.success(request, "you have successfully clocked in for lunch") current.save() elif 'lunchOut' in request.POST: current.lunchout_time = date current.dateTimeEntered = date - timedelta(hours=6) current.clocked_in = True messages.success( request, "you have successfully clocked out for lunch") current.save() elif 'autoOut' in request.POST: current.out_time = date current.dateTimeEntered = date - timedelta(hours=6) current.clocked_in = False messages.success(request, "you have successfully clocked out") current.save() if (current.out_time - current.in_time) > timedelta(hours=8): messages.success( request, "you have clocked in over eight hours, please talk to management to fix your time" ) #print("autoout") # else: # return render(request, 'timeEntry.html', {'form' : currentReqForm}) form = timeForm(instance=current, user=request.user) return render(request, 'timeEntry.html', {'form': form}) return render(request, 'timeEntry.html', {'form': currentReqForm}) else: if not current: current = timeKeep(user=request.user, dateTimeEntered=timezone.now().date()) form = timeForm(instance=current, user=request.user) return render(request, 'timeEntry.html', {'form': form})
def convert_datetime(cls, dt): return datetime.strftime(dt, '%Y-%m-%d %H:%M:%S.%f+00:00')
def convert_date(cls, d): return datetime.strftime(d, '%Y-%m-%d')
def _generate_xml(self): """ This were all is put together into an xml. """ namespaces = { # Default None: 'urn:iso:std:iso:20022:tech:xsd:pain.001.001.03', 'xsi': 'http://www.w3.org/2001/XMLSchema-instance' } document = Element('Document', nsmap=namespaces) if self._type is 'CT': main = SubElement(document, 'CstmrCdtTrfInitn') elif self._type is 'DD': main = SubElement(document, 'CstmrDrctDbtInitn') else: raise Exception('Unknown SepaDocument type, or type not set.') # Group Header grp_hdr = SubElement(main, 'GrpHdr') SubElement(grp_hdr, 'MsgId').text = str(self.message_identification) SubElement(grp_hdr, 'CreDtTm').text = datetime.strftime(datetime.now(), '%Y-%m-%dT%H:%I:%S') SubElement(grp_hdr, 'NbOfTxs').text = str(len(self._credit_transfers)) SubElement(grp_hdr, 'CtrlSum').text = str(self._header_control_sum) assert self.initiating_party initg_pty = SubElement(grp_hdr, 'InitgPty') SubElement(initg_pty, 'Nm').text = self.initiating_party.name # Credit Transfer Transactions Information # Rabobank wants only one transaction per payment info so we create multiple payment infos here. for transfer in self._credit_transfers: # PaymentInformation pmt_inf = SubElement(main, 'PmtInf') # PaymentInformationIdentification # PmtInfId SubElement(pmt_inf, 'PmtInfId').text = transfer.creditor_payment_id if self.category_purpose_code: cd = SubElement(pmt_inf, 'Cd') SubElement(cd, 'CtgyPurp').text = self.category_purpose_code # PaymentMethod SubElement(pmt_inf, 'PmtMtd').text = self._payment_method # BatchBooking [optional] # BtchBookg # NumberofTransactions SubElement(pmt_inf, 'NbOfTxs').text = "1" # ControlSum [optional] # CtrlSum # PaymentTypeInformation pmt_tp_inf = SubElement(pmt_inf, 'PmtTpInf') # InstructionPriority [optional] # InstrPrty # ServiceLevel svc_lvl = SubElement(pmt_tp_inf, 'SvcLvl') # Code SubElement(svc_lvl, 'Cd').text = 'SEPA' if self._local_instrument_code: # LocalInstrument lcl_instr = SubElement(pmt_inf, 'LclInstr') # Code SubElement(lcl_instr, 'Cd').text = self._local_instrument_code # Proprietary [otional] # Prtry # CategoryPurpose [optional # CtgyPurp # # - Cd Code # - Prtry Proprietary # RequestedExecutionDate SubElement(pmt_inf, 'ReqdExctnDt').text = datetime.strftime( datetime.now(), '%Y-%m-%d') # Debtor dbtr = SubElement(pmt_inf, 'Dbtr') # Name SubElement(dbtr, 'Nm').text = self.debtor.name # PostalAddress [optional] # PstlAdr # # - Country [optional] # - Ctry # # - AddressLine [optional] # - AdrLine # Identification [optional] # Id # DebtorAccount dbtr_acct = SubElement(pmt_inf, 'DbtrAcct') # Identification dbtr_id = SubElement(dbtr_acct, 'Id') # IBAN SubElement(dbtr_id, 'IBAN').text = self.debtor.iban # Currency SubElement(dbtr_acct, 'Ccy').text = self.currency # DebtorAgent dbtr_agt = SubElement(pmt_inf, 'DbtrAgt') # FinancialInstitutionIdentification fin_isnstn_id = SubElement(dbtr_agt, 'FinInstnId') # BIC SubElement(fin_isnstn_id, 'BIC').text = self.debtor.bic # UltimateDebtor [optional] # UltmtDbtr # - Name # - Nm # # - Identification # - Id # ChargeBearer SubElement(pmt_inf, 'ChrgBr').text = 'SLEV' # CTTransactionInformation cd_trf_tx_inf = SubElement(pmt_inf, 'CdtTrfTxInf') # PaymentIdentification pmt_id = SubElement(cd_trf_tx_inf, 'PmtId') # InstructionIdentification # InstrId [optional] # End to End Identification SubElement(pmt_id, 'EndToEndId').text = transfer.end_to_end_id # PaymentTypeInformation [optional] # PmtTpInf # ServiceLevel # SvcLvl [optional] # # - Code # - Cd # LocalInstrument [optional] # LclInstrm # # - Code # - Cd # # - Proprietary # - Prtry # CategoryPurpose [optional] # CtgyPurp # # - Code # - Cd # Amount amt = SubElement(cd_trf_tx_inf, 'Amt') # InstructedAmount instd_amt = SubElement(amt, 'InstdAmt', {'Ccy': transfer.currency}) instd_amt.text = str(transfer.amount) # Charge Bearer [optional] # ChrgBr # UltimateDebtor [optional] # UltmtDbtr # - Name # - Nm # # - Identification # - Id # Creditor Agent cdtr_agt = SubElement(cd_trf_tx_inf, 'CdtrAgt') # FinancialInstitutionIdentification fin_inst_id = SubElement(cdtr_agt, 'FinInstnId') # BIC bic = SubElement(fin_inst_id, 'BIC') bic.text = transfer.creditor.bic # Creditor cdrt = SubElement(cd_trf_tx_inf, 'Cdtr') # Name SubElement(cdrt, 'Nm').text = transfer.creditor.name # PostalAddress [optional] # PstlAdr # # - Country [optional] # - Ctry # # - AddressLine [optional] # - AdrLine # Identification [optional] # Id # Creditor Account cdtr_acct = SubElement(cd_trf_tx_inf, 'CdtrAcct') # Id cdtr_id = SubElement(cdtr_acct, 'Id') # IBAN SubElement(cdtr_id, 'IBAN').text = transfer.creditor.iban # Currency [optional] # Ccy # Name [optional] # Nm # UltimateDebtor [optional] # UltmtDbtr # - Name # - Nm # # - Identification # - Id # Purpose [optional] # Purp # # - Code # - Cd # RemittanceInformation rmt_inf = SubElement(cd_trf_tx_inf, 'RmtInf') # Unstructured if transfer.remittance_information: SubElement(rmt_inf, 'Ustrd').text = transfer.remittance_information # Structured (optional) # # - CreditorReferenceInformation (optional) # # - - Type # - - Tp # # - - - CodeOrProprietary # - - - CdOrPrtry # - - - - Code # - - - Issuer # - - Reference return document
def daily_storage(self): """ 日报数据存储 :return: 无返回值 """ qdate = datetime.strftime(now() - timedelta(days=1), "%Y-%m-%d") # 获取昨天日期 for sql_obj in automatic_models.SQLRecord.objects.filter(usage=2).all(): # 获取日报相关的所有SQL记录 try: ret = utils.get_info_list("rz", sql_obj.content.format(qdate=qdate)) setattr(self, sql_obj.nick_name, ret) except Exception as e: logger.warning("%s信息查询出错!出错信息如下\n%s" % (sql_obj.nick_name, e)) logger.info("%s信息查询完毕!" % sql_obj.nick_name) with transaction.atomic(): # 增加基础数据信息 models.BaseInfo.objects.using("default").create( qdate=qdate, # 日期 zhu_r=getattr(self, "zhu_info")[0].get("zhu_r") or None, # 注册人数 sm_r=getattr(self, "sm_info")[0].get("sm_r") or None, # 实名人数 sc_r=getattr(self, "sc_info")[0].get("sc_r") or None, # 首充人数 xztz_r=getattr(self, "xztz_info")[0].get("xztz_r") or None, # 新增投资人数 xztz_j=getattr(self, "xztz_info")[0].get("xztz_j") or None, # 新增投资金额 cz_r=getattr(self, "cz_info")[0].get("cz_r") or None, # 充值人数 cz_j=getattr(self, "cz_info")[0].get("cz_j") or None, # 充值金额 tx_r=getattr(self, "tx_info")[0].get("tx_r") or None, # 提现人数 tx_j=getattr(self, "tx_info")[0].get("tx_j") or None, # 提现金额 tz_r=getattr(self, "tz_info")[0].get("tz_r") or None, # 投资人数 tz_j=getattr(self, "tz_info")[0].get("tz_j") or None, # 投资金额 tz_b=getattr(self, "tz_info")[0].get("tz_b") or None, # 投资笔数 tz_dl_r=getattr(self, "tz_dl_info")[0].get("tz_dl_r") or None, # 投资登录人数 hk_r=getattr(self, "hk_info")[0].get("hk_r") or None, # 回款人数 hk_j=getattr(self, "hk_info")[0].get("hk_j") or None, # 回款金额 zg_j=getattr(self, "balance_info")[0].get("zg_j") or None, # 站岗金额 zg_r=getattr(self, "balance_info")[0].get("zg_r") or None, # 站岗人数 zd_r=getattr(self, "zaidai_info")[0].get("zd_r") or None, # 在贷人数 zd_j=getattr(self, "zaidai_info")[0].get("zd_j") or None, # 在贷金额 xt_j=getattr(self, "xt_info")[0].get("xt_j") or None, # 续投金额 cz_tz=getattr(self, "cz_tz_info")[0].get("cz_tz") or None, # 充值并投资金额 ) logger.info("%s基础数据信息增加完毕!" % qdate) # 增加昨日推广数据信息 models.TgInfo.objects.using("default").create( qdate=qdate, # 日期 tg_zhu_r=getattr(self, "tg_info")[0].get("tg_zhu_r") or None, # 推广注册人数 tg_sm_r=getattr(self, "tg_info")[0].get("tg_sm_r") or None, # 推广实名人数 tg_sc_r=getattr(self, "tg_info")[0].get("tg_sc_r") or None, # 推广首充人数 tg_xztz_r=getattr(self, "tg_info")[0].get("tg_xztz_r") or None, # 推广新增人数 tg_xztz_j=getattr(self, "tg_info")[0].get("tg_xztz_j") or None # 推广新增金额 ) logger.info("%s推广数据信息增加完毕!" % qdate) # 增加运营数据信息 models.OperateInfo.objects.using("default").create( qdate=qdate, # 日期 xz_cz=getattr(self, "xz_cz_info")[0].get("xz_cz") or None, # 新增充值 hk_cz=getattr(self, "hk_cz_info")[0].get("hk_cz") or None, # 回款并充值 unhk_cz=getattr(self, "unhk_cz_info")[0].get("unhk_cz") or None, # 非回款充值 zj_ft_lv=getattr(self, "zj_ft_lv_info")[0].get("zj_ft_lv") or None, # 资金复投率 rs_ft_lv=getattr(self, "rs_ft_lv_info")[0].get("rs_ft_lv") or None # 人数复投率 ) logger.info("%s运营数据信息增加完毕!" % qdate) # 增加邀请数据信息 models.InviteInfo.objects.using("default").create( qdate=qdate, # 日期 invite_r=getattr(self, "invite_info")[0].get("invite_r") or None, # 邀请人数 invited_r=getattr(self, "invite_info")[0].get("invited_r") or None, # 被邀请人数 invited_st_r=getattr(self, "invite_info")[0].get("invited_st_r") or None, # 被邀请首投人数 invited_st_j=getattr(self, "invite_info")[0].get("invited_st_j") or None, # 被邀请首投金额 cash_f=getattr(self, "invite_info")[0].get("cash_f") or None, # 现金发放金额 # cash_l=invite_info.get("cash_l"), # 现金领取金额 # hb_f=invite_info.get("hb_f"), # 红包发放金额 # hb_s=invite_info.get("hb_s") # 红包使用金额 ) logger.info("%s邀请数据信息增加完毕!" % qdate) # 增加各端数据详情 geduan_rw = getattr(self, "geduan_rw") # 获取各端回款并提现数据 geduan_rw_dic = {} # 定义一个各端回款并提现字典 for i in geduan_rw: geduan_rw_dic[i.get("geduan")] = {"recover": i.get("recover"), "recover_withdraw": i.get("recover_withdraw")} geduan_account = getattr(self, "geduan_account") # 获取各端投资数据 geduan_account_dic = {} for i in geduan_account: geduan_account_dic[i.get("geduan")] = {"account": i.get("account")} geduan_xztz = getattr(self, "geduan_xztz") # 获取各端新增投资数据 geduan_xztz_dic = {} for i in geduan_xztz: geduan_xztz_dic[i.get("geduan")] = {"xztz_j": i.get("xztz_j")} geduan_withdraw = getattr(self, "geduan_withdraw") # 获取各端提现数据 geduan_withdraw_dic = {} for i in geduan_withdraw: geduan_withdraw_dic[i.get("geduan")] = {"withdraw": i.get("withdraw")} geduan_list = ["APP", "PC", "WAP"] # 各端列表 geduan_info_obj_list = [] for gd in geduan_list: geduan_info_obj_list.append(models.GeDuanInfo( qdate=qdate, geduan=gd, recover=geduan_rw_dic.get(gd, {"recover": 0}).get("recover") or None, recover_withdraw=geduan_rw_dic.get(gd, {"recover_withdraw": 0}).get("recover_withdraw") or None, account=geduan_account_dic.get(gd, {"account": 0}).get("account") or None, xztz_j=geduan_xztz_dic.get(gd, {"xztz_j": 0}).get("xztz_j") or None, withdraw=geduan_withdraw_dic.get(gd, {"withdraw": 0}).get("withdraw") or None )) models.GeDuanInfo.objects.using("default").bulk_create(geduan_info_obj_list) logger.info("%s各端数据详情增加完毕!" % qdate) # 增加时间段数据详情 time_slot_obj_list = [] for row in getattr(self, "timeslot_info"): time_slot_obj_list.append(models.TimeSlot( qdate=qdate, # 日期 timeslot=row.get("timeslot") or None, # 时间段 tz_r=row.get("tz_r") or None # 投资人数 )) models.TimeSlot.objects.using("default").bulk_create(time_slot_obj_list) logger.info("%s时间段数据详情增加完毕!" % qdate) # 增加其他数据详情 models.OtherInfo.objects.using("default").create( qdate=qdate, short_tz_r=getattr(self, "short_tz_info")[0].get("short_tz_r") or None, short_tz_j=getattr(self, "short_tz_info")[0].get("short_tz_j") or None, short_zd_j=getattr(self, "short_zd_info")[0].get("short_zd_j") or None, Rplan_account=getattr(self, "Rplan_tz_info")[0].get("Rplan_account") or None, Rplan_recover_account=getattr(self, "Rplan_zd_info")[0].get("Rplan_recover_account") or None, g_tz_j=getattr(self, "g_tz_info")[0].get("g_tz_j") or None, x_tz_j=getattr(self, "x_tz_info")[0].get("x_tz_j") or None, Rplan_xt=getattr(self, "Rplan_xt_info")[0].get("Rplan_xt") or None, unRplan_xt_hk_j=getattr(self, "unRplan_xt_hk_info")[0].get("unRplan_xt_hk_j") or None, ) logger.info("%s其他数据详情增加完毕!" % qdate) # 增加每日每人在贷详情 user_recover_account_obj_list = [] for row in getattr(self, "user_recover"): user_recover_account_obj_list.append(models.UserRecoverAccount( qdate=qdate, # 日期 uid=row.get("uid") or None, # 用户ID recover_account=row.get("recover_account") or None # 在贷金额 )) models.UserRecoverAccount.objects.using("default").bulk_create(user_recover_account_obj_list) logger.info("%s每日每人在贷详情增加完毕!" % qdate) # 增加EXCEL日报资产数据详情 daily_asset_info_obj_list = [] for row in getattr(self, "daily_qixian_info"): daily_asset_info_obj_list.append(models.AssetInfo( qdate=qdate, # 日期 asset_type="所有", # 资产类型 term=row.get("term") or None, # 期限类型 tz_r=row.get("tz_r") or None, # 投资人数 tz_j=row.get("tz_j") or None, # 投资金额 mb_ys=row.get("mb_ys") or None # 满标用时 )) for row in getattr(self, "daily_s_qixian_info"): daily_asset_info_obj_list.append(models.AssetInfo( qdate=qdate, # 日期 asset_type="散标", # 资产类型 term=row.get("term") or None, # 期限类型 tz_r=row.get("tz_r") or None, # 投资人数 tz_j=row.get("tz_j") or None, # 投资金额 )) for row in getattr(self, "daily_r_qixian_info"): daily_asset_info_obj_list.append(models.AssetInfo( qdate=qdate, # 日期 asset_type="R计划", # 资产类型 term=row.get("term") or None, # 期限类型 tz_r=row.get("tz_r") or None, # 投资人数 tz_j=row.get("tz_j") or None, # 投资金额 )) models.AssetInfo.objects.using("default").bulk_create(daily_asset_info_obj_list) logger.info("%sEXCEL日报资产数据详情增加完毕!" % qdate) # 增加EXCEL日报提现分类数据详情 daily_withdraw_classify_obj_list = [] for row in getattr(self, "daily_withdraw_section"): daily_withdraw_classify_obj_list.append(models.WithdrawClassify( qdate=qdate, # 日期 withdraw_type="提现区间", # 提现类型 term=row.get("term") or None, # 提现分类 tx_r=row.get("tx_r") or None, # 提现人数 tx_j=row.get("tx_j") or None, # 提现金额 )) # 获取累计提现投资时间间隔数据 for row in getattr(self, "daily_withdraw_investment_interval"): daily_withdraw_classify_obj_list.append(models.WithdrawClassify( qdate=qdate, # 日期 withdraw_type="投资时间间隔", # 提现类型 term=row.get("term") or None, # 提现分类 tx_r=row.get("tx_r") or None, # 提现人数 tx_j=row.get("tx_j") or None, # 提现金额 )) # 获取累计提现投资次数数据 for row in getattr(self, "daily_withdraw_investment_times"): daily_withdraw_classify_obj_list.append(models.WithdrawClassify( qdate=qdate, # 日期 withdraw_type="投资次数", # 提现类型 term=row.get("term") or None, # 提现分类 tx_r=row.get("tx_r") or None, # 提现人数 tx_j=row.get("tx_j") or None, # 提现金额 )) models.WithdrawClassify.objects.using("default").bulk_create(daily_withdraw_classify_obj_list) logger.info("%sEXCEL日报提现分类数据详情增加完毕!" % qdate) # 增加EXCEL日报待收分类数据详情 daily_collect_classify_obj_list = [] for row in getattr(self, "daily_collect_section"): daily_collect_classify_obj_list.append(models.CollectClassify( qdate=qdate, # 日期 collect_type="待收区间", # 待收类型 term=row.get("term") or None, # 待收分类 collect_r=row.get("collect_r") or None, # 待收人数 collect_j=row.get("collect_j") or None, # 待收金额 )) # 获取待收投资时间间隔数据 for row in getattr(self, "daily_collect_investment_interval"): daily_collect_classify_obj_list.append(models.CollectClassify( qdate=qdate, # 日期 collect_type="待收投资时间间隔", # 待收类型 term=row.get("term") or None, # 待收分类 collect_r=row.get("collect_r") or None, # 待收人数 collect_j=row.get("collect_j") or None, # 待收金额 )) # 获取待收投资次数数据 for row in getattr(self, "daily_collect_investment_times"): daily_collect_classify_obj_list.append(models.CollectClassify( qdate=qdate, # 日期 collect_type="待收投资次数", # 待收类型 term=row.get("term") or None, # 待收分类 collect_r=row.get("collect_r") or None, # 待收人数 collect_j=row.get("collect_j") or None, # 待收金额 )) models.CollectClassify.objects.using("default").bulk_create(daily_collect_classify_obj_list) logger.info("%sEXCEL日报待收分类数据详情增加完毕!" % qdate) # 增加日报专属客服复投数据 re_casting_obj_list = [] # 获取专属客服复投数据 for row in getattr(self, "re_casting_info"): re_casting_obj_list.append(models.ReCasting( qdate=qdate, # 日期 kefuname=row.get("kefuname") or None, # 客服姓名 ft_r=row.get("ft_r") or None, # 首投后复投人数 st_r=row.get("st_r") or None, # 首投人数 ft_lv=row.get("ft_lv") or None, # 复投率 ft_j=row.get("ft_j") or None, # 复投金额 day_t_j=row.get("day_t_j") or None, # 当日投资金额 month_t_j=row.get("month_t_j") or None, # 当月投资金额 one_month_ft_r=row.get("one_month_ft_r") or None, # 本月首投后复投人数 one_month_st_r=row.get("one_month_st_r") or None, # 本月首投人数 one_month_ft_lv=row.get("one_month_ft_lv") or None, # 本月首投用户复投率 one_month_ft_j=row.get("one_month_ft_j") or None, # 本月首投用户复投金额 two_month_ft_r=row.get("two_month_ft_r") or None, # 前两月首投后复投人数 two_month_st_r=row.get("two_month_st_r") or None, # 前两月首投人数 two_month_ft_lv=row.get("two_month_ft_lv") or None, # 前两月首投用户复投率 two_month_ft_j=row.get("two_month_ft_j") or None, # 前两月首投用户复投金额 )) models.ReCasting.objects.using("default").bulk_create(re_casting_obj_list) logger.info("%sEXCEL日报专属客服复投数据详情增加完毕!" % qdate) # 增加日报VIP客服流失数据 loss_rate_obj_list = [] # 获取VIP客服流失数据 for row in getattr(self, "daily_loss_rate_info"): loss_rate_obj_list.append(models.LossRate( qdate=qdate, # 日期 kefuname=row.get("kefuname") or None, # 客服姓名 loss_num=row.get("loss_num") or None, # 流失用户 exist_num=row.get("exist_num") or None, # 在投用户 day_invest=row.get("day_invest") or None, # 当日投资金额 month_withdraw=row.get("month_withdraw") or None, # 当月提现金额 month_invest=row.get("month_invest") or None, # 当月投资金额 recall_num=row.get("recall_num") or None, # 当月召回人数 )) models.LossRate.objects.using("default").bulk_create(loss_rate_obj_list) logger.info("%sEXCEL日报VIP客服流失数据详情增加完毕!" % qdate) logger.info("%s日报所需数据已经更新!" % (qdate,))