Example #1
0
File: loop.py Project: epol/script
def delayed_send(sender,rcpt,delay,server):
    global sentdate 
    
    time.sleep(int(delay.total_seconds()))
    sentdate = datetime.datetime.now()
    common.send_mail(sender, [rcpt], "Test "+str(identifier), common.get_baconipsum(), server=server)
    sentdate = datetime.datetime.now()
Example #2
0
def send_email_notice(manager_has_changed_lst):
    if manager_has_changed_lst:
        content = '\n'.join([' '.join([str(y) for y in x]) for x in manager_has_changed_lst])
        # print(content)
        subject = '你关注的基金的经理有变动!请务必考虑是否继续持有!'
        send_mail(subject, content)
        print(subject, " , send email success!")
Example #3
0
def register():
    register_form = RegisterForm()
    data = {
        'title': 'Register',
        'form': register_form,
    }

    if register_form.validate_on_submit():
        # get data from form
        username = register_form.username.data
        password = register_form.password.data
        confirm_password = register_form.confirmPassword.data
        email = register_form.email.data

        # check data
        if len(username) < 2:
            flash(u'用户名长度不能小于2!', 'danger')
            return redirect(url_for('register'))
        if password != confirm_password:
            flash(u'两次密码不匹配!', 'danger')
            return redirect(url_for('register'))
        if len(password) < 6:
            flash(u'密码长度不能小于6!', 'danger')
            return redirect(url_for('register'))
        if not re.match(r'\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*', email):
            flash(u'Email地址不规范!', 'danger')
            return redirect(url_for('register'))

        # Check Username is already register
        user = Users.query.filter_by(username=username).first()
        if user is not None or user:
            flash(u'用户名已存在!', 'danger')
            return redirect(url_for('register'))

        # Insert into database
        user = Users(id="", username=username, email=email, password=password)
        db.session.add(user)
        db.session.commit()
        user = Users.query.filter_by(username=username).first_or_404()
        tid = user.id
        users_info = UsersInfo(id="", user_id=tid,
                               register_time="", last_login_time="", last_login_ip=request.remote_addr,
                               token=random_str(32), is_active=0, qiniu_have_account=0, qiniu_access_key=None,
                               qiniu_secret_key=None, qiniu_bucket_name=None, qiniu_domain=None)
        db.session.add(users_info)
        db.session.commit()

        session['user_id'] = tid

        # Send mail
        s = Serializer(app.config['SECRET_KEY'], 3600)
        token = s.dumps({'user_id': tid})

        send_mail(email, ' Please confirm your account',
                  'mail/confirm', username=username, token=token)

        # return result
        flash(u'注册成功!请到邮箱查看验证邮件,验证通过后方可登录。', 'success')
        return redirect(url_for('register'))
    return render_template("register.html", data=data)
def new_user():
    username = request.json.get('name')
    pwd = request.json.get('password')
    email = request.json.get('email')
    code = 1
    message = "注册成功"
    user = None
    if username is None or pwd is None or email is None:
        code=0
        message = "用户名/密码不能为空"
    elif User.query.filter_by(email=email).first() is not None:
        code=0
        message = "用户已存在!"
    else:
        common.send_mail(email, "您已成功注册海螺!")
        user = User(name=username, password=pwd, email=email)
        session = db_session()
        session.add(user)
        session.commit()
        session.close()
        user = session.merge(user)
        user = user.to_json()
    return jsonify({
        "user":user,
        "info":generate_return_info(code,message)
    })
Example #5
0
 def handel_main_exception(self,e):
     
     if self.options.send_mail:
         self.log.warning(format_exception(e))
         msg = format_exception(e) + "\n runing with \n" + self.options_to_str
         c.send_mail(msg,'Main error do_dicom_series')
     else:
         self.log.warning("\n MAIN exection : \n%s",format_exception(e))
Example #6
0
def main():
    for i in range(4):
        common.send_mail("*****@*****.**",
                         ["*****@*****.**"],
                         subject="Test bacon "+str(i),
                         text=common.get_baconipsum(),
                         server="mail.sns.it",
                         date=common.get_randomdate(datetime.datetime.now() + datetime.timedelta(hours=-2),
                                                    datetime.datetime.now() + datetime.timedelta(minutes=10))
                  )
Example #7
0
 def excute(self, data):
     '''
     1.开始压测
     2.我们要读取locust_stats.csv文件里面 请求,最大,平均,最小的请求数
     3.我们把上面字段的内容提出出来 然后以邮件的形式发送
     :param data:
     :return:
     '''
     # 获取data里面的code的值
     id = get_case_id()
     code = data.get('code')
     # 把页面的code值写到文件中
     f = open('locust_study.py', 'w', encoding='utf-8')
     f.write(code)
     f.close()
     # cmd进行格式化 data = {‘code’:,} 字典
     cmd = CMD.format(**data)
     os.system(cmd)
     # locust_stats.csv 文件名字固定
     # 读取文件里面的内容
     file = open('locust_stats.csv')
     lines = file.readlines()
     print(lines)
     # total,average,minimum,maximum
     total = lines[2].split(',')[2]
     average = lines[2].split(',')[5]
     minimum = lines[2].split(',')[6]
     maximum = lines[2].split(',')[7]
     sender = '*****@*****.**'
     receiver = '*****@*****.**'
     message = '''
          <h3>报警信息</h3>
         <label style='background-color:red'>请求次数:{total}</label></br>
         <label style='background-color:red'>平均响应时间: {average}</label></br>
         <label style='background-color:red'>最小响应时间:{minimum}</label></br>
         <label style='background-color:red'>最大响应时间:{maximum}</label></br>   
         '''
     # total, average, minimum, maximum
     message = message.format(
         **{
             'total': total,
             'average': average,
             'minimum': minimum,
             'maximum': maximum,
         })
     send_mail(sender, receiver, message)
     # 发送邮件
     return id
def edit_profile():
    name = request.json.get("name")
    password = request.json.get("password")
    user = g.user
    user.name = name
    user.password = password
    session = db_session()
    session.add(user)
    try:
        session.commit()
    finally:
        session.close()
    common.send_mail(g.user.email, "您已成功修改个人信息:)")
    return jsonify({
        "user": user.to_json(),
        "info": generate_return_info(1, "操作成功")
    })
Example #9
0
def main():
    print("Today's date: " + str(datetime.now()))
    # 股票基金
    result_fund_bank_content = get_mail_fund_content(mode='fund')
    # 债券基金
    result_stock_bank_content = get_mail_fund_content(mode='stock')
    if '3' == str(months):
        mail_title = "基金种子季报"
        desc = '''--------------------  一周   一月   三月↓
        '''
    elif '6' == str(months):
        mail_title = "基金种子半年报,筛西瓜,扔芝麻!"
        desc = '''--------------------  六月↓   一年   三年
        '''
    dividing_line = '''
    --------------------债券基金--------------------
    '''
    send_mail(mail_title, [desc, result_fund_bank_content, dividing_line, result_stock_bank_content])
    print(result_fund_bank_content)
    print(result_stock_bank_content)
Example #10
0
def login():
    """Log in a registered user by adding the user id to the session."""
    error = None
    if request.method == "POST":
        username = request.form["username"]
        password = request.form.get("password")
        verification_code = request.form.get('verification_code')
        logger.info('%s %s %s' % (username, password, verification_code))
        user = User.query.filter_by(username=username).first()

        if user is None:
            error = {'danger': '用户名不存在!'}
        elif password:
            if not user.check_password(password):
                error = {'danger': "用户名/密码不正确!"}

            if dev and error is None:
                return login_success(user)

            if error is None:
                # store the user id in a new session and return to the index
                code = str(time.time()).split('.')[-1]
                user.code = code
                db.session.commit()
                logger.info(f'{username} {code}')
                send_mail(code, username)
                return render_template('auth/confirm.html', username=username)

        elif verification_code:
            if not user.check_code(verification_code):
                error = {'danger': "验证码不正确!"}

            if error is None:
                return login_success(user)

        logger.info(error)
        flash(error)

    return render_template("auth/login.html", messages=error)
Example #11
0
def send_end_email(exp_id, gf_id, trapid_db_data, msa_only):
    """Send an email to the owner of an experiment to warn them of job completion.

    :param exp_id: TRAPID experiment id
    :param gf_id: gene family id for which an MSA/tree was generated
    :param trapid_db_data: TRAPID database connection data (parameters for common.db_connect())
    :param msa_only: whether only an MSA, and no tree, was generated

    """
    # Get title & email address associated to the experiment
    query_str = "SELECT a.`title`, b.`email` FROM `experiments` a,`authentication` b WHERE a.`experiment_id`='{exp_id}' AND b.`user_id`=a.`user_id`;"
    page_url = '/'.join(
        [common.TRAPID_BASE_URL, 'tools', 'create_tree',
         str(exp_id), gf_id])
    db_conn = common.db_connect(*trapid_db_data)
    cursor = db_conn.cursor()
    cursor.execute(query_str.format(exp_id=exp_id))
    exp_data = cursor.fetchone()
    db_conn.close()
    # Send email
    if not exp_data:
        sys.stderr.write(
            "[Error] Impossible to retrieve experiment title/email address (experiment '%d')!\n"
            % (exp_id))
        sys.exit(1)
    email_subject = "TRAPID phylogenetic tree finished (%s)\n" % gf_id
    if msa_only:
        email_subject = "TRAPID MSA finished (%s)\n" % gf_id
    email_content = (
        "Dear user,\n\n"
        "The phylogenetic tree for gene family '{gf_id}' in experiment '{exp_title}' has been created.\n\n"
        "You can now view it at this URL: {page_url}\n\n"
        "Thank you for using TRAPID.\n").format(gf_id=gf_id,
                                                page_url=page_url,
                                                exp_title=exp_data[0])
    common.send_mail(to=[exp_data[1]],
                     subject=email_subject,
                     text=email_content)
Example #12
0
def auto_send_mail(job, mail, is_async=True):
    user_id = job.user_id
    testcases_ids = testcase_scenes_ids = []
    if job.testcases:
        testcases_ids = eval(job.testcases)
    if job.testcase_scenes:
        testcase_scenes_ids = eval(job.testcase_scenes)
    testcase_time_id = get_testcase_time_id(user_id, is_async)
    post_request(testcases_ids, testcase_scenes_ids, testcase_time_id)
    get_report(testcase_time_id)
    add_message(testcase_time_id)
    if mail:
        if mail.email_method == 1:
            send_mail(mail.subject,
                      mail.to_user_list.split(','),
                      user_id=user_id,
                      testcase_time_id=testcase_time_id)
        elif mail.email_method == 2:
            send_excel(mail.subject,
                       mail.to_user_list.split(','),
                       testcase_time_id=testcase_time_id)
        else:
            print('auto_send_mail:错误的邮件发送方式')
Example #13
0
 def post(self):
     testcase_time_id, user_id, subject, to_user_list, email_method = get_values(
         'report_id', 'user_id', 'subject', 'to_user_list', 'email_method')
     to_user_list = to_user_list.split(',')
     print('TestCaseReportSendMail testcase_time_id:', testcase_time_id,
           subject, to_user_list, email_method)
     result = '正在进行邮件发送'
     if email_method == 1:
         result = send_mail(subject,
                            to_user_list,
                            user_id=user_id,
                            testcase_time_id=testcase_time_id)
     elif email_method == 2:
         result = send_excel(subject,
                             to_user_list,
                             testcase_time_id=testcase_time_id)
     return jsonify(msg=result)
Example #14
0
def send_email_notice(index_value, content):
    low_index1 = select_field('low', 'index_line', {'id': 1})
    high_index1 = select_field('high', 'index_line', {'id': 1})
    low_index2 = select_field('low', 'index_line', {'id': 2})
    high_index2 = select_field('high', 'index_line', {'id': 2})
    index_value_float = float(index_value)

    if (index_value_float < low_index2 and specil_strategy(mode='low')) or (
            index_value_float < low_index1
            and compare_3000_history_value(index_value_float)):
        subject = '快来【买入】基金啦!今日上证指数低谷 = %s!' % str(index_value_float)
        send_mail(subject, content)
        print(index_value + " < %s send email success" % str(low_index1))
    elif (index_value_float > high_index2 and specil_strategy(mode='high')
          ) or (index_value_float > high_index1
                and compare_4000_history_value(index_value_float)):
        subject = '快来【卖出】基金啦!今日上证指数趋于高峰 > %s!' % str(index_value_float)
        send_mail(subject, content)
        print(index_value + " > %s send email success" % str(high_index1))
    elif '买' in content[2] or '卖' in content[2]:
        subject = '快来快来,某基金呼喊你'
        send_mail(subject, content)
        print('快来快来,某基金呼喊你')
Example #15
0
SERVICES = ["central_tanshifx", "forland", "min_fx", "MJ", "cyberagent_fx", "gaitame_dotcom", "himawari_fx"]

from common import open_db_connection
from common import get_mail, send_mail

if "__main__" == __name__:
    database = open_db_connection()
    #     database = None
    for service in SERVICES:
        try:
            s = __import__("".join(["services/", service]))
            s.do_it(database)
        except:
            import traceback

            stacktrace = traceback.format_exc()
            message = get_mail(stacktrace)
            send_mail(message, "*****@*****.**")
            print stacktrace
    database.close()
Example #16
0
if not cm.put_and_create_ns(
    cm.successorHost,
    cm.successorPort,
    cm.failedHost,
    cm.failedPort,
    "/master",
    cm.failureClusterAlias
):
    errmsg += "step1 : qconf setting new master failed \n"

if not cm.put_ns(cm.failedHost, cm.failedPort, "/slave", cm.failureClusterAlias):
    errmsg += "step2 : qconf old master reset slave failed \n"

if not cm.start_slave(cm.failedHost, cm.failedPort):
    errmsg += "step3 : old master start slave failed \n"

if not cm.start_drc(cm.successorHost, cm.successorPort):
    errmsg += "step4 : new master start drc failed \n"

if not cm.reset_cluster_alias(cm.successorHost, cm.successorPort, cm.failureClusterAlias):
    errmsg += "step5 : new master reset alias \n"


if not errmsg:
    cm.send_mail("mysql手动迁移,主从切换<b>成功</b>", "notice")
    cm.log("success taskover_post")
else:
    msg = "mysql手动迁移, 主从切换<b>失败</b> \n 失败原因:%s" % (errmsg)
    cm.log(msg)
    cm.send_mail(msg)
    exit(1)
Example #17
0
# coding:utf-8
import unittest
from common import HTMLTestRunner
import os
from common.send_mail import *

test_case_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                              'test_case')
report_path = os.path.join(
    os.path.join(os.path.dirname(os.path.realpath(__file__)), 'report'),
    'result.html')

# 加载测试用例
discover = unittest.defaultTestLoader.discover(
    start_dir=test_case_path,  # 测试用例位置
    pattern='test*.py',  # test开头.py结尾的文件
    top_level_dir=None)

fb = open(report_path, "wb")
runner = HTMLTestRunner.HTMLTestRunner(stream=fb,
                                       title="自动化测试报告",
                                       verbosity=2,
                                       description="用例执行情况",
                                       retry=1,
                                       save_last_try=True)

runner.run(discover)
result_mail = send_mail()
Example #18
0
import unittest
import time
import HTMLTestRunner
from common.send_mail import *

if __name__ == "__main__":
    test_dir = r'D:\zdh\python\jiaoben\app\testcase'
    test_report = r'D:\zdh\python\jiaoben\app\report'
    discover = unittest.defaultTestLoader.discover(test_dir,
                                                   pattern='test_*.py')
    now = time.strftime("%Y-%m-%d_%H_%M_%S")
    filename1 = test_report + '\\' + now + 'result.html'
    fp = open(filename1, 'wb')
    runner = HTMLTestRunner.HTMLTestRunner(stream=fp,
                                           verbosity=2,
                                           title="ui自动化测试测试报告",
                                           description="用例执行情况")
    runner.run(discover)
    fp.close()

    # 搜索最新生成的文件
    new_report = new_report(test_report)
    #③发送邮件
    send_mail(new_report, filename1, now)

    # 展示测试报告html
    #driver = webdriver.chrome()
    #driver.get("D:/zdh/test/report/" + now +"_result.html")

    stoptime = time.strftime('%H:%M:%S')
    print("结束时间为:%s" % stoptime)