def fetch(self): # given a ccn, a cellphone number and a studentname #print "running?" info_list, has_waitlist = _find_info(self.ccn) current_enroll, enroll_limit, current_waitlist, waitlist_limit = -1, -1, -1, -1 all_full = False if has_waitlist: # if this class has waitlist if len(info_list) == 4: current_enroll, enroll_limit, current_waitlist, waitlist_limit = info_list elif len(info_list) == 2: current_waitlist, waitlist_limit = info_list elif len(info_list) == 0: all_full = True else: if len(info_list) == 4: current_enroll, enroll_limit, current_waitlist, waitlist_limit = info_list elif len(info_list) == 2: current_enroll, enroll_limit = info_list elif len(info_list) == 0: all_full = True #print current_enroll, enroll_limit, current_waitlist, waitlist_limit, all_full, has_waitlist is_different, different_list = self.update(current_enroll, enroll_limit, current_waitlist, waitlist_limit, all_full, has_waitlist) if is_different: msg = "Change in course %d:\n%s" % (self.ccn, '; '.join(different_list) + '.') if self.user_profile.is_phone_set: cell_mail = '%s@%s' % (self.user_profile.cellphone, self.user_profile.cell_mail) send_message(toaddrs=cell_mail, msg=msg) if self.user_profile.is_email_set: send_email(toaddrs=self.user_profile.email, title="Status change of course with CCN %s" % self.ccn, msg=msg)
def undone_orders_notice(): undone_orders = [] for x in OrderBase().get_undone_orders_before_yesterdey(): undone_orders.append(u"%s 于 %s 创建的订单未结" % (x.company.combine_name(), x.create_time.strftime('%Y-%m-%d %H:%M:%S'))) if undone_orders: content = u",\n".join(undone_orders) send_email('*****@*****.**', u'共「%s」单订单未结:' % len(undone_orders), content) from www.weixin.interface import WeixinBase from www.account.interface import ExternalTokenBase persons = [] persons.append('541798fc416311e5a8ba00163e001bb1') # 李聪 persons.append('de918ec6dfb911e5bb1d00163e001bb1') # 刘磊 for person in persons: to_user_openid = ExternalTokenBase().get_weixin_openid_by_user_id(person) WeixinBase().send_todo_list_template_msg( to_user_openid, u'瓜娃子,单子又没结完', u'结束当日订单', u'高', u"搞紧哈,下次莫忘咯" )
def main(limit): """ /usr/bin/tail -n 500000 /var/log/nginx/www.log | grep 61.140.150.163 | awk -F"HTTP" {'print $1'} | awk -F"\"" {'print $2'}| sort |uniq -c |sort -rn |awk '{ if($1>1) print count $1 " url "$2" "$3}' """ t1 = time.time() cmd_www = """/usr/bin/tail -n 500000 /var/log/nginx/www.log | grep -v 127.0.0.1 | awk -F"-" {'print $1'} | sort |uniq -c |sort -rn |awk '{ if($1>%s) print "count " $1 " ip "$2 }' """ % limit content_www = commands.getoutput(cmd_www) t2 = time.time() content = u'www.log info is:\n%s \n\n' % (content_www,) time_content = u'shell run time:%.1f second' % (t2 - t1, ) if check_content(content_www): file_name = '%s/../scripts/crontab/last_analyze_log.txt' % settings.SITE_ROOT try: f = open(file_name, 'r') file_content = f.read() f.close() except: file_content = '' if content != file_content: send_email(emails=settings.NOTIFICATION_EMAIL, title=u'frequent ip of nginx log from %s' % settings.SERVER_NAME, content=content + time_content, type="text") f = open(file_name, 'w') f.write(content) f.close() print 'ok'
def mutate(root, info, email, company_id): company = CompanyModel.find_by_id(company_id) if not company: raise Exception("company not found") user = User.find_by_email(email) if user: if user.company: raise Exception("user already belongs to a company") msg = f"We would like you to join our company '{company.name}'.\n" \ f"Please accept thought this link </>" send_email(email, msg) # TODO send invitation return AddMember(ok=True) # TODO create a url for sign up msg = f"We would like you to join our company '{company.name}'.\n" \ f"Please sign up to this link </>" send_email(email, msg) return AddMember(ok=True)
def main(limit): """ /usr/bin/tail -n 500000 /var/log/nginx/www_xcqifu.log | grep 61.140.150.163 | awk -F"HTTP" {'print $1'} | awk -F"\"" {'print $2'}| sort |uniq -c |sort -rn |awk '{ if($1>1) print count $1 " url "$2" "$3}' """ t1 = time.time() cmd_www = """/usr/bin/tail -n 500000 /var/log/nginx/www_xcqifu.log | grep -v 127.0.0.1 | awk -F"-" {'print $1'} | sort |uniq -c |sort -rn |awk '{ if($1>%s) print "count " $1 " ip "$2 }' """ % limit content_www = commands.getoutput(cmd_www) t2 = time.time() content = u'www_xcqifu.log info is:\n%s \n\n' % (content_www,) time_content = u'shell run time:%.1f second' % (t2 - t1, ) if check_content(content_www): file_name = '%s/../scripts/crontab/last_www_xcqifu_analyze_log.txt' % settings.SITE_ROOT try: f = open(file_name, 'r') file_content = f.read() f.close() except: file_content = '' if content != file_content: send_email(emails=settings.NOTIFICATION_EMAIL, title=u'frequent ip of nginx log from %s' % settings.SERVER_NAME, content=content + time_content, type="text") f = open(file_name, 'w') f.write(content) f.close() print 'ok'
def process_exception(self, request, exception): if type(exception) == Http404: return title = u'%s error in %s' % (settings.SERVER_NAME, request.get_full_path()) content = debug.get_debug_detail(exception) if not settings.LOCAL_FLAG: utils.send_email(settings.NOTIFICATION_EMAIL, title, content)
def post(self): try: data = request.get_json(force=True) except BadRequest: return (bad_request, 400, headers) try: validator = validate.Email() validator(data["email"]) except ValidationError: unprocessable_entity["error_list"]["email"] = "Not an valid email!" return (unprocessable_entity, 422, headers) # getting the user. Assuming the user exists. Case of user not existing is checked below try: user = g.session.query(g.Base.classes.users).filter( g.Base.classes.users.email == data["email"]).one() except NoResultFound: # *If no email is found with that address then you return 200 and send the email either way say # *Your confirmation message displayed on the web page would simply say “An email has been sent to (provided email address) with further instructions.” return ({"email": data["email"]}, 200, headers) except Exception as err: print(type(err)) print(err) return (internal_server_error, 500, headers) try: # *create reset password token and send email if user: user.reset_password_token = secrets.token_urlsafe(15) user.reset_password_sent_at = datetime.now(), user.auth_token = secrets.token_urlsafe(25) else: return (not_found, 404, headers) except Exception as err: print(type(err)) print(err) return (internal_server_error, 500, headers) # error handling for mail send try: f = open("common/reset_password.html", 'r') body = Template(f.read()) f.close() body = body.render(reset_password_token=user.reset_password_token) send_email(subject="SpartaHack Password Reset", recipient=data["email"], body=body) return ({ "status": "Reset password token set at " + data["email"] }, 200, headers) except Exception as err: print(type(err)) print(err) internal_server_error["error_list"][ "error"] = "Password reset token created but error in sending email" return (internal_server_error, 500, headers)
def social_probation(tracked_user): """ TODO: Docstring """ subject = "Scholarship: Social Probation" message = "You have been placed on social probation" +\ " for failing to complete study hours." scholarship = User.objects.filter(groups__name='Scholarship Chair') if not scholarship.exists(): return scholarship_chair = scholarship.first() send_email( subject=subject, body=message, to_emails=[tracked_user.user.email], cc_emails=[scholarship_chair.email, settings.EC_EMAIL], )
def study_hours_untracked(tracked_user): """ TODO: Docstring """ subject = "Scholarship: Study Hours" message = "Based on your academic performance," +\ " you are no longer required to report study hours." scholarship = User.objects.filter(groups__name='Scholarship Chair') if not scholarship.exists(): return scholarship_chair = scholarship.first() send_email( subject=subject, body=message, to_emails=[tracked_user.user.email], cc_emails=[scholarship_chair.email], )
def summons_requested(summons_request_count): """ Get a message for a summons request. """ subject = 'Standards Board: New Summons Request(s) Submitted' message = ( str(summons_request_count) + ' new summons request(s) have been submitted for your approval. ' + 'You may view details on the request and approve/deny it at: ' + 'https://sigmapigammaiota.org/secure/standards/summons/requests/') fourth = User.objects.get(groups__name='4th Counselor') send_email( subject=subject, body=message, to_emails=[fourth.email], cc_emails=[], )
def save(self, account, user): try: account, action = self.form_action(account, user) except errors.Error as e: error_message = str(e) self.add_error(None, error_message) raise if self.cleaned_data.get('send_email', False): send_email( to=[account.user.email], subject_template=self.email_subject_template, body_template=self.email_body_template, context={ "account": account, "action": action, } )
def main(): warn_list = [] for item in WORKER_CONFIG: count = get_delay_count(item['name']) print u'---%s----%s----' % (item['name'], count) if count > item.get('limit'): item['count'] = count warn_list.append(item) if warn_list: title = u'%s主机 worker积压警告' % (settings.SERVER_NAME, ) content = u'' for item in warn_list: content += u'%(name)s:积压任务数%(count)s, 警戒值为%(limit)s\n' % item send_email(emails=settings.NOTIFICATION_EMAIL, title=title, content=content, type="text") print 'ok'
def post(self, request): print(request.data) html = render_to_string( 'cupon.html', { 'name': '{} {}'.format(request.data.get('name', ''), request.data.get('lastName', '')) }) EmailLog.objects.create(email=request.data.get('email'), name=request.data.get('name'), lastName=request.data.get('lastName')) send_email('¡Xtistore - Obten tu descuento!', html, request.data.get('email')) return Response(status=status.HTTP_200_OK)
def scholarship_content_submitted(): """ TODO: Docstring """ subject = "Scholarship: Content Submitted for Approval" message = ("Content has been submitted to " + "the Scholarship module for your approval. " + "You may view and approve/deny " + "this content at" + "https://sigmapigammaiota.org/secure/scholarship/approve/") scholarship = User.objects.filter(groups__name='Scholarship Chair') if not scholarship.exists(): return scholarship_chair = scholarship.first() send_email( subject=subject, body=message, to_emails=[scholarship_chair.email], cc_emails=[], )
def fetch(self): url = self.url if getsize(url) > MAXIMUM_SIZE: return new_hash = gethash(url) if not self.hash_data: self.hash_data = new_hash self.save() else: if new_hash != self.hash_data: msg = "There has been a change of status in your monitoring course page %s (%s)." % (self.shortname, self.url) print self.user_profile if self.user_profile.is_phone_set: cell_mail = '%s@%s' % (self.user_profile.cellphone, self.user_profile.cell_mail) send_message(toaddrs=cell_mail, msg=msg[:100]+'...') if self.user_profile.is_email_set: send_email(toaddrs=self.user_profile.email, title="Status change of course page %s" % self.shortname, msg=msg) self.hash_data = new_hash self.save()
def summons_request_denied(summons_request): """ Get a message for a summons request denial. """ subject = 'Standards Board: Summons Request Denied' message = ( 'Your request to summons ' + summons_request.summonee.first_name + ' ' + summons_request.summonee.last_name + ' has been denied. If you want more details, ' + 'please speak with the Fourth Counselor.' ) fourth = User.objects.get(groups__name='4th Counselor') send_email( subject=subject, body=message, to_emails=[summons_request.summoner.email], cc_emails=[fourth.email], )
def _send_booking_notification_emails(self, subject, booking_id, is_user, is_created_by, update): booking = Booking.objects.filter(id=booking_id).select_related( 'course__school', 'course__type', 'created_by', 'user').first() if is_created_by and not update: ctx = dict(school=booking.course.school.name, course=booking.course.type.name) send_email(subject, booking.created_by.email, 'booking_confirm', ctx) if is_user and not update: ctx = dict(school=booking.course.school.name, course=booking.course.type.name, user_first_name=booking.created_by.first_name, user_last_name=booking.created_by.last_name, user_email=booking.created_by.email) send_email(subject, booking.school.created_by.email, 'booking_created', ctx) if is_user and update: ctx = dict(school=booking.course.school.name, course=booking.course.type.name, user_first_name=booking.created_by.first_name, user_last_name=booking.created_by.last_name, user_email=booking.created_by.email, booking_id=booking.id) send_email(subject, booking.school.created_by.email, 'booking_updated', ctx)
def study_hours_tracked(tracked_user): """ TODO: Docstring """ subject = "Scholarship: Study Hours" message = ( "Based on your academic performance, " + "you are now required to report " + str(tracked_user.number_of_hours) + " " + "study hours per week. " "Weeks begin on Mondays and " + "end at Sunday at midnight. " "You may report your study hours " + "at: https://sigmapigammaiota.org/secure/scholarship/study_hours/") scholarship = User.objects.filter(groups__name='Scholarship Chair') if not scholarship.exists(): return scholarship_chair = scholarship.first() send_email( subject=subject, body=message, to_emails=[tracked_user.user.email], cc_emails=[scholarship_chair.email], )
def main(): # 执行case testcases = settings.TESTCASES.split(" ") run_command = ["-n", "auto", "--dist=loaddir", '-s', "--html=./report/pytest.html", "--junitxml=./report/pytest.xml", "--resultlog=./report/result.txt", "--self-contained-html"] for testcase in testcases: run_command.append(testcase) if settings.CASE_TYPE: run_command.append("-m {}".format(settings.CASE_TYPE)) logger.info('pytest command: {}'.format(run_command)) pytest.main(run_command) if settings.RESOURCE_PREFIX != "local": # 如果有失败的用例循环几次 for i in range(0, 1): failed_cases = get_failed_case() print("start to rerun failed cases: {},rerun times:{}".format(failed_cases, i + 1)) if len(failed_cases) > 0: with tarfile.open("./report/report_failed_{}.tar".format(i + 1), "w:gz") as tar: tar.add("./report/", arcname=os.path.basename("./report")) for testcase in testcases: run_command.remove(testcase) run_command = run_command + failed_cases pytest.main(run_command) with tarfile.open("./report/report.tar", "w:gz") as tar: tar.add("./report/", arcname=os.path.basename("./report")) if settings.RESOURCE_PREFIX != "local": file_paths = ["./report/report.tar"] if os.path.exists("./report/report_failed.tar"): file_paths.append("./report/report_failed.tar") send_email( "({}) ({}) ({}) ({}) API E2E Test".format(settings.ENV, settings.REGION_NAME, settings.CASE_TYPE, settings.RESOURCE_PREFIX), "html", settings.RECIPIENTS, file_paths) # 同步用例 if settings.ENV == "staging2": create_test_case()
def fetch(self): url = self.url if getsize(url) > MAXIMUM_SIZE: return new_hash = gethash(url) if not self.hash_data: self.hash_data = new_hash self.save() else: if new_hash != self.hash_data: msg = "There has been a change of status in your monitoring course page %s (%s)." % ( self.shortname, self.url) print self.user_profile if self.user_profile.is_phone_set: cell_mail = '%s@%s' % (self.user_profile.cellphone, self.user_profile.cell_mail) send_message(toaddrs=cell_mail, msg=msg[:100] + '...') if self.user_profile.is_email_set: send_email(toaddrs=self.user_profile.email, title="Status change of course page %s" % self.shortname, msg=msg) self.hash_data = new_hash self.save()
def async_send_email_worker(emails, title, content, type='text'): from common import utils return utils.send_email(emails, title, content, type)
def _send_activation_email(self, user: CustomUser) -> None: current_site = get_current_site(self.request) message = render_confirmation_email(user, current_site.domain) send_email(mail_subject="Activate your Sheet Storm account.", message=message, addressee=user.email)
def delete(self, user_id): """ DELETE user request. Only Directors, Organizers and user calling the request """ user_status, calling_user = has_admin_privileges() if user_status == "no_auth_token": return (bad_request, 400, headers) if user_status == "not_logged_in": return (unauthorized, 401, headers) # getting the user. Assuming the user exists. Case of user not existing is checked below try: user = g.session.query(g.Base.classes.users).get(user_id) except Exception as err: print(type(err)) print(err) return (internal_server_error, 500, headers) # *Only Directors, Organizers and user calling the request if user: try: if user_status in ["director", "organizer" ] or calling_user.id == user.id: if user.rsvps_collection: g.session.delete( g.session.query(g.Base.classes.rsvps).get( user.rsvps_collection[0].id)) if user.applications_collection: g.session.delete( g.session.query(g.Base.classes.applications).get( user.applications_collection[0].id)) g.session.delete( g.session.query(g.Base.classes.users).get(user_id)) else: forbidden["error_list"] = { "Authorization error": "You do not privileges to access this resource. Contact one of the organizers if you think require access." } return (forbidden, 403, headers) except Exception as err: print(type(err)) print(err) return (internal_server_error, 500, headers) else: return (not_found, 404, headers) # error handling for mail send try: f = open("common/account_creation.html", 'r') body = Template(f.read()) f.close() body = body.render(first_name=user.first_name) send_email(subject="Account creation confirmation!", recipient=user.email, body="Account deleted!") return ("", 204, headers) except Exception as err: print(type(err)) print(err) internal_server_error["error_list"][ "error"] = "Account successfully created. Error in confirmation email sending." return (internal_server_error, 500, headers)
def post(self): """ Create new user. Required data: email,password,confirmation_password,first_name,last_name """ Users = g.Base.classes.users try: data = request.get_json(force=True) except BadRequest: return (bad_request, 400, headers) # *request data validation. Check for empty fields will be done by frontend validation = User_Input_Schema().validate(data) if validation: unprocessable_entity["error_list"] = validation["_schema"][0] return (unprocessable_entity, 422, headers) # check if user already signed up try: exist_check = g.session.query( exists().where(Users.email == data["email"])).scalar() if exist_check: waste_time() return (conflict, 409, headers) except Exception as err: print(type(err)) print(err) return (internal_server_error, 500, headers) try: new_user = Users(email=data["email"], encrypted_password=encrypt_pass(data["password"]), sign_in_count=0, checked_in=False, role=64, auth_token=secrets.token_urlsafe(25), first_name=data["first_name"], last_name=data["last_name"], confirmation_token=secrets.token_urlsafe(15), confirmation_sent_at=datetime.now(), updated_at=datetime.now(), created_at=datetime.now()) g.session.add(new_user) g.session.commit() ret = g.session.query(Users).filter( Users.email == data["email"]).one() except Exception as err: print(type(err)) print(err) internal_server_error["error_list"][ "error"] = "Error in account creation. Please try again." return (internal_server_error, 500, headers) # error handling for mail send try: f = open("common/account_creation.html", 'r') body = Template(f.read()) f.close() body = body.render(first_name=data["first_name"]) send_email(subject="Account creation confirmation!", recipient=data["email"], body=body) return (User_Schema().dump(ret).data, 201, headers) except Exception as err: print(type(err)) print(err) internal_server_error["error_list"][ "error"] = "Account successfully created. Error in confirmation email sending." return (internal_server_error, 500, headers)
def post(self): """ Create new application. Required data: birth_day birth_month birth_year education university other_university travel_origin graduation_season graduation_year major hackathons github linkedin website devpost other_link statement race gender outside_north_america reimbursement phone """ try: data = request.get_json(force=True) except BadRequest: return (bad_request, 400, headers) # *request data validation. Check for empty fields will be done by frontend validation = Application_Schema().validate(data) if validation: unprocessable_entity["error_list"] = validation return (unprocessable_entity, 422, headers) Applications = g.Base.classes.applications user_status, calling_user = has_admin_privileges() if user_status == "no_auth_token": return (bad_request, 400, headers) if user_status == "not_logged_in": return (unauthorized, 401, headers) # check if application already submitted try: exist_check = g.session.query(exists().where( Applications.user_id == calling_user.id)).scalar() if exist_check: waste_time() return (conflict, 409, headers) except Exception as err: print(type(err)) print(err) return (internal_server_error, 500, headers) try: new_application = Applications( user_id=calling_user.id, birth_day=data['birth_day'], birth_month=data['birth_month'], birth_year=data['birth_year'], education=data['education'], university=data['university'], other_university=data['other_university'], travel_origin=data['travel_origin'], graduation_season=data['graduation_season'], graduation_year=data['graduation_year'], major=list(set(data['major'])), hackathons=data['hackathons'], github=data['github'], linkedin=data['linkedin'], website=data['website'], devpost=data['devpost'], other_link=data['other_link'], statement=data['statement'], created_at=datetime.now(), updated_at=datetime.now(), race=list(set(data['race'])), gender=data['gender'], outside_north_america=data['outside_north_america'], status="Applied", reimbursement=data['reimbursement'], phone=data['phone']) g.session.add(new_application) g.session.commit() ret = g.session.query(Applications).filter( Applications.user_id == calling_user.id).one() ret = Application_Schema().dump(ret).data except Exception as err: print(type(err)) print(err) internal_server_error["error_list"][ "error"] = "Error in application submission. Please try again." return (internal_server_error, 500, headers) # error handling for mail send try: f = open("common/application_submitted.html", 'r') body = Template(f.read()) f.close() body = body.render(first_name=calling_user.first_name) send_email(subject="Application submission confirmation!", recipient=calling_user.email, body=body) return (ret, 201, headers) except Exception as err: print(type(err)) print(err) internal_server_error["error_list"][ "error"] = "Application successfully submitted. Error in confirmation email sending." return (internal_server_error, 500, headers)
def summons_sent(summons): """ Get a message for receiving a summons. """ subject = 'Standards Board: Summoning Request Approved' if summons.spokeWith: summons_info = ( 'The recorded details of your ' 'conversation with the summoner is:\n\n\t"{0}"\n\n' 'The summoner has requested this case be ' 'sent to the Standards Board ' 'for the following reason:\n\n\t"{1}"').format( summons.outcomes, summons.standards_action ) else: summons_info = ( "The reason for your summons is as follows:" "\n\n\t\"{0}\"".format( summons.special_circumstance)) message_context = { 'date': 'Date: {0}.'.format( summons.dateSummonsSent.strftime('%Y-%m-%d')), 'summoner_info': ( # This is all treated as one string, so there is only one # format at the end '{0},\n\n' 'You are receiving this email because you have' ' been summoned by {1} {2}.'.format( summons.summonee.first_name, summons.summoner.first_name, summons.summoner.last_name ) ), 'summons_info': summons_info, 'outcome': ( 'Please come to the next Standards meeting following your case' 'being anounced at a house meeting. ' 'This is the meeting where you case will be heard. ' 'You will have the opportunity to make your case, ' 'after which time the Standards board will decide if an ' 'appropriate sanction should be imposed. ' 'If you cannot make the meeting for a legitimate purpose, ' 'please speak with the Parliamentarian.' '\n\nAs per the bylaws, chosing not to come without an excuse ' 'will be considered as an affirmation of fault and may have ' 'adverse consequences.' ), } message = ( '{date}\n\n{summoner_info} ' '{summons_info}\n\n{outcome}'.format(**message_context) ) fourth = User.objects.get(groups__name='4th Counselor') standards = User.objects.get(groups__name='Parliamentarian') send_email( subject=subject, body=message, to_emails=[summons.summonee.email], cc_emails=[fourth.email, standards.email, settings.EC_EMAIL], )