def register(): form = RegisterForm(request.form) if form.validate_on_submit(): user = User(form.username.data, form.email.data, form.password.data, form.type.data, False) db.session.add(user) db.session.commit() temp = None if form.type.data == 'Consumer': temp = Consumer(ConsumerID=user.UserID) elif form.type.data == 'Company': temp = Company(CompanyID=user.UserID) else: temp = Designer(DesignerID=user.UserID) db.session.add(temp) db.session.commit() token = generate_confirmation_token(user.UserEmail) confirm_url = url_for('auth.confirm_email', token=token, _external=True) html = render_template('auth/activate.html', confirm_url=confirm_url) subject = "Please confirm your email" send_email(user.UserEmail, subject, html) login_user(user) flash('A confirmation email has been sent via email.', 'success') return redirect(url_for("auth.unconfirmed")) return render_template('auth/register.html', form=form)
def export_posts(user_id): try: user = User.query.get(user_id) _set_task_progress(0) data = [] total_posts = user.posts.count() for i, post in enumerate(user.posts.order_by(Post.timestamp.asc())): data.append({ "body": post.body, "timestamp": post.timestamp.isoformat() + "Z" }) time.sleep(5) # Only needed to test out progress reporting _set_task_progress(i / total_posts * 100) # Send email to user send_email( subject="Your blog post export", sender=app.config["ADMINS"][0], recipients=[user.email], text_body=render_template("email/export_posts.txt", user=user), html_body=render_template("email/export_posts.html", user=user), attachments=[( "posts.json", "application/json", json.dumps({"posts": data}, indent=4), )], sync=True, ) except: app.logger.error("Unhandled exception", exc_info=sys.exc_info()) finally: _set_task_progress(100)
def export_posts(user_id): try: user = User.query.get(user_id) _set_task_progress(0) data = [] total_posts = user.posts.count() for i, post in enumerate(user.posts.order_by(Post.timestamp.asc())): data.append({ 'body': post.body, 'timestamp': post.timestamp.isoformat() + 'Z', }) # for testing purposes, set a sleep to see task progress in web browser time.sleep(5) _set_task_progress(100 * i // total_posts) send_email( '[Microblog] Exported Posts', sender=app.config['ADMINS'][0], recipients=[user.email], body=render_template('email/export_posts.txt', user=user), html=render_template('email/export_posts.html', user=user), attachments=[( 'posts.json', 'application/json', json.dumps({'posts': data}, indent=4), )], sync=True, ) except: _set_task_progress(100) app.logger.error('Unhandled exception', exc_info=sys.exc_info())
def export_posts(user_id): try: user = User.query.get(user_id) _set_task_progress(0) data = [] i = 0 total_posts = user.posts.count() for post in user.posts.order_by(Post.timestamp.asc()): data.append({ 'body': post.body, 'timestamp': post.timestamp.isoformat() + 'Z' }) time.sleep(5) i += 1 _set_task_progress(100 * i // total_posts) send_email('[Microblog] Your blog posts', sender=app.config['MAIL_FROM'], recipients=[user.email], text_body=render_template('email/export_posts.txt', user=user), html_body=render_template('email/export_posts.html', user=user), attachments=[('posts.json', 'application/json', json.dumps({'posts': data}, indent=4))], sync=True) except: _set_task_progress(100) app.logger.error('Unhandled exception', exc_info=sys.exc_info())
def reset_password_request(): title = 'Reset password' if current_user.is_authenticated: redirect(url_for('auth.index')) form = StartResetPasswordForm() if form.validate_on_submit(): if form.email_validate(): pass else: user = User.query.filter_by(email=form.email.data).first() token = user.get_reset_password_token() html_body = render_template('auth/reset_password.html', user=user, token=token) send_email(subject='Сброс пароля', sender='*****@*****.**', recipients=[user.email], html_body=html_body) flash(f'Вам отправлено письмо на почту {user.email}') return redirect(url_for('auth.reset_password_request')) return render_template('auth/start_reset_password_form.html', form=form, title=title)
def export_posts(user_id): # web应用中的错误和异常会有app.logger来收集,但是对于后台任务是一个单独的进程,所以需要手动来收集错误信息,否则只能通过worker的控制台才能看到错误 try: _set_task_progress(0) user = User.query.get(user_id) total_post = user.posts.count() data = [] i = 0 for post in user.posts.order_by(Post.timestamp.desc()).all(): data.append({'body': post.body, 'timestamp': post.timestamp.isoformat() + 'Z'}) # 把datetime格式的时间转换成字符串,最后加上时区 i += 1 time.sleep(3) _set_task_progress(100*i/total_post) email.send_email(subject='[myblog] your posts', sender=app.config['ADMIN'], receiver=[user.email], text_body=render_template('auth/email/export_posts.txt', user=user), html_body=render_template('auth/email/export_posts.html', user=user), attachments=[('posts.txt', 'text/plain', json.dumps({'posts': data}, ensure_ascii=False, indent=4).encode('utf-8'))], # indent=4是为了更好看的输出, encode编码是为了保证附件的中文不被转换成16进制 sync=True) # 这里已经是后台任务,所以选择成同步模式发送邮件,否则会有问题 except: _set_task_progress(100) app.logger.error('Unhandled exception', exc_info=sys.exc_info()) # sys.exc_info()方法包含了错误的traceback信息
def email_patient(email): form = EmailPatientForm() if form.validate_on_submit(): #subject, sender, reciever, text_body, html_body send_email(form.subject.data, current_user.email, email, form.body.data, form.body.data) flash('Your email has succesfully been sent.') return redirect(url_for('auth.all_patients', email=current_user.email)) return render_template('auth/email_patient.html', email=email, form=form)
def signup(): """ Signup a user using name, email, password. :return: Http Json response """ if request.content_type == 'application/json': post_data = request.get_json(force=True) email = post_data.get('email') password = User.encode_password(post_data.get('password')) name = post_data.get('name') if re.match(r"[^@]+@[^@]+\.[^@]+", email): user = User.get_by_email(email) if user and user.isActive and user.isEmailVerified: return response( 'failed', 'Email already registered. Use the Sign-in option', 401) if user and user.isActive and not user.isEmailVerified: token = user.get_auth_token() confirm_url = url_for('auth.verify', token=token, _external=True) html = render_template('activate.html', confirm_url=confirm_url) subject = "Fronteous Arena - Confirm your email address" send_email(user.email_id, subject, html) logger.bind(userId=user._id) return response_auth('success', 'Successfully signed up.', None, None, 200) else: user = User(email_id=email, name=name, password=password) user.sign_up(userObj=post_data) if not user.isEmailVerified: #If email is not verified. Not email at this stage wil be verified only for invited users coming through invitation token token = user.get_auth_token() confirm_url = url_for('auth.verify', token=token, _external=True) html = render_template('activate.html', confirm_url=confirm_url) subject = "Fronteous Arena - Confirm your email address" send_email(user.email_id, subject, html) logger.bind(userId=user._id) return response_auth('success', 'Successfully signed up.', None, None, 200) return response( 'failed', 'Missing or wrong email format or password is less than four characters', 400) return response('failed', 'Content-type must be json', 402)
def signup(): if current_user.is_authenticated: return redirect(url_for('main.index')) # jsonify({'url': '/', 'msg': 'you are already login, you cant perform this action'}) form = RegistrationForm(request.form) if request.method == 'POST': if form.validate_on_submit(): # noinspection PyArgumentList,PyArgumentList,PyArgumentList,PyArgumentList,PyArgumentList,PyArgumentList user = User(full_name=request.form['full_name'], email=request.form['email'], username=request.form['username'], password=request.form['password'], email_confirmed=False, account_confirmed=False) try: db.session.add(user) db.session.commit() except IntegrityError: db.session.rollback() # The following lines of code # is the confirmation email being sent # to the user token = generate_confirmation_token(user.email) confirm_url = url_for('auth.confirm_email', token=token, _external=True) html = render_template('activate.html', confirm_url=confirm_url) subject = 'Please confirm your Email' # send_email function was imported from # the email file # send_email(user.email, subject, html) flash('A mail has been sent to you') return redirect(url_for('auth.login')) # return jsonify({'code': 200, 'url': '/login'}) # else: # return jsonify({'msg': 'something wrong occurred', 'url': '/signup'}) return render_template('register.html', form=form)
def post(self): parser = reqparse.RequestParser() parser.add_argument('username', required=True) parser.add_argument('email', required=True) parser.add_argument('password', required=True) args = parser.parse_args() # 验证长度 if len(args['username']) == 0 or len(args['username']) > 32: abort_unacceptable_length("username") if len(args['email']) == 0: abort_unacceptable_length("email") if len(args['password']) == 0: abort_unacceptable_length("password") # User existing if LocalAuth.query.filter_by(username=args['username']).first(): abort_username_existed('username') if LocalAuth.query.filter_by(email=args['email']).first(): abort_username_existed('email') # 写入数据库 user = User() db.session.add(user) db.session.commit() localauth = LocalAuth(username=args['username'], email=args['email'], user=user) localauth.hash_password(args['password']) db.session.add(localauth) db.session.commit() # 发送邮件 token = generate_confirmation_token(localauth.email) confirm_url = url_for('frontend.confirm_email', token=token, _external=True) html = ''' <p>Welcome! Thanks for signing up. Please follow this link to activate your account:</p> <p><a href="%s">%s</a></p> <br> <p>Cheers!</p> ''' % (confirm_url, confirm_url) subject = "Please confirm your email" send_email(localauth.email, subject, html) return "{ 'username': %s }" % (localauth.username), 201
def login(): if current_user.is_authenticated: return redirect(url_for('main.index')) form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user is None or not user.check_password(form.password.data): flash("Invalid user name or password") return redirect(url_for('auth.login')) login_user(user, remember=form.remember_me.data) send_email('new message from Hello', '*****@*****.**', ['*****@*****.**'], 'this is body', 'this is html body') next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for("main.index") return redirect(next_page) return render_template('auth/login.html', form=form, title="Sign In")
def reset(): if current_user.is_authenticated: return redirect(url_for('main.index')) form = EmailForm(request.form) if request.method == 'POST': if form.validate_on_submit(): user = User.query.filter_by(email=request.form['email']).first() if user and user.email_confirmed: subject = 'Password reset requested' token = generate_recovery_token(user.email) recover_url = url_for('auth.reset_password_with_token', token=token, _external=True) html = render_template('recover.html', recover_url=recover_url) send_email(user.email, subject, html) flash( 'A confirmation link to reset your password has been sent to you' ) return redirect(url_for('auth.login')) # return jsonify({'url': '/login'}) else: flash('This email has\nt been confirmed yet') # return jsonify({'msg': 'This email has\nt been confirmed yet'}) return render_template('reset.html', form=form)
def resend_email(): if current_user.is_authenticated: return jsonify({'url': '/', 'msg': 'user already logged in'}) form = ResendEmailForm(request.form) if request.method == 'POST': if form.validate_on_submit(): user = User.query.filter_by(email=request.form['email']).first() token = resend_confirmation_token(user.email) subject = 'Please confirm your email' confirm_url = url_for('auth.confirm_recovery_email', token=token, _external=True) html = render_template('resend_email_confirms.html', confirm_url=confirm_url) send_email(user.email, subject, html) flash('A confirmation email has been sent to you') return redirect(url_for('main.index')) # return jsonify({'url': '/login'}) # else: # return jsonify({'status': 'error','msg': 'check post form', # 'url': '/resend/email'}) return render_template('resend_email.html', form=form)
def submission(): user = load_user(current_user.id) query_seq = Post(author=user).query.order_by(Post.timestamp.desc()).first() query_seq = query_seq.body hasher = hashlib.md5(query_seq.encode('ASCII')) hasher = hasher.hexdigest()[:50] hasher = hasher + str(random.randint(1, 10000)) sequence = '/Users/LarryBliss/Documents/Viper 2/Hermes_Prediction/app/backend/Sequences_for_prediction.fa' with open(sequence, 'w') as outfile: outfile.write(str(query_seq)) with open(sequence, 'a') as outfile: with open(sequence, 'r') as fin: lines = fin.readlines() # flash(lines[-1]) if lines[-1] != '>': outfile.write('\n>\n') sequences = [] with open(sequence, 'r') as fin: in_sequence = '' for line in fin: if line.startswith('>'): sequences.append(in_sequence) in_sequence = '' else: in_sequence += line.strip() # flash(sequences) sequences = list(filter(None, sequences)) # flash(sequences) # flash(query_seq) prediction_sets = [] title_set = [] dummy_email_list = [ '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**' ] for seq, dummy_email in zip(sequences, itertools.cycle(dummy_email_list)): DNA, RNA, protein, protein_length, Hermes_final_solution = Launcher( dummy_email, seq) prediction_sets.append( [DNA, RNA, protein, protein_length, Hermes_final_solution]) title_set.append([ 'DNA sequence: ', 'RNA sequence: ', 'Amino acid sequence: ', 'Length of the protein: ', 'Final Hermes_Prediction Solution: ' ]) if Hermes_final_solution == "": flash( "Unfortunately there is an issue with a protein layer server and an optimal result is unattainable at this momment, please try again later" ) count = 1 message = "" with open( "/Users/LarryBliss/Documents/Viper 2/Hermes_Prediction/app/solved_prediction_set.txt", 'w') as prediction_file: for pred_set, t_set in zip(prediction_sets, title_set): prediction_file.write("Submission " + str(count) + '\n') message += "Submission " + str(count) + '\n' message += '\n' for element1, element2 in zip(pred_set, t_set): prediction_file.write(str(element2)) prediction_file.write(str(element1) + '\n') message += '\n' message += str(element2) message += str(element1) + '\n' count += 1 with open( "/Users/LarryBliss/Documents/Viper 2/Hermes_Prediction/app/templates/base_prediction.html", 'r') as base_file: with open( "/Users/LarryBliss/Documents/Viper 2/Hermes_Prediction/app/templates/prediction.html", "w") as final_file: lines = base_file.readlines() for line in lines: final_file.write(line) with open( "/Users/LarryBliss/Documents/Viper 2/Hermes_Prediction/app/solved_prediction_set.txt", "r") as contents: with open( "/Users/LarryBliss/Documents/Viper 2/Hermes_Prediction/app/templates/prediction.html", "a") as e: for lines in contents.readlines(): if lines != '\n' or lines != None: e.write('<pre style="font-size:18px">' + lines + "</pre> <br>\n") e.write("{% endblock %}") send_email(user.email, message) return redirect(url_for('main.specific_submission', hasher=hasher))