class aMail: def __init__(self): self.app = None self.mail = None def initApp(self, app): self.app = app self.mail = Mail() self.mail.init_app(app) def send_async_email(self, msg): with self.app.app_context(): self.mail.send(msg) def send_email(self, msg): thr = Thread(target=self.send_async_email, args=[msg]) thr.start() return thr def send_email_low(self, msg): try: self.mail.send(msg) return True except Exception as e: return False
def create_app(config_class=Config): application = Flask(__name__) application.config.from_object(config_class) mongo.init_app(application, tlsCAFile=certifi.where()) bcrypt.init_app(application) cors.init_app(application) Mail.init_app(application) os.environ['ROOT_PATH'] = application.root_path # Init firebase with your credentials cred = credentials.Certificate(os.path.join( application.root_path, 'static', os.environ.get('Private_Key_JSON'))) initialize_app( cred, {'storageBucket': os.environ.get('Image_Bucket')}) from abbrefy.users.routes import users from abbrefy.links.routes import links from abbrefy.main.routes import main from abbrefy.links.links_api import linksApi from abbrefy.users.users_api import usersApi application.register_blueprint(users) application.register_blueprint(links) application.register_blueprint(main) application.register_blueprint(linksApi) application.register_blueprint(usersApi) return application
def trans_mail(sender_acc, sender, new_balance, receiver_acc, receiver, amount, new_balance_recv): mail = Mail() app.config["MAIL_SERVER"] = "smtp.gmail.com" app.config["MAIL_PORT"] = 465 app.config["MAIL_USE_SSL"] = True app.config["MAIL_USERNAME"] = '******' app.config["MAIL_PASSWORD"] = '******' mail.init_app(app) summary = "\n\nTransaction summary :\n\n" + "Sent by : " + str( sender_acc) + "\nreceived by : " + str( receiver_acc) + "\nAmount : " + str( amount) + " \nCurrent balance : " msg = Message("Account Credited", sender="Projectsoteria-support", recipients=[receiver]) warning = "\n\nNote : Never share your private key with anybody." msg.body = " Your account has been credited by amount " + str( amount) + summary + str(new_balance_recv) + warning mail.send(msg) msg = Message("Account Debited", sender="Projectsoteria-support", recipients=[sender]) warning = "\n\nNote : Never share your private key with anybody." msg.body = "Your account has been debited by amount " + str( amount) + summary + str(new_balance) + warning mail.send(msg) return True
def change_permissions(self, user): if current_user.is_admin: form = ChangePermissionsForm() if request.method == 'POST': user.change_permissions(form.is_admin.data, form.can_post_provided.data, form.can_post_solicited.data) mail = Mail() mail.init_app(current_app) mail.send_message( subject="Your YDP Account", recipients=[user.email], body= f"""Hello {user.name}, Your YCP Project Database account permissions have been modified by an admin""" ) return redirect(url_for('UserPageView:view', id=user.id)) else: catalog = user.get_user_projects() form.is_admin.data = user.is_admin form.can_post_provided.data = user.can_post_provided form.can_post_solicited = user.can_post_solicited return render_template('userpage.html', catalog=catalog, user=user, permissions_form=form, current_user=current_user) else: return 'Access denied', 403
def email_activate_account(profile_dict): app = Flask(__name__) app.config['MAIL_SERVER'] = 'smtp.mailtrap.io' app.config['MAIL_PORT'] = 2525 app.config['MAIL_USERNAME'] = '******' app.config['MAIL_PASSWORD'] = '******' app.config['MAIL_USE_TLS'] = True app.config['MAIL_USE_SSL'] = False mail = Mail(app) mail.init_app(app) name = dict_val_similar_key(profile_dict, 'first_name') profile_email = dict_val_similar_key(profile_dict, 'email') token = gen_unik_token(profile_email) token_link = f'http://127.0.0.1:5000/activate_account?key={token}' #token_link = f'http://127.0.0.1:5000/matcha_activate_account/5' message = f'click on this link to activate your account \n {token_link}' subject = f"welcome to Matcha, activate your account {name}" msg = Message(sender="*****@*****.**", recipients=["*****@*****.**"], body=message, subject=subject) with app.app_context(): mail.send(msg)
def create_app(config, enable_config_env=False): """app工厂""" app = Flask(__name__, template_folder='../templates') app.config.from_object(config) if enable_config_env: from common.utils import constants app.config.from_envvar(constants.GLOBAL_SETTING_ENV_MAIL_USERNAME, silent=True) app.config.from_envvar(constants.GLOBAL_SETTING_ENV_MAIL_PASSWORD, silent=True) app.config.from_envvar(constants.GLOBAL_SETTING_ENV_MAIL_SENDER, silent=True) # 初始化邮箱扩展 mail = Mail() mail.init_app(app) app.mail = mail # 初始化bootstrap扩展 bootstrap = Bootstrap() bootstrap.init_app(app) # 初始化ckeditor ckeditor = CKEditor() ckeditor.init_app(app) return app
def send_all_mail(): # pragma: no cover print('Sending mails...') mail = Mail(app) mail.init_app(app=app) users = requests.get(DATASERVICE + '/users').json() for user in users: # check if this user wants to receives mail report = db.session.query(Report).filter( Report.user_id == str(user['id'])).first() if report is not None and time() - report.timestamp >= report.frequency: body = prepare_body(user) if body: # can be None if there are no runs to be shown # send the mail print('Sending email to %s' % user['email']) msg = Message('Your BeepBeep Report', sender=app.config['MAIL_USERNAME'], recipients=[user['email']]) msg.body = body mail.send(msg) # update the latest report timestamp report.set_timestamp() db.session.merge(report) db.session.commit() print('All mails are sent')
def create_app(): mail = Mail() app = Flask(__name__) mail.init_app(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) return app
class EmailService(EmailServiceInterface): def __init__(self): self.mail = Mail() self.mail.init_app(APP) def _send_email(self, message: Message): with APP.app_context(): try: self.mail.send(message) except ConnectionRefusedError as msg: APP.logger.warning("%(msg)s" % {"msg": msg}) def send(self, message_data: dict): message = Message( subject=message_data["subject"], sender=message_data["sender"], recipients=[message_data["to"]], body=message_data["content_text"], html=message_data["content_html"], ) try: Thread(target=self._send_email, args=(message)).start() return True except SMTPAuthenticationError as msg: APP.logger.warning("%(msg)s" % {"msg": msg}) except SMTPException as msg: APP.logger.warning("%(msg)s" % {"msg": msg}) return False
def send_all_mail(): # pragma: no cover print('sending') global _APP # lazy init if _APP is None: from monolith.app import create_app app = create_app() db.init_app(app) else: app = _APP mail = Mail(app) mail.init_app(app=app) with app.app_context(): users = db.session.query(User).filter() for user in users: report = db.session.query(Report).filter( Report.runner_id == user.id).first() if report is not None and time( ) - report.timestamp >= report.choice_time: body = prepare_body(user, app) if body: msg = Message('Your BeepBeep Report', sender=app.config['MAIL_USERNAME'], recipients=[user.email]) msg.body = body mail.send(msg) report.set_timestamp() db.session.merge(report) db.session.commit()
class MailEmailMethodService(IEmailMethodService): def __init__(self): self.mail = Mail() self.mail.init_app(current_app) def send_message(self, data_message: dict): message = Message( subject=data_message['subject'], sender=data_message['sender'], recipients=[data_message['to']], body=data_message['content_text'], html=data_message['content_html'] ) try: self.mail.send(message) return True except SMTPAuthenticationError as e: print("error: {0}".format(e)) except SMTPException as e: print("error: {0}".format(e)) return False
def reset(): if current_user.is_authenticated: return redirect(url_for("index")) form = EmailForm() if form.validate_on_submit(): agency = Agency.query.filter_by(email=form.email.data).first_or_404() subject = "Password reset requested." token = ts.dumps(agency.email, salt='recover-key') recover_url = url_for('reset_with_token', token=token, _external=True) html = 'hello ' + recover_url from flask_mail import Mail, Message mail = Mail() mail.init_app(app) msg = Message("hello", sender="*****@*****.**", recipients=["*****@*****.**"]) msg.html = html mail.send(msg) flash('An email has been sent to ' + agency.email + ' with a password reset link.') return redirect(url_for("login")) return render_template('reset.html', form=form)
def create_app(config_name): app = Flask(__name__) #setting up configuration app.config.from_object(config_options[config_name]) # Initializing Flask Extensions bootstrap.init_app(app) db.init_app(app) login_manager.init_app(app) mail = Mail() def create_app(config_name): app = Flask(__name__) #........ mail.init_app(app) # Registering the blueprint from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/authenticate') return app
def forgotPassword(self): form = RecoveryForm() if request.method == 'POST': try: user = User.get_by_username(form.username.data) if user: # initializing size of string N = 8 # using secrets.choices() # generating random strings res = ''.join( secrets.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase + string.punctuation) for i in range(N)) user.update_password(res, res) flash('Password change successful!') mail = Mail() mail.init_app(current_app) mail.send_message(subject="PASSWORD CHANGED!", recipients=[user.email], html=render_template( 'pwd_forgot_email.html', username=form.username.data, res=res)) return redirect(url_for('UserView:login')) except TypeError as e: flash(str(e)) return render_template('forgot_password.html', form=form)
def init_mail(app=None): """ flask-mail i initialize eder """ if app is None: app = current_app mail = Mail() try: universite_id = SessionHandler.universite_id() ayarlar = DB.session.query(SiteAyarlari).filter_by( universite_id=universite_id).first() mail_sunucu_ayarlari = ayarlar.params["mail_sunucu_ayarlari"] mail_config = { "MAIL_SERVER": mail_sunucu_ayarlari['mail_server'], "MAIL_PORT": mail_sunucu_ayarlari['mail_port'], "MAIL_USE_TLS": mail_sunucu_ayarlari['mail_use_tls'], "MAIL_USE_SSL": mail_sunucu_ayarlari['mail_use_ssl'], "MAIL_USERNAME": mail_sunucu_ayarlari['mail_username'], "MAIL_PASSWORD": ayarlar.mail_password, "MAIL_DEFAULT_SENDER": mail_sunucu_ayarlari['mail_default_sender'], "MAIL_MAX_EMAILS": mail_sunucu_ayarlari['mail_max_emails'] } app.logger.info("Mail ayarlari databaseden tekrar yuklendi") state = mail.init_mail(config=mail_config) app.extensions['mail'] = state except (AttributeError, RuntimeError, InternalError, ProgrammingError): app.logger.info( "Mail ayarlari databaseden yuklenemedi config'den aliniyor") mail.init_app(app=app)
def set_mail(user): s = Serializer(app.config['SECRET_KEY'], 300) data = {'email': user.email} data.update({'id': user.name}) token = s.dumps(data) mail = Mail() mail.init_app(app) msg = Message('重置密码', sender=('图片秀', '*****@*****.**'), recipients=[user.email]) #msg.body = render_template('reset_password.txt',token = token, email=email ) msg.html = render_template('reset_password.html', token=token, name=user.name) app2 = current_app._get_current_object() #mail.send(msg) th = Thread(target=send_async_mail, args=[app2, msg]) th.start() # 使用JWT.io(https://jwt.io )提供的调试工具 # https://ninghao.net/blog/2834 # time.sleep(2) # s1 = Serializer(app.config['SECRET_KEY']) # data1 = s1.loads(ss) return "邮件已发送,5分钟内有效;"
def mail_setup(app): """ init flask mail """ mail = Mail() mail.init_app(app) app.mail = mail
def create_app(config=None): app = Flask(__name__) # load configuration if config: app.config.from_object(config) else: app.config.from_object('rhiz.config.Default') app.config.from_envvar('RHIZ_APPLICATION_SETTINGS') security = Security() security.init_app(app, user_datastore) assets.init_app(app) db.init_app(app) admin.init_app(app) mail = Mail() mail.init_app(app) feature_flag = FeatureFlag() feature_flag.init_app(app) # register routes register_blog_routes(app) return app
def post(self, client_id, hostname): req = request if 'file' in req.files: file = req.files['file'] fileName = secure_filename(file.filename) basePath = os.path.join('/tmp', client_id) if os.path.exists(basePath): shutil.rmtree(basePath) os.mkdir(basePath) filePath = os.path.join(basePath, fileName) file.save(filePath) mail = Mail() mail.init_app(app) msg = Message("MacPatch - Support Data From {}".format(hostname), sender='*****@*****.**', recipients=['*****@*****.**']) msg.body = "Log Capture From {} \n".format(client_id) with app.open_resource(filePath) as fp: msg.attach(fileName, "application/zip", fp.read()) mail.send(msg) if os.path.exists(basePath): shutil.rmtree(basePath) return {"result": {}, "errorno": 200, "errormsg": ''}, 200
def create_app(): """Create Flask Application""" app = Flask(__name__, instance_relative_config=False) # config app with things i'd normally put in app.py app.config.from_object("config.Config") app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( "DATABASE_URL", "postgres:///carabiner" ) app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False app.config["SQLALCHEMY_ECHO"] = True app.config["DEBUG_TB_INTERCEPT_REDIRECTS"] = False app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY") toolbar = DebugToolbarExtension(app) # Flask-Login init login_manager = LoginManager() # Mail init mail = Mail() # Assets init assets = Environment() # DB init connect_db(app) mail.init_app(app) login_manager.init_app(app) assets.init_app(app) with app.app_context(): # Import parts of our application from .index import index from .api_test import api_test from .auth import auth from .user_views import user_views from .search_views import search_views from .route_views import route_views # Register Blueprints app.register_blueprint(index.index_bp) app.register_blueprint(api_test.api_test_bp, url_prefix="/api") app.register_blueprint(auth.auth_bp) app.register_blueprint(user_views.user_views) app.register_blueprint(search_views.search_views) app.register_blueprint(route_views.route_views) # Compile static assets compile_assets(assets) return app # Error Handlers @app.errorhandler(404) def page_not_found(error): return render_template("404.html")
def send_self_email(subject, name, email, body): mail = Mail() mail.init_app(app) msg = Message(subject, sender='*****@*****.**', recipients=['*****@*****.**']) msg.body = "From: {} ({}) \n {}".format(name, email, body) mail.send(msg)
def send_email(to, subject, template): mail = Mail() mail.init_app(current_app) msg = Message(subject, recipients=[to], html=template, sender=current_app.config['MAIL_DEFAULT_SENDER']) mail.send(msg)
def mailer(app): internal_mail = Mail() internal_mail.init_app(app) internal_mail.server = config.INTERNAL_MAIL_SERVER internal_mail.username = config.INTERNAL_MAIL_USERNAME internal_mail.password = config.INTERNAL_MAIL_PASSWORD internal_mail.port = config.INTERNAL_MAIL_PORT return internal_mail
def create_app(): env = DotEnv() app = Flask(__name__) env.init_app(app) env.eval(keys={ 'DEBUG': bool, 'TESTING': bool }) mail = Mail(app) mail.init_app(app) @app.route("/", methods=['GET', 'POST']) def index(): """ Render the view of index page. """ form = FeedbackForm() return render_template('index.html', title='Tri Sinergi Mitra', current_page='TSM', form=form) @app.route("/send_feedback", methods=['POST']) def send_feedback(): """ Do action with python form """ if request.method == 'POST' : #result = request.form result = request.form['email'] msg_subject = "You got an email from {} / {} - {}".format(request.form['email'], request.form['full_name'], request.form['subject']) msg_body = request.form['body'] send_email(msg_subject,'*****@*****.**', ['*****@*****.**'], msg_body) return redirect(url_for('index')) else: flash('The message has not been sent due to unknown failure') return redirect(url_for('index')) def send_email(subject, sender, recipients, text_body): msg = Message(subject, sender=sender, recipients=recipients) msg.body = text_body mail.send(msg) return @app.errorhandler(404) def page_not_found_error(err): """ Render the view of error 404 page """ return render_template('404.html', title='TSM not found', current_page='404') @app.errorhandler(500) def internal_server_error(err): """ Render the view of error 500 page """ return render_template('500.html', title='TSM internal server error', current_page='500') return app
def init_app(self, app): app.jinja_env.filters[ "humanizeDateToNaturalTime"] = humanize_date_to_natural_time app.extensions["inspirehep-mailing"] = self mail = Mail() mail.init_app(app) return self
def get_mail(): # 初始化邮件 global _mail if not _mail: from flask_mail import Mail _mail = Mail(current_app) _mail.init_app(current_app) return _mail
def send_trial_expired_email(email): app = Flask(__name__) mail = Mail() mail.init_app(app) msg = Message("Your free trial with Domain has expired.", sender="*****@*****.**", recipients=[email]) msg.html = render_template('user/mail/trial_expired_email.html') mail.send(msg)
def send_email(email, text, topic, app): with app.app_context(): mail = Mail() mail.init_app(app) message = Message(topic, recipients=[email]) message.body = text mail.send(message)
def app(): db = MongoEngine() crypt = Bcrypt() mongo = PyMongo() mail = Mail() login_manager = LoginManager() login_manager.login_view = None login_manager.login_message_category = 'info' app = create_app({ "SECRET_KEY": 'testsecret', "SECURITY_PASSWORD_SALT": 'testsalt', "SECURITY_CSRF_COOKIE": { "key": "XSRF-TOKEN" }, "SECURITY_CSRF_IGNORE_UNAUTH_ENDPOINTS": True, "WTF_CSRF_TIME_LIMIT": None, "WTF_CSRF_CHECK_DEFAULT": False, "MONGODB_SETTINGS": { 'host': 'mongodb://localhost/pwsched-test' }, "MONGO_URI": 'mongodb://localhost/pwsched-test', "TESTING": True }) db.init_app(app) crypt.init_app(app) login_manager.init_app(app) mongo.init_app(app) mail.init_app(app) Shift.drop_collection() Congregation.drop_collection() User.drop_collection() congregation = Congregation(name="English - Willimantic").save() shift = Shift(location="UConn", datetime=datetime.now, congregation=congregation.to_dbref()).save() congregation.shifts.append(shift.to_dbref()) congregation.save() hashed_password = crypt.generate_password_hash('password').decode('utf-8') User( name="Brother Service Overseer", email="*****@*****.**", password=hashed_password, congregation=( Congregation.objects().order_by('-id').first().to_dbref())).save() yield app Shift.drop_collection() Congregation.drop_collection() User.drop_collection()
def send_creator_welcome_email(email): app = Flask(__name__) mail = Mail() mail.init_app(app) msg = Message("You've successfully signed up for Schedulr!", sender="*****@*****.**", recipients=[email]) msg.html = render_template('user/mail/creator_welcome_email.html') mail.send(msg)
def send_cancel_email(email): app = Flask(__name__) mail = Mail() mail.init_app(app) msg = Message("Goodbye from Schedulr", sender="*****@*****.**", recipients=[email]) msg.html = render_template('user/mail/cancel_email.html') mail.send(msg)
def send_cancel_email(email): app = Flask(__name__) mail = Mail() mail.init_app(app) msg = Message("Goodbye from Domain", sender="*****@*****.**", recipients=[email]) msg.html = render_template('user/mail/cancel_email.html') mail.send(msg)
def send_cancel_email(email): app = Flask(__name__) mail = Mail() mail.init_app(app) msg = Message("Goodbye from SimpleMetrics", #sender="*****@*****.**", sender="*****@*****.**", recipients=[email]) msg.html = render_template('pages/cancel_email.html') mail.send(msg)
def mail(): print current_app.config msg = Message("hello", sender = "*****@*****.**", recipients = ['*****@*****.**']) msg.body = "testing" msg.html = "<b>testing</b>" mail = Mail() mail.init_app(current_app) mail.send(msg) return "ok"
class Mailer(object): def __init__(self, app): self.mail = Mail() self.mail.init_app(app) def send_simple_mail(self, details): msg = Message(subject=details.Subject, sender=details.Sender, recipients=details.To.split(','), html=details.Message) self._send(msg) def _send(self, msg): self.mail.send(msg)
def get_mail(default_config=None): email_config = default_config or config.get('email', default_value={}, value_type=dict) app.config.update({ 'MAIL_SERVER': email_config['smtp_server'], 'MAIL_PORT': int(email_config['smtp_port']), 'MAIL_USE_SSL': bool(int(email_config['smtp_ssl'])), 'MAIL_USERNAME': email_config['email_address'], 'MAIL_PASSWORD': email_config['email_password'], 'MAIL_DEFAULT_SENDER': email_config['email_address'], }) mail = Mail() mail.init_app(app) return mail
def send_welcome_email(email, plan): app = Flask(__name__) mail = Mail() mail.init_app(app) msg = Message("You've successfully signed up for SimpleMetrics!", #sender="*****@*****.**", sender="*****@*****.**", recipients=[email]) if (plan == 'Hobby'): amount = 39 elif (plan == 'Startup'): amount = 79 else: amount = 149 msg.html = render_template('pages/welcome_email.html', plan=plan, amount=amount) mail.send(msg)
def send_plan_change_email(email, plan): app = Flask(__name__) mail = Mail() mail.init_app(app) msg = Message("Your plan with SimpleMetrics has been changed.", #sender="*****@*****.**", sender="*****@*****.**", recipients=[email]) if (plan == 'Hobby'): amount = 39 elif (plan == 'Startup'): amount = 79 else: amount = 149 msg.html = render_template('pages/plan_change_email.html', plan=plan, amount=amount) mail.send(msg)
def create_app(configuration=None, instance_path='/etc/ihatemoney', instance_relative_config=True): app = Flask( __name__, instance_path=instance_path, instance_relative_config=instance_relative_config) # If a configuration object is passed, use it. Otherwise try to find one. load_configuration(app, configuration) app.wsgi_app = PrefixedWSGI(app) # Get client's real IP # Note(0livd): When running in a non-proxy setup, is vulnerable to requests # with a forged X-FORWARDED-FOR header app.wsgi_app = ProxyFix(app.wsgi_app) validate_configuration(app) app.register_blueprint(web_interface) app.register_blueprint(api) # Configure the application setup_database(app) mail = Mail() mail.init_app(app) app.mail = mail # Error reporting Sentry(app) # Jinja filters app.jinja_env.filters['minimal_round'] = minimal_round # Translations babel = Babel(app) @babel.localeselector def get_locale(): # get the lang from the session if defined, fallback on the browser "accept # languages" header. lang = session.get('lang', request.accept_languages.best_match(['fr', 'en'])) setattr(g, 'lang', lang) return lang return app
def send_email(username, email, password): app.config.update(dict( DEBUG=True, MAIL_SERVER = app.config['MAIL_SERVER'], MAIL_PORT = app.config['MAIL_PORT'], MAIL_USE_TLS = True, MAIL_USERNAME = app.config['MAIL_USERNAME'], MAIL_PASSWORD = app.config['MAIL_PASSWORD'], )) mail = Mail(app) mail.init_app(app) subject = 'Mewstagram Registration Notification' msg = Message(subject=subject,sender='*****@*****.**',recipients=[email]) msg.html = make_msg_html(username, password) thr = Thread(target=send_async_email, args=[app,msg,mail]) thr.start() return thr
def contact_us_email(email, message): app = Flask(__name__) mail = Mail() mail.init_app(app) msg = Message("Support request from " + email, #recipients=["*****@*****.**"], recipients=["*****@*****.**"], #sender="*****@*****.**") sender="*****@*****.**") msg.body = email + " sent you a message:\n\n" + message response = Message("Your email to SimpleMetrics has been received.", recipients=[email], sender="*****@*****.**") response.body = "\n\nThanks for emailing us! Your message has been sent and we'll reply shortly. Please don't " \ "respond to this email, as it's coming from an autoresponder and we won't get any replies to " \ "this address.\n\nThe email address you provided is " + email + "." mail.send(msg) mail.send(response)
app.config['SECURITY_RECOVERABLE'] = True app.config['SECURITY_CHANGEABLE'] = SECURITY_CHANGEABLE """ The default settings for Mail """ app.config['MAIL_SERVER'] = MAIL_SERVER app.config['MAIL_PORT'] = MAIL_PORT app.config['MAIL_USE_TLS'] = MAIL_USE_TLS app.config['MAIL_USERNAME'] = MAIL_USERNAME app.config['MAIL_PASSWORD'] =MAIL_PASSWORD app.config['MAIL_DEFAULT_SENDER'] = MAIL_DEFAULT_SENDER appMail = Mail() appMail.init_app(app) # apply settings for default security views app.config['SECURITY_LOGIN_URL']=SECURITY_LOGIN_URL app.config['SECURITY_LOGOUT_URL']=SECURITY_LOGOUT_URL app.config['SECURITY_REGISTER_URL']=SECURITY_REGISTER_URL app.config['SECURITY_RESET_URL']=SECURITY_RESET_URL app.config['SECURITY_CHANGE_URL']= SECURITY_CHANGE_URL app.config['SECURITY_CONFIRM_URL']=SECURITY_CONFIRM_URL app.config['SECURITY_CONFIRM_ERROR_VIEW'] = SECURITY_CONFIRM_ERROR_VIEW app.config['SECURITY_POST_LOGOUT_VIEW']=SECURITY_POST_LOGOUT_VIEW app.config['SECURITY_POST_CONFIRM_VIEW'] = SECURITY_POST_CONFIRM_VIEW #set the template html pages app.config['SECURITY_FORGOT_PASSWORD_TEMPLATE'] = SECURITY_FORGOT_PASSWORD_TEMPLATE app.config['SECURITY_LOGIN_USER_TEMPLATE'] = SECURITY_LOGIN_USER_TEMPLATE
def register_mail(app): mail = Mail() mail.init_app(app) return mail
def create_celery_app(app=None): app = app or create_app("sz_webapp", os.path.dirname(__file__)) mail = Mail() mail.init_app(app) from .logs import init_app_logger init_app_logger(app, 'celery_error.log') celery_app = celery.Celery(__name__, broker=app.config["CELERY_BROKER_URL"], backend=app.config["CELERY_RESULT_BACKEND"]) celery_app.conf.update(app.config) TaskBase = celery_app.Task class ContextTask(TaskBase): abstract = True def __call__(self, *args, **kwargs): with app.app_context(): return TaskBase.__call__(self, *args, **kwargs) celery_app.Task = ContextTask from celery.signals import task_postrun from .core import db from .models import CeleryTaskLog @task_postrun.connect def task_postrun_handler(*args, **kwargs): task_id = kwargs['task_id'] task_name = kwargs['task'].name task_args = kwargs['args'] task_kwargs = kwargs['kwargs'] task_state = kwargs['state'] task_retval = kwargs['retval'] task_log = db.session.query(CeleryTaskLog).filter(CeleryTaskLog.id == task_id).first() if not task_log: task_log = CeleryTaskLog(id=task_id, name=task_name, args=task_args, kwargs=task_kwargs, retries=0) if task_state == 'SUCCESS': task_log.status = 1 elif task_state == 'FAILURE': task_log.status = -1 elif task_state == 'RETRY': task_log.status = -2 task_log.retries += 1 if isinstance(task_retval, basestring): task_log.retval = task_retval elif isinstance(task_retval, Exception): task_log.retval = str(task_retval) else: try: task_log.retval = json.dumps(task_retval) except Exception, e: task_log.retval = "no_jsonified_object" _logger.exception(e) db.session.add(task_log)
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_mail import Message, Mail from flask_login import LoginManager # Create an Instance of Flask application = Flask(__name__) # Include config from config.py application.config.from_object('config') application.secret_key = 'A0Zr98jh/3yXR~XHH!jmN]LWX/,?RT' # Create an instance of SQLAlchemy db = SQLAlchemy(application) mail = Mail() mail.init_app(application) login_manager = LoginManager() login_manager.init_app(application) login_manager.login_view = 'login' login_manager.login_message = u"Please log in to access this page." login_manager.login_message_category = "info" # Import views to enable proper routing from app import models, views
#-*- coding: utf-8 -*- from flask import Flask from flask.ext.login import LoginManager from flask_mail import Mail app = Flask(__name__) app.config.from_object('config') lm = LoginManager() lm.init_app(app) mailbox = Mail() mailbox.init_app(app) from .main import main as main_blueprint from .login import login as login_blueprint from .profile import profile as profile_blueprint from .detail import detail as detail_blueprint from .manager import manager as manager_blueprint from .ranking import ranking as ranking_blueprint app.register_blueprint(login_blueprint) # login: 用户登录, 用户注册, 验证系统 app.register_blueprint(profile_blueprint) # profile: 用户自己的信息, 借了哪些书, 记录 app.register_blueprint(main_blueprint) # main: 展示在架书籍 app.register_blueprint(detail_blueprint) # detail: 书籍详情页 app.register_blueprint(manager_blueprint) # manager: 管理图书,添加图书 app.register_blueprint(ranking_blueprint) # ranking: 排行榜
from app.config.app_config import DevelopmentConfig flapp.config.from_object(DevelopmentConfig()) from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy(flapp) from dbase.dbutils import init_db init_db(flapp) flapp.orderbooks = dict() from flask.ext.socketio import SocketIO socketio = SocketIO(flapp) from redis import Redis rcon = Redis() from flask_user import SQLAlchemyAdapter, UserManager from dbase.models import User db_adapter = SQLAlchemyAdapter(db, User) # Register the User model user_manager = UserManager(db_adapter, flapp) # Initialize Flask-User from flask_mail import Mail mail = Mail(flapp) mail.init_app(flapp) flapp.config['TESTING'] = True flapp.config['LOGIN_DISABLED'] = True import views, forms # import forms, views, eventhandlers, market, testing, utils, dbase
request, render_template, url_for, redirect, request, jsonify, flash, session ) from flask_mail import Mail, Message from utilities import paginate_model mail = Mail() metpet_ui = Flask(__name__) metpet_ui.config.from_object("config") mail.init_app(metpet_ui) dotenv.read_dotenv(os.path.dirname(__file__) + '../app_variables.env') @metpet_ui.route("/") def index(): return render_template("index.html", auth_token = session.get("auth_token",None), email = session.get("email",None), name = session.get("name",None) ) @metpet_ui.route("/search/") def search():
webapp.config['MAIL_PORT'] = 465 webapp.config['MAIL_USE_TLS'] = False webapp.config['MAIL_USE_SSL'] = True webapp.config['MAIL_USERNAME'] = '******' webapp.config['MAIL_PASSWORD'] = '******' webapp.config['DEFAULT_MAIL_SENDER'] = '*****@*****.**' db.init_app(webapp) login_manager = LoginManager() login_manager.init_app(webapp) bcrypt = Bcrypt() mail = Mail() mail.init_app(webapp) bootstrap = Bootstrap() bootstrap.init_app(webapp) import datetime from dateutil import parser from rq import Queue from rq.job import Job from worker import conn q = Queue(connection=conn) import tasks import collections
from dateutil import parser as dateparser # app config app = Flask(__name__) app.config.from_pyfile('flaskapp.cfg') # debug config app.debug = False toolbar = DebugToolbarExtension(app) # app setup CsrfProtect(app) mongo = PyMongo(app) mail = Mail() mail.init_app(app) def make_poem_html(poem, pid): """This function makes a section of HTML code for a poem. Args: poem: A poem defined as a list (rows) of lists (words in rows). pid: HTML <p> tag ID attribute for CSS identification. Returns: A string containing HTML code for displaying a poem, for example: '<p id="poemline">Day, Morning, Sun,</p><p id="poemline">Birds, Trees, Grass.</p>' """ res_html = ''
csrf = CsrfProtect() db = SQLAlchemy() # After defining `db`, import auth models due to # circular dependency. from mhn.auth.models import User, Role, ApiKey user_datastore = SQLAlchemyUserDatastore(db, User, Role) mhn = Flask(__name__) mhn.config.from_object('config') csrf.init_app(mhn) # Email app setup. mail = Mail() mail.init_app(mhn) # Registering app on db instance. db.init_app(mhn) # Setup flask-security for auth. Security(mhn, user_datastore) # Registering blueprints. from mhn.api.views import api mhn.register_blueprint(api) from mhn.ui.views import ui mhn.register_blueprint(ui) from mhn.auth.views import auth