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 execute(self, **kwargs): """ Send email message """ from . import actions with self.act_manager.app.app_context(): if self.act_manager.app.debug == True: msg = Message(sender='*****@*****.**') for func in [getattr(self, aa) for aa in dir(self) if aa.startswith('get_')]: result = func(**kwargs) if result: head, sep, tail = func.__name__.partition('_') if tail == 'attachments': for attachment in result: msg.add_attachment(attachment) else: setattr(msg, tail, result) mail = Mail(self.act_manager.app) mail.connect() mail.send(msg) if self.log_mail: """ Log email to a table with a timestamp. Note, for attachements, don't only log the file name and content_type, not the data. """ pass return
def registration_user(): data = request.get_json(force=True) if not User().check_mail_for_uniqueness(data['email']): return hook_validation_error('Email already exists. Please register with a new email.') elif not User().check_unique_username(data['username']): return hook_validation_error('Username already exists, please try another username') else: user = datastore.create_user(email=data['email'], password=data['password']) user.set_password(data['password']) user.active = False user.username = data['username'] db.session.commit() email_token = generate_confirmation_token(user.email) confirm_url = url_for('.confirm_email', token=email_token, _external=True) mail = Mail() msg = Message("Please confirm your account", sender="*****@*****.**", recipients=[user.email]) msg.body = render_template( "email/confirmation_email.txt", confirmation_url=confirm_url, user=user ) msg.html = render_template( "email/confirmation_email.html", confirmation_url=confirm_url, user=user ) mail.send(msg) return jsonify({ 'id': user.id, 'message': 'User successfully created, please check your email to activate your account' })
def send_email(self, register_user): """ Method for sending the registration Email to the user """ try: from flask_mail import Mail, Message except: log.error("Install Flask-Mail to use User registration") return False mail = Mail(self.appbuilder.get_app) msg = Message() msg.subject = self.email_subject url = url_for('.activation', _external=True, activation_hash=register_user.registration_hash) msg.html = render_template(self.email_template, url=url, username=register_user.username, first_name=register_user.first_name, last_name=register_user.last_name) msg.recipients = [register_user.email] try: mail.send(msg) except Exception as e: log.error("Send email exception: {0}".format(str(e))) return False return True
def email_errors(): beginningform = TimeForm(request.form) endform = TimeForm(request.form) if request.method == 'POST': beginning = beginningform.year + beginningform.month + beginningform.day + beginningform.hour + beginningform.min + beginningform.sec end = endform.year + endform.month + endform.day + endform.hour + endform.min + endform.sec begformatted = "%s/%s/%s %s:%s:%s" %(beginningform.month, beginningform.day, beginningform.year, beginningform.hour, beginningform.min, beginningform.sec) endformatted = "%s/%s/%s %s:%s:%s" %(endform.month, endform.day, endform.year, endform.hour, endform.min, endform.sec) report = "Between %s and %s, the following errors occurred:\n" %(begformatted, endformatted) errorcount = error_handling.count_errors(int(beginning), int(end)) for error in errorcount: report += "%d of error \"%s\"\n" %(errorcount[error], error_handling.db.lindex(error, 0)) # move this to mail module ADMINS = ["*****@*****.**"] msg = Message("Error Aggregation Report", sender = "*****@*****.**", recipients = ADMINS) msg.body = report mail = Mail(app) mail.send(msg) return render_template('email_errors.html', form = beginningform) elif request.method == 'GET': return render_template('email_errors.html')
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 send_mail(app, form): """ Send email confirmation of an RSVP response, both to myself and to the guest. If DEBUG is enabled, send responses to a testing address instead. """ mail = Mail(app) msg = Message("Thanks for your RSVP!", sender="*****@*****.**", reply_to="Daven and Beth <*****@*****.**>", extra_headers={"From":"Daven and Beth via davenquinn.com <*****@*****.**>"}) if app.config["DEBUG"]: msg.recipients = ['*****@*****.**'] else: msg.recipients = [form["email"]] msg.bcc = ["*****@*****.**"] _ = partial(render_template, form=form, attending=int(form["number"]) > 0) msg.body = _("wedding/email/thanks.txt") msg.html = _("wedding/email/thanks.html") mail.send(msg)
class Email(object): def __init__(self, app): self.app = app self.mail = Mail(app) def send_welcome(self, user, passwd): subject = 'Bem vindo ao garupa.com!' recipients = [user.get_email()] body = 'Oi %s,\n' % user.get_name() body += 'Sua conta no garupa.com foi criada com sucesso!\n\n' body += 'Sua matricula: %s\n' % user.get_uid() body += 'Sua senha: %s (nao va perder em?)\n' % passwd self.send(subject, recipients, body) def send_recover_passwd(self, user, passwd): subject = 'Tua senha! Criatura esquecida!' recipients = [user.get_email()] body = 'Oi %s,\n' % user.get_name() body += 'Esquecesse tua senha num foi?\n' body += 'Sua senha nova: %s (nao vai esquecer de novo em?)' % passwd self.send(subject, recipients, body) def send(self, subject, recipients, text_body): msg = Message(subject, recipients=recipients) msg.body = text_body thr = Thread(target=self.send_async, args=[msg]) thr.start() def send_async(self, msg): with self.app.app_context(): self.mail.send(msg)
def callmeCreate(): jsonData = request.get_json(force=True) if not (jsonData and 'name' in jsonData and 'phone' in jsonData): #check not-nullable fields abort(400) #set gmail settings app.config.update( MAIL_SERVER='smtp.gmail.com', MAIL_PORT=465, MAIL_USE_SSL=True, MAIL_USERNAME='******', MAIL_PASSWORD=MAIL_PASS, MAIL_DEFAULT_SENDER=('ВИССОН', '*****@*****.**') ) mail = Mail(app) #and send email to me try: #send to buyer msg = Message("ВИССОН", recipients=["*****@*****.**"]) msg.html = "Заявка перезвонить <br> имя: %s <br> номер: %s <br>" % (jsonData.get("name"), jsonData.get("phone")) mail.send(msg) except BaseException as e: print(str(e)) abort(400) return str(True)
def rims_add(): form = RimForm(request.form) if request.method == "POST" and form.validate_on_submit(): rim = Rims() form.populate_obj(rim) db.session.add(rim) db.session.commit() flash("Rim Created") if app.config.get('MAIL_SERVER', None): mail = Mail(app) body = render_template('rims_email.txt.j2', form=form, rim=rim) msg = Message(subject="New Rim submitted", body=body, recipients=[app.config.get('MAIL_TO', None)]) try: mail.send(msg) except Exception as e: app.logger.error(e) return redirect(url_for("wheel_add_rim", rim_id=rim.id)) else: for e in form.errors.items(): flash(f"{e[0]} - {e[1][0]}") return render_template('rims_add.html.j2', form=form)
def hubs_add(): form = HubForm(request.form) if request.method == "POST" and form.validate_on_submit(): hub = Hubs() form.populate_obj(hub) db.session.add(hub) db.session.commit() flash("Hub Created") if app.config.get('MAIL_SERVER', None): mail = Mail(app) body = render_template('hubs_email.txt.j2', form=form, hub=hub) msg = Message(subject="New Hub submitted", body=body, sender="*****@*****.**", recipients=[app.config.get('MAIL_TO', None)]) try: mail.send(msg) except Exception as e: app.logger.error(e) return redirect(url_for("wheel_add_hub", hub_id=hub.id)) else: for e in form.errors.items(): flash(f"{e[0]} - {e[1][0]}") return render_template('hubs_add.html.j2', form=form)
def send_mail(recipient,hash_code): mail = Mail(app) msg = Message("Your python snippet",sender="*****@*****.**",recipients=[recipient]) msg.html = render_template("email.html",emailid=recipient.split('@')[0],link="http://pypad.herokuapp.com/get/"+hash_code) mail.send(msg)
def sendMail(self, app, form): app.config['MAIL_SERVER']='smtp.gmail.com' app.config['MAIL_PORT'] = 465 app.config['MAIL_USERNAME'] = Constants.ADMIN_MAIL_ADDR app.config['MAIL_PASSWORD'] = Constants.ADMIN_MAIL_PASS app.config['MAIL_USE_TLS'] = False app.config['MAIL_USE_SSL'] = True mail = Mail(app) #generate encrypt key encryptkey = Script.encode(form['mail']) # read file and prepare mail body txtBody = '' with open(Constants.MAIL_TEMPLATE_FILE) as f: content = f.readlines() #content = [x.strip() for x in content] for row in content: row = row.replace("%ACTIVATION_LINK%", "http://localhost/activate?mail={0}&encryptkey={1}".format(form['mail'], encryptkey)) row = row.replace("%MAIL_ADDRESS%", form['mail']) row = row.replace("%FIRSTNAME%", form['firstname']) row = row.replace("%REGISTRATION_DATE%", strftime("%Y-%m-%d %H:%M:%S", gmtime())) txtBody +=row msg = Message('Registration', sender = Constants.ADMIN_MAIL_ADDR, recipients = [form['mail']]) msg.body = txtBody mail.send(msg)
def test_email(): from flask_mail import Mail, Message mail = Mail(app) msg = Message(subject='test subject', recipients=[app.config['TEST_RECIPIENT']]) msg.body = 'text body' msg.html = '<b>HTML</b> body' with app.app_context(): mail.send(msg)
def send_mail(config, msg): if not config.get('MAIL_DEFAULT_SENDER', None): return app = Flask('june') app.config = config with app.test_request_context(): mail = Mail(app) mail.send(msg)
def send_mail(config, msg): if not config.get("DEFAULT_MAIL_SENDER", None): return app = Flask("yuan") app.config = config with app.test_request_context(): mail = Mail(app) mail.send(msg)
def send_activation_mail(user_id, email): url = url_for('activation', signedstring=sign(str(user_id), app.config), _external=True) mail = Mail(app) msg = Message('Activate your account', recipients=[email], sender='*****@*****.**') msg.body = render_template('email.activation.txt', url=url) msg.html = render_template('email.activation.html', url=url) mail.send(msg)
def send_mail(subject, body, to): mail = Mail(app) # Configure the specifics message = Message(subject, sender=('surgeprotech submissions','*****@*****.**'), recipients=[to]) message.body = body # Finally send the mail mail.send(message)
def test_email(): """ Usage: ./manage.py test email Send a test email -- useful for ensuring flask-mail is set up correctly """ from flask_mail import Mail, Message mail = Mail(app) msg = Message(subject='test subject', recipients=[app.config['TEST_RECIPIENT']]) msg.body = 'text body' msg.html = '<b>HTML</b> body' with app.app_context(): 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 deliver(cls, msg, force=False, dogfood=True, deferred=False): if not msg: return False # HACKY HACK HACK # this allows the stuff to work from command line, it is # kind of terrible though. Ideally we just use current_app from app import application mail = Mail(application) cls.set_defaults(msg) # check the user's email preferences #for recipient in msg.recipients: #user = User.find_by_email(recipient) #if user and not EmailPreference.is_on(user, msg.category): #msg.recipients.remove(recipient) if len(msg.recipients) == 0: print "No recipients" return False # create an email log #el = EmailLog.log(msg) #if config.FLASK_ENV != 'production': # only send mails in debug mode if we force it #if not force: #body = msg.html #pass #if msg.body: #body = msg.body # pass # don't log if we're in test #if config.FLASK_ENV != 'test': # pass #return True #else: # log to mixpanel #pass # send or defer #if deferred: #cls.enqueue(msg) #else: mail.send(msg) # log message as sent #el.sent = True #db.add(el) #db.commit() if ((config.FLASK_ENV == 'production') or force) and dogfood: cls.send_dogfood(msg, deferred) return True
class SMTPEmailAdapter(EmailAdapterInterface): """ Implements the EmailAdapter interface to send emails with SMTP using Flask-Mail.""" def __init__(self, app): """Check config settings and setup Flask-Mail. Args: app(Flask): The Flask application instance. """ super(SMTPEmailAdapter, self).__init__(app) # Setup Flask-Mail try: from flask_mail import Mail except ImportError: raise ConfigError( "The Flask-Mail package is missing. Install Flask-Mail with 'pip install Flask-Mail'.") self.mail = Mail(app) def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name): """ Send email message via Flask-Mail. Args: recipient: Email address or tuple of (Name, Email-address). subject: Subject line. html_message: The message body in HTML. text_message: The message body in plain text. """ # Construct sender from sender_name and sender_email sender = '"%s" <%s>' % (sender_name, sender_email) if sender_name else sender_email # Send email via SMTP except when we're testing if not current_app.testing: # pragma: no cover try: # Prepare email message from flask_mail import Message message = Message( subject, sender=sender, recipients=[recipient], html=html_message, body=text_message) # Send email message self.mail.send(message) # Print helpful error messages on exceptions except (socket.gaierror, socket.error) as e: raise EmailError('SMTP Connection error: Check your MAIL_SERVER and MAIL_PORT settings.') except smtplib.SMTPAuthenticationError: raise EmailError('SMTP Authentication error: Check your MAIL_USERNAME and MAIL_PASSWORD settings.')
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"
def contact(): form = ContactForm() if form.validate_on_submit(): # validate form on submit # mail = Mail(app) body = '' for x in form.fields: body+='%s : %s\n' % (x['field_name'],form[x['field']].data) msg = Message("NCI Wiki new account request", sender=form.email.data, recipients=["*****@*****.**"], body=body) mail.send(msg) return redirect('/success') # redirect to success page if it passes # return render_template('home.html', form=form) # render template again if fails #
def send_email(subject, body, pdf_path=""): mail_ext = Mail(app) mail_to_be_sent = Message( subject=subject, recipients=app_config.recipients, sender=app_config.sender) mail_to_be_sent.body = body if pdf_path: with app.open_resource(pdf_path) as fp: mail_to_be_sent.attach(pdf_path, "application/pdf", fp.read()) mail_ext.send(mail_to_be_sent)
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 check_queue(ip, port): app = Flask(__name__) app.config['SERVER_NAME'] = conf.SERVER_NAME app.add_url_rule('/pathfinder/download/<uuid>', 'download', download) with app.app_context(): db = get_db() cur = db.cursor() cur.execute('select * from job where status == ?', ('R',)) numjobs = 0 mail = None for row in cur.fetchall(): uuid, email, date, status = row # finished? pid = int(open(os.path.join(get_job_folder(uuid), 'run.pid'), 'r').read()) if pid_exists(pid): numjobs += 1 else: mail = Mail(app) msg = Message('[PathFinder] Your job is finished.', sender='*****@*****.**', recipients=[email, '*****@*****.**']) if os.path.exists(os.path.join(get_job_folder(uuid), 'pathway.pdb')): cur.execute('update job set status = ? where uuid = ?', ('F',uuid)) msg.body = render_template('email.tpl', uuid=uuid, has_error=False) msg.attach('pathway.pdb', 'text/pdb', open(os.path.join(get_job_folder(uuid), 'pathway.pdb')).read()) else: cur.execute('update job set status = ? where uuid = ?', ('E',uuid)) msg.body = render_template('email.tpl', uuid=uuid, has_error=True) if numjobs < NUMJOBS_CONCUR: cur.execute('select * from job where status == ?', ('Q',)) for row in cur.fetchall(): uuid, email, date, status = row newpid = client(ip, port, "SPAWN:%s" % uuid) open(os.path.join(get_job_folder(uuid), 'run.pid'), 'w').write(newpid) cur.execute('update job set status = ? where uuid = ?', ('R',uuid)) numjobs += 1 if numjobs >= NUMJOBS_CONCUR: break db.commit() db.close() if mail: try: mail.send(msg) except: pass
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)
import wget from flask import request, flash, Flask from flask_mail import Message, Mail from werkzeug.utils import secure_filename from forms import ALLOWED_EXTENSIONS j = Flask(__name__) j.config['MAIL_SERVER'] = 'smtp.nyu.edu' j.config['MAIL_PORT'] = 25 j.config['MAIL_USERNAME'] = '******' j.config['MAIL_PASSWORD'] = '' j.config['MAIL_USE_TLS'] = False j.config['MAIL_USE_SSL'] = False mail = Mail(j) def redisjob(target_dir, timestamp, email, chrom, upstream_fasta, downstream_fasta, position, ref_fastaURL, ref_gffURL, in_fasta, in_gff): if position: command = "bash ./run.sh {} {} {} {} {} {} {} {} {}".format( target_dir, timestamp, email, chrom, ref_fastaURL, ref_gffURL, in_fasta, in_gff, position) else: command = "bash ./run.sh {} {} {} {} {} {} {} {} {} {}".format( target_dir, timestamp, email, chrom, ref_fastaURL, ref_gffURL, in_fasta, in_gff, upstream_fasta, downstream_fasta) try: os.system(command)
static_file_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '../public/') app = Flask(__name__) app.url_map.strict_slashes = False app.config.update( dict( DEBUG=True, MAIL_SERVER='smtp.outlook.com', MAIL_PORT=587, MAIL_USE_TLS=True, MAIL_USE_SSL=False, MAIL_USERNAME='******', MAIL_PASSWORD='******', )) app.mail = Mail(app) # database condiguration if os.getenv("DATABASE_URL") is not None: app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL') else: app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:////tmp/test.db" app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False MIGRATE = Migrate(app, db) db.init_app(app) app.config["JWT_SECRET_KEY"] = os.environ.get("JWT_SECRET_KEY") jwt = JWTManager(app) # Allow CORS requests to this API CORS(app)
import os from flask import Flask from dotenv import load_dotenv from flask_restful import Api from flask_sqlalchemy import SQLAlchemy from flask_jwt_extended import JWTManager from flask_mail import Mail api = Api() db = SQLAlchemy() jwt = JWTManager() mailsender = Mail() def create_app(): app = Flask(__name__) load_dotenv() if not os.path.exists(os.getenv('DATABASE_PATH')+os.getenv('DATABASE_NAME')): os.mknod(os.getenv('DATABASE_PATH')+os.getenv('DATABASE_NAME')) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////'+os.getenv('DATABASE_PATH')+os.getenv('DATABASE_NAME') db.init_app(app) import main.resources as resources api.add_resource(resources.BolsonesResource,'/bolsones') api.add_resource(resources.BolsonResource,'/bolson/<id>') api.add_resource(resources.BolsonesVentaResource, '/bolsones-venta') api.add_resource(resources.BolsonVentaResource,'/bolson-venta/<id>') api.add_resource(resources.BolsonesPendientesResource,'/bolsones-pendientes') api.add_resource(resources.BolsonPendienteResource,'/bolson-pendiente/<id>') api.add_resource(resources.BolsonesPreviosResource,'/bolsones-previos')
from flask import url_for, request, render_template, redirect, send_from_directory, g, session, abort, flash, jsonify from functools import wraps from lib import * from coco_scheduling import * import re from flask.globals import session, request from flask_mail import Mail, Message from db_helper import DBAssistant # from celery import Celery app.config.from_object(__name__) mail_ext = Mail(app) # celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL']) # celery.conf.update(app.config) PERIOD = {} COLORPREFS = {0: "tomato", 1: "", 2: "yellow", 3: "lightgreen", 5: "lightgrey"} courseComplete = { } # for the current lecturer: dictionary for courses and resp. preferences for each of them hrs = { } # hours per week for every course of current lecturer (who is logged in now) markedTimes = {} allSolutions = [] incr = 0 newPrefs = 0 app.config.from_envvar('COCO_SETTINGS', silent=True) db_assist = DBAssistant()
def __init__(self, repo, db_uri=None, debug=None, config=None, **kwargs): Flask.__init__(self, __name__, template_folder='templates', static_folder='static') # Add unique identifier for this application isinstance self.uuid = str(uuid.uuid4()) if 'KNOWLEDGE_REPO_MASTER_UUID' not in os.environ: os.environ['KNOWLEDGE_REPO_MASTER_UUID'] = self.uuid # Preload default configuration self.config.from_object('knowledge_repo.app.config_defaults') # Load configuration from file or provided object if config: if isinstance(config, str): config = imp.load_source('knowledge_server_config', os.path.abspath(config)) self.config.from_object(config) # Add configuration passed in as keyword arguments self.config.update(kwargs) # Prepare repository, and add it to the app if hasattr(config, 'prepare_repo'): repo = config.prepare_repo(repo) self.repository = repo assert isinstance(self.repository, knowledge_repo.KnowledgeRepository), "Invalid repository object provided." # Set debug mode from kwargs or else maintain current setting if debug is not None: self.config['DEBUG'] = debug # Set the secret key for this instance (creating one if one does not exist already) self.config['SECRET_KEY'] = self.config['SECRET_KEY'] or str(uuid.uuid4()) # Configure database if db_uri: self.config['SQLALCHEMY_DATABASE_URI'] = db_uri logger.debug(u"Using database: {}".format(self.config['SQLALCHEMY_DATABASE_URI'])) # Register database schema with flask app sqlalchemy_db.init_app(self) # Set up database migration information # Registers Migrate plugin in self.extensions['migrate'] Migrate(self, self.db) # Try to create the database if it does not already exist # Existence is determined by whether there is an existing alembic migration revision db_auto_create = self.config.get('DB_AUTO_CREATE', True) db_auto_upgrade = self.config.get('DB_AUTO_UPGRADE', True) if db_auto_create and self.db_revision is None: self.db_init() elif db_auto_upgrade: self.db_upgrade() # Initialise login manager to keep track of user sessions LoginManager().init_app(self) self.login_manager.login_view = 'auth.login' self.login_manager.anonymous_user = AnonymousKnowledgeUser @self.login_manager.user_loader def load_user(user_id): return User(identifier=user_id) # Attempt login via http headers if header is specified if self.config.get('AUTH_USER_IDENTIFIER_REQUEST_HEADER'): @self.login_manager.request_loader def load_user_from_request(request): identifier = request.headers.get(current_app.config['AUTH_USER_IDENTIFIER_REQUEST_HEADER']) if identifier: if current_app.config['AUTH_USER_IDENTIFIER_REQUEST_HEADER_MAPPING']: identifier = current_app.config['AUTH_USER_IDENTIFIER_REQUEST_HEADER_MAPPING'](identifier) user = User(identifier=identifier) user.can_logout = False user = prepare_user(user, session_start=False) return user # Intialise access policies self.principal = Principal(self) # Add AnonymousIdentity fallback so that on_identity_loaded is called for # anonymous users too. self.principal.identity_loaders.append(lambda: AnonymousIdentity()) # Synchronise user permissions with data model @user_loaded_from_request.connect def on_user_loaded_from_request(sender, user): self.principal.set_identity(Identity(user.id)) @identity_loaded.connect_via(self) def on_identity_loaded(sender, identity): populate_identity_roles(identity, user=current_user) @self.errorhandler(PermissionDenied) def handle_insufficient_permissions(error): return render_template('permission_denied.html'), 403 # Add mail object if configuration is supplied if self.config.get('MAIL_SERVER'): self.config['mail'] = Mail(self) # Register routes to be served self.register_blueprint(routes.posts.blueprint) self.register_blueprint(routes.health.blueprint) self.register_blueprint(routes.index.blueprint) self.register_blueprint(routes.tags.blueprint) self.register_blueprint(routes.vote.blueprint) self.register_blueprint(routes.comment.blueprint) self.register_blueprint(routes.stats.blueprint) self.register_blueprint(routes.editor.blueprint) self.register_blueprint(routes.groups.blueprint) self.register_blueprint(routes.auth.blueprint) KnowledgeAuthProvider.register_auth_provider_blueprints(self) if self.config['DEBUG']: self.register_blueprint(routes.debug.blueprint) # Register error handler @self.errorhandler(500) def show_traceback(self): """ If LOCAL MODE: show the stack trace on a server error otherwise show a nice error template to the users """ if current_app.config.get("DEBUG"): return render_template('traceback.html', info=traceback.format_exc()), 500 else: return render_template('error.html') @self.before_first_request def ensure_excluded_tags_exist(): # For every tag in the excluded tags, create the tag object if it doesn't exist excluded_tags = current_app.config['EXCLUDED_TAGS'] for tag in excluded_tags: Tag(name=tag) db_session.commit() # Set up indexing timers set_up_indexing_timers(self) @self.before_request def open_repository_session(): if not request.path.startswith('/static'): current_repo.session_begin() @self.after_request def close_repository_session(response): if not request.path.startswith('/static'): current_repo.session_end() return response @self.context_processor def webediting_enabled(): # TODO: Link this more to KnowledgeRepository capability and # configuration rather than a specific name. return {"webeditor_enabled": 'webposts' in current_repo.uris} @self.context_processor def inject_version(): version = knowledge_repo.__version__ version_revision = None if '_' in knowledge_repo.__version__: version, version_revision = version.split('_') return dict(version=version, version_revision=version_revision, last_index=time_since_index(human_readable=True), last_index_check=time_since_index_check(human_readable=True)) @self.template_global() def modify_query(**new_values): args = request.args.copy() for key, value in new_values.items(): args[key] = value return u'{}?{}'.format(request.path, url_encode(args)) @self.template_global() def pagination_pages(current_page, page_count, max_pages=5, extremes=True): page_min = int(max(1, current_page - math.floor(1.0 * max_pages // 2))) page_max = int(min(page_count, current_page + math.floor(1.0 * max_pages / 2))) to_acquire = max_pages - (page_max - page_min + 1) while to_acquire > 0 and page_min > 1: page_min -= 1 to_acquire -= 1 while to_acquire > 0 and page_max < page_count: page_max += 1 to_acquire -= 1 pages = list(range(page_min, page_max + 1)) if extremes: if 1 not in pages: pages[0] = 1 if page_count not in pages: pages[-1] = page_count return pages @self.template_filter('format_date') def format_date(date): """ This will be a Jinja filter that string formats a datetime object. If we can't correctly format, we just return the object. :type date: Datetime :return: A string of the format of YYYY-MM-DD :rtype: String """ try: return datetime.strftime(date, '%Y-%m-%d') except: return date
def base_app(request): """Flask application fixture without OAuthClient initialized.""" instance_path = tempfile.mkdtemp() base_app = Flask('testapp') base_app.config.update( TESTING=True, WTF_CSRF_ENABLED=False, LOGIN_DISABLED=False, CACHE_TYPE='simple', OAUTHCLIENT_REMOTE_APPS=dict( cern=CERN_REMOTE_APP, orcid=ORCID_REMOTE_APP, github=GITHUB_REMOTE_APP, globus=GLOBUS_REMOTE_APP, ), GITHUB_APP_CREDENTIALS=dict( consumer_key='github_key_changeme', consumer_secret='github_secret_changeme', ), ORCID_APP_CREDENTIALS=dict( consumer_key='orcid_key_changeme', consumer_secret='orcid_secret_changeme', ), CERN_APP_CREDENTIALS=dict( consumer_key='cern_key_changeme', consumer_secret='cern_secret_changeme', ), GLOBUS_APP_CREDENTIALS=dict( consumer_key='globus_key_changeme', consumer_secret='globus_secret_changeme', ), # use local memory mailbox EMAIL_BACKEND='flask_email.backends.locmem.Mail', SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI', 'sqlite://'), SERVER_NAME='localhost', DEBUG=False, SECRET_KEY='TEST', SECURITY_DEPRECATED_PASSWORD_SCHEMES=[], SQLALCHEMY_TRACK_MODIFICATIONS=False, SECURITY_PASSWORD_HASH='plaintext', SECURITY_PASSWORD_SCHEMES=['plaintext'], APP_ALLOWED_HOSTS=['localhost']) FlaskMenu(base_app) Babel(base_app) Mail(base_app) InvenioDB(base_app) InvenioAccounts(base_app) with base_app.app_context(): if str(db.engine.url) != 'sqlite://' and \ not database_exists(str(db.engine.url)): create_database(str(db.engine.url)) db.create_all() def teardown(): with base_app.app_context(): db.session.close() if str(db.engine.url) != 'sqlite://': drop_database(str(db.engine.url)) shutil.rmtree(instance_path) request.addfinalizer(teardown) base_app.test_request_context().push() return base_app
def setup_email(self): self.mail = Mail(self)
from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_mail import Mail from celery import Celery from flask_login import LoginManager try: from flask_wtf.csrf import CSRFProtect except ImportError: # backward-compatibility from flask_wtf.csrf import CsrfProtect as CSRFProtect from .weblogger import WebLogger from clustermgr.config import Config db = SQLAlchemy() csrf = CSRFProtect() migrate = Migrate() wlogger = WebLogger() celery = Celery('clustermgr.application', backend=Config.CELERY_RESULT_BACKEND, broker=Config.CELERY_BROKER_URL) login_manager = LoginManager() mailer = Mail()
def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'), ) app.secret_key = os.urandom(24) app.config.from_pyfile('config.cfg') app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER mail = Mail(app) S = URLSafeTimedSerializer('dasfegrhrdaUYUHHNJ&@IUJ') # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass # a simple page that says hello @app.route('/hello') def hello(): return 'Hello, World!' @app.route('/register', methods=('GET', 'POST')) def register(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] email = request.form['email'] profile_picture="images/default.png" if 'file' in request.files: file =request.files['file'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(os.getcwd()+"/flaskr/static/images/", filename)) profile_picture=os.path.join(app.config['UPLOAD_FOLDER'], filename) print(profile_picture) else: print ("format not allowed") else: print("no file received") db = get_db() error = None if not username: error = 'Username is required.' elif not password: error = 'Password is required.' elif db.execute( 'SELECT id FROM user WHERE username = ?', (username,) ).fetchone() is not None: error = 'User {} is already registered.'.format(username) elif db.execute( 'SELECT id FROM user WHERE email = ?', (email,) ).fetchone() is not None: error = 'User {} is already registered.'.format(username) if error is None: db.execute( 'INSERT INTO TempUser (username, password, email,profile_picture) VALUES (?, ?, ?, ?)', (username, generate_password_hash(password), email,profile_picture) ) db.commit() token = S.dumps(email, salt='email-confirm') msg = Message('Confirm Email', sender="*****@*****.**", recipients=[email]) link = url_for('confirm_mail', token=token, _external=True) msg.body = 'Your Authentication link is : {}'.format(link) mail.send(msg) flash('Registration is successful. Please check your email for verification link.') return render_template('auth/login.html') flash(error) return render_template('auth/register.html') @app.route('/confirm/<token>') def confirm_mail(token): try: email = S.loads(token, salt='email-confirm', max_age=3600) # users.email_confirmation(email) # TODO: move user from TempUser to user db=get_db() user = db.execute( 'SELECT username, password, email,profile_picture FROM TempUser where email = ?',(email,)).fetchall() print(user[0]) db.execute( 'INSERT INTO user (username, password, email,profile_picture) VALUES (?, ?, ?, ?)', (user[0][0], user[0][1], user[0][2],user[0][3]) ) db.commit() db.execute('DELETE from TempUser where email = ?',(email,)) db.commit() return "Email confirmed." # return redirect(url_for(login')) except SignatureExpired: return "<h3> Token Expired !<h3>" @app.route('/tags') def get_tags(): page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page') db=get_db() tagdata = db.execute('SELECT * from TagDescription').fetchall() posts = tagdata total=len(posts) pagination_posts = get_posts(offset=offset, per_page=per_page,posts=posts) pagination = Pagination(page=page, per_page=per_page, total=total, css_framework='bootstrap4') return render_template('question/tags.html',posts=pagination_posts, page=page, per_page=per_page, pagination=pagination,) @app.errorhandler(404) def page_not_found(e): return render_template('auth/404.html'), 404 from . import db db.init_app(app) from . import auth app.register_blueprint(auth.bp) from . import question app.register_blueprint(question.bp) app.add_url_rule('/', endpoint='index') return app
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_bcrypt import Bcrypt from flask_login import LoginManager from flask_mail import Mail from kombu.utils.url import safequote application = Flask(__name__) application.config['SECRET_KEY'] = '5791628bb0b13ce0c676dfde280ba245' application.config['SQLALCHEMY_DATABASE_URI']='sqlite:///site.db' #application.config['SQLALCHEMY_TRACK_MODIFICATIONS']=True db=SQLAlchemy(application) bcrypt =Bcrypt(application) login_manager=LoginManager(application) login_manager.login_view='login' #setting the route to login login_manager.login_message_category='info' application.config['MAIL_SERVER']='smtp.googlemail.com' application.config['MAIL_USE_TLS']=587 application.config['MAIL_USERNAME']='******' application.config['MAIL_PASSWORD']='******' mail=Mail(application) from THAT import routes
from flask_bootstrap import Bootstrap from config import config_options, Config from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_uploads import UploadSet,configure_uploads,IMAGES from flask_mail import Mail from flask_simplemde import SimpleMDE login_manager = LoginManager() login_manager.session_protection = 'strong' login_manager.login_view = 'auth.login' bootstrap = Bootstrap() db = SQLAlchemy() photos = UploadSet('photos',IMAGES) mail = Mail() simple = SimpleMDE() def create_app(config_name): app = Flask(__name__) # Creating the app configurations 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.init_app(app) simple.init_app(app)
from werkzeug.contrib.cache import MemcachedCache app = Flask(__name__) app.config.from_pyfile('../config.py') # Bootstrap bootstrap = Bootstrap(app) # Cache cache = MemcachedCache(['127.0.0.1:11211']) # SimpleAuth basic_auth = BasicAuth(app) #Mail mail = Mail(app) db = SQLAlchemy(app) from models import * from forms import * import sources app.config['REGION_DATA'] = {} for region_id, region_data in app.config['REGIONS'].iteritems(): if 'parent' in region_data: app.config['REGION_DATA'][region_data['parent']]['children'][region_id] = region_data else: app.config['REGION_DATA'][region_id] = region_data app.config['REGION_DATA'][region_id]['children'] = {} import webapp.views
def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( SECRET_KEY='dev', DATABASE=os.path.join(app.instance_path, 'yeabackend.sqlite'), ) app.config['JWT_ACCESS_TOKEN_EXPIRES'] = ACCESS_EXPIRES app.config['JWT_BLACKLIST_ENABLED'] = True app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access'] CORS(app) jwt = JWTManager(app) # Create our function to check if a token has been blacklisted. In this simple # case, we will just store the tokens jti (unique identifier) in redis # whenever we create a new token (with the revoked status being 'false'). This # function will return the revoked status of a token. If a token doesn't # exist in this store, we don't know where it came from (as we are adding newly # created tokens to our store with a revoked status of 'false'). In this case # we will consider the token to be revoked, for safety purposes. @jwt.token_in_blacklist_loader def check_if_token_is_revoked(decrypted_token): jti = decrypted_token['jti'] entry = revoked_store.get(jti) if entry is None: return True return entry == 'true' 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 = Mail() mail.init_app(app) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass from . import db db.init_app(app) from . import auth app.register_blueprint(auth.bp) from . import location app.register_blueprint(location.bp) from . import check app.register_blueprint(check.bp) from . import data app.register_blueprint(data.bp) from . import inform app.register_blueprint(inform.bp) from . import admin app.register_blueprint(admin.bp) @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def catch_all(path): return app.send_static_file("index.html") return app
import logging from flask import Flask from flask_mail import Mail from flask_security import Security, MongoEngineUserDatastore, user_confirmed # Create app app = Flask(__name__) app.config.from_pyfile('configs.py') from user_management.forms import ExtendedRegisterForm from user_management.models import db, User, Role, Tenant from user_management.signal_callbacks import user_confirmed_callback # Setup Flask-Mail Mail(app) # Setup MongoEngine db.init_app(app) # Setup Flask-Security user_datastore = MongoEngineUserDatastore(db, User, Role) security = Security(app, user_datastore, register_form=ExtendedRegisterForm, confirm_register_form=ExtendedRegisterForm) user_confirmed.connect(user_confirmed_callback, app) # Logging handler = logging.FileHandler('rw-um.log') handler.setLevel(logging.DEBUG) # only log errors and above app.logger.addHandler(handler) # attach the handler to the app's logger import user_management.views
from flask import Flask from flask_mail import Mail, Message import os # instantiate flask app app = Flask(__name__) # set configuration and instantiate mail mail_settings = { "MAIL_SERVER": 'smtp.office365.com', "MAIL_PORT": 587, "MAIL_USE_TLS": True, "MAIL_USE_SSL": False, "MAIL_USERNAME": '******', "MAIL_PASSWORD": os.environ['EMAIL_PASSWORD'] } app.config.update(mail_settings) mail = Mail(app) # create message msg = Message(subject='test', sender='*****@*****.**', recipients='*****@*****.**', body='Hello World') # change message ID # msg.msgId = msg.msgId.split('@')[0] + '@short_string' # for instance your domain name # send email mail.send(msg)
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_admin import Admin from flask_login import LoginManager from flask_mail import Mail app = Flask(__name__) app.config['SECRET_KEY'] = 'hdjkfhuiy12ui3y12783yhjskbdks' app.config[ 'SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456789@localhost/airlinedb?charset=utf8mb4' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True app.config['ROOT_PROJECT_PATH'] = app.root_path app.config['MAIL_SERVER'] = 'smtp.gmail.com' app.config['MAIL_PORT'] = 465 app.config['MAIL_USERNAME'] = '******' app.config['MAIL_PASSWORD'] = '******' app.config['MAIL_USE_TLS'] = False app.config['MAIL_USE_SSL'] = True mail = Mail(app=app) db = SQLAlchemy(app=app) ad = Admin(app=app, name="Bán vé chuyến bay", template_mode="Bootstrap4") login = LoginManager(app=app)
def defaultHandler(err): response = err.get_response() print('response', err, err.get_response()) response.data = dumps({ "code": err.code, "name": "System Error", "message": err.get_description(), }) response.content_type = 'application/json' return response APP = Flask(__name__) mail = Mail(APP) CORS(APP) APP.config['TRAP_HTTP_EXCEPTIONS'] = True APP.register_error_handler(Exception, defaultHandler) APP.config['MAIL_SERVER'] = 'smtp.gmail.com' APP.config['MAIL_PORT'] = 465 APP.config['MAIL_USERNAME'] = '******' APP.config['MAIL_PASSWORD'] = '******' APP.config['MAIL_USE_TLS'] = False APP.config['MAIL_USE_SSL'] = True mail = Mail(APP) # Example
#SQLPART mysql = MySQL() app.secret_key = 'rootpasswordgiven' app.config['MYSQL_DATABASE_USER'] = '******' app.config['MYSQL_DATABASE_PASSWORD'] = '******' app.config['MYSQL_DATABASE_DB'] = 'test' app.config['MYSQL_DATABASE_HOST'] = 'localhost' mysql.init_app(app) #MONGOPART app.config["MONGO_URI"] = "mongodb://*****:*****@app.route("/home", methods = [ 'GET' , 'POST' ]) def home(): if 'username' in session: return render_template('start.html') @app.route('/', methods=['GET', 'POST']) def login():
def __init__(self, to: str = None): app.config.from_pyfile('config.cfg') self.mail = Mail(app) self.s = URLSafeTimedSerializer(app.config['SECRET_KEY']) self.sender = '*****@*****.**' self.to = to
# Built-in modules import os # import ssl app = Flask(__name__) # Initialize Flask # Configure Mail app.config['MAIL_SERVER'] = 'smtp.gmail.com' app.config['MAIL_PORT'] = 465 app.config['MAIL_USE_SSL'] = True app.config['MAIL_USE_TLS'] = False app.config['MAIL_USERNAME'] = str(os.environ.get('MAIL_USERNAME')) app.config['MAIL_PASSWORD'] = str(os.environ.get('MAIL_PASSWORD')) app.config['MAIL_MAX_EMAILS'] = 1000 mail = Mail(app) # Instantiate Mail into app # Configure Flask Compress app.config['COMPRESS_MIMETYPES'] = ['text/html','text/css', 'text/javascript', 'application/javascript', 'application/json', 'application/vnd.ms-fontobject','font/ttf', 'image/svg+xml', 'application/font-sfnt','font/woff2', 'font/woff',] Compress(app) # Instantiate Compress into app # Security measures @app.after_request def apply_headers(response): compression = request.headers["Accept-Encoding"] algorithm = x if (x:='br') in compression else 'gzip' app.config['COMPRESS_ALGORITHM'] = algorithm # configure compress algorithm
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() # 数据库 from flask_bootstrap import Bootstrap bootstrap = Bootstrap() # 蓝本 from flask_login import LoginManager login_manager = LoginManager() from flask_mail import Mail mail = Mail() # 邮件 from flask_moment import Moment moment = Moment() from flask_admin import Admin admin = Admin() from flask_babelex import Babel babel = Babel()
ipa_admin = IPAAdmin(app) # Theme support themename = app.config.get('THEME') blueprint = Blueprint( 'theme', __name__, static_url_path='/theme/static', static_folder="themes/" + themename + "/static/", template_folder="themes/" + themename + "/templates/", ) app.register_blueprint(blueprint) app.register_blueprint(healthz, url_prefix="/healthz") # Flask-Mail mailer = Mail(app) # i18n babel = Babel(app) @babel.localeselector def get_locale(): return request.accept_languages.best_match(LANGUAGES) # Catch IPA errors IPAErrorHandler(app, "ipa_error.html") # Whitenoise for static files app.wsgi_app = WhiteNoise(app.wsgi_app,
from flask_sqlalchemy import SQLAlchemy from flask_restplus import Api from flask_mail import Mail from flask_qrcode import QRcode db: SQLAlchemy = SQLAlchemy() mail: Mail = Mail() api: Api = Api(version='1.0', title="smarttickets", description="application programming interface of smarttickets", authorizations={ "token": { "type": "apiKey", "in": "header", "name": "Token" } }, doc='/swagger/') qrcode: QRcode = QRcode()
from imp import reload import datetime import basic reload(basic) from basic import public db, ATTACH_ROOT = public.db, public.ATTACH_ROOT app.config['MAIL_SERVER'] = '' app.config['MAIL_PORT'] = 994 app.config['MAIL_USE_SSL'] = True app.config['MAIL_DEBUG'] = True app.config['MAIL_DEFAULT_SENDER'] = '' app.config['MAIL_USERNAME'] = '' app.config['MAIL_PASSWORD'] = "" mails = Mail(app) @c.task def silk_mp3(): sql = """select p.id,p.audio from post_future p where COALESCE(p.tomp3,0)=0 and COALESCE(p.audio_flag,0)=0""" l, t = db.select(sql) if t > 0: with app.app_context(): for i in l: id, audio = i[0], i[1] mp3 = audio.split('.')[0] + '.mp3' path = os.path.join(ATTACH_ROOT, audio)
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_login import LoginManager #引用login from flask_mail import Mail #发送邮件的引用 from gonghui.config import Config db = SQLAlchemy() migrate = Migrate() login_manager = LoginManager() #login关联 login_manager.login_view = 'login' #强制登录的重定向设置 mail = Mail() #关联发送邮件 from gonghui.route import index,login,logout,manageruser,register,password_reset_request,\ password_reset,account_add,account_query,condolence,condolence_add,test,page_not_found,member_manager,\ membership_list,membership_roster,buju,accounts def create_app(): app = Flask(__name__) app.config.from_object(Config) db.init_app(app) migrate.init_app(app,db) login_manager.init_app(app) #login与app关联 mail.init_app(app) #login与app关联 app.add_url_rule('/index','index',index) app.add_url_rule('/','index',index) app.add_url_rule('/login','login',login,methods=['GET','POST']) app.add_url_rule('/logout','logout',logout) app.add_url_rule('/manageruser','manageruser',manageruser) app.add_url_rule('/register','register',register,methods=['GET','POST']) app.add_url_rule('/password_reset_request','password_reset_request',password_reset_request,methods=['GET','POST'])
def create_app(app_name=None): # Configuration settings import config if not app_name: app_name = config.APP_NAME # Only enable password related functionality in server mode. if config.SERVER_MODE is True: # Some times we need to access these config params where application # context is not available (we can't use current_app.config in those # cases even with current_app.app_context()) # So update these params in config itself. # And also these updated config values will picked up by application # since we are updating config before the application instance is # created. config.SECURITY_RECOVERABLE = True config.SECURITY_CHANGEABLE = True # Now we'll open change password page in alertify dialog # we don't want it to redirect to main page after password # change operation so we will open the same password change page again. config.SECURITY_POST_CHANGE_VIEW = 'browser.change_password' """Create the Flask application, startup logging and dynamically load additional modules (blueprints) that are found in this directory.""" app = PgAdmin(__name__, static_url_path='/static') # Removes unwanted whitespace from render_template function app.jinja_env.trim_blocks = True app.config.from_object(config) app.config.update(dict(PROPAGATE_EXCEPTIONS=True)) ########################################################################## # Setup logging and log the application startup ########################################################################## # Add SQL level logging, and set the base logging level logging.addLevelName(25, 'SQL') app.logger.setLevel(logging.DEBUG) app.logger.handlers = [] # We also need to update the handler on the webserver in order to see # request. Setting the level prevents werkzeug from setting up it's own # stream handler thus ensuring all the logging goes through the pgAdmin # logger. logger = logging.getLogger('werkzeug') logger.setLevel(logging.INFO) # Set SQLITE_PATH to TEST_SQLITE_PATH while running test cases if ('PGADMIN_TESTING_MODE' in os.environ and os.environ['PGADMIN_TESTING_MODE'] == '1'): config.SQLITE_PATH = config.TEST_SQLITE_PATH # Ensure the various working directories exist from pgadmin.setup import create_app_data_directory, db_upgrade create_app_data_directory(config) # File logging fh = logging.FileHandler(config.LOG_FILE, encoding='utf-8') fh.setLevel(config.FILE_LOG_LEVEL) fh.setFormatter(logging.Formatter(config.FILE_LOG_FORMAT)) app.logger.addHandler(fh) logger.addHandler(fh) # Console logging ch = logging.StreamHandler() ch.setLevel(config.CONSOLE_LOG_LEVEL) ch.setFormatter(logging.Formatter(config.CONSOLE_LOG_FORMAT)) app.logger.addHandler(ch) logger.addHandler(ch) # Log the startup app.logger.info('########################################################') app.logger.info('Starting %s v%s...', config.APP_NAME, config.APP_VERSION) app.logger.info('########################################################') app.logger.debug("Python syspath: %s", sys.path) ########################################################################## # Setup i18n ########################################################################## # Initialise i18n babel = Babel(app) app.logger.debug('Available translations: %s' % babel.list_translations()) @babel.localeselector def get_locale(): """Get the language for the user.""" language = 'en' if config.SERVER_MODE is False: # Get the user language preference from the miscellaneous module if current_user.is_authenticated: user_id = current_user.id else: user = user_datastore.get_user(config.DESKTOP_USER) if user is not None: user_id = user.id user_language = Preferences.raw_value('miscellaneous', 'user_language', None, user_id) if user_language is not None: language = user_language else: # If language is available in get request then return the same # otherwise check the session or cookie data = request.form if 'language' in data: language = data['language'] or language setattr(session, 'PGADMIN_LANGUAGE', language) elif hasattr(session, 'PGADMIN_LANGUAGE'): language = getattr(session, 'PGADMIN_LANGUAGE', language) elif hasattr(request.cookies, 'PGADMIN_LANGUAGE'): language = getattr(request.cookies, 'PGADMIN_LANGUAGE', language) return language ########################################################################## # Setup authentication ########################################################################## app.config['SQLALCHEMY_DATABASE_URI'] = u'sqlite:///{0}?timeout={1}' \ .format(config.SQLITE_PATH.replace(u'\\', u'/'), getattr(config, 'SQLITE_TIMEOUT', 500) ) # Create database connection object and mailer db.init_app(app) ########################################################################## # Upgrade the schema (if required) ########################################################################## with app.app_context(): # Run migration for the first time i.e. create database from config import SQLITE_PATH if not os.path.exists(SQLITE_PATH): db_upgrade(app) else: version = Version.query.filter_by(name='ConfigDB').first() schema_version = version.value # Run migration if current schema version is greater than the # schema version stored in version table if CURRENT_SCHEMA_VERSION >= schema_version: db_upgrade(app) # Update schema version to the latest if CURRENT_SCHEMA_VERSION > schema_version: version = Version.query.filter_by(name='ConfigDB').first() version.value = CURRENT_SCHEMA_VERSION db.session.commit() Mail(app) import pgadmin.utils.paths as paths paths.init_app(app) # Setup Flask-Security user_datastore = SQLAlchemyUserDatastore(db, User, Role) security = Security(None, user_datastore) ########################################################################## # Setup security ########################################################################## with app.app_context(): config.CSRF_SESSION_KEY = Keys.query.filter_by( name='CSRF_SESSION_KEY').first().value config.SECRET_KEY = Keys.query.filter_by( name='SECRET_KEY').first().value config.SECURITY_PASSWORD_SALT = Keys.query.filter_by( name='SECURITY_PASSWORD_SALT').first().value # Update the app.config with proper security keyes for signing CSRF data, # signing cookies, and the SALT for hashing the passwords. app.config.update( dict({ 'CSRF_SESSION_KEY': config.CSRF_SESSION_KEY, 'SECRET_KEY': config.SECRET_KEY, 'SECURITY_PASSWORD_SALT': config.SECURITY_PASSWORD_SALT })) security.init_app(app, user_datastore) # register custom unauthorised handler. app.login_manager.unauthorized_handler(pga_unauthorised) app.session_interface = create_session_interface(app) # Make the Session more secure against XSS & CSRF when running in web mode if config.SERVER_MODE: paranoid = Paranoid(app) paranoid.redirect_view = 'browser.index' ########################################################################## # Load all available server drivers ########################################################################## driver.init_app(app) ########################################################################## # Register language to the preferences after login ########################################################################## @user_logged_in.connect_via(app) def register_language(sender, user): # After logged in, set the language in the preferences if we get from # the login page data = request.form if 'language' in data: language = data['language'] # Set the user language preference misc_preference = Preferences.module('miscellaneous') user_languages = misc_preference.preference('user_language') if user_languages and language: language = user_languages.set(language) ########################################################################## # Register any local servers we can discover ########################################################################## @user_logged_in.connect_via(app) def on_user_logged_in(sender, user): # Keep hold of the user ID user_id = user.id # Get the first server group for the user servergroup_id = 1 servergroups = ServerGroup.query.filter_by( user_id=user_id).order_by("id") if servergroups.count() > 0: servergroup = servergroups.first() servergroup_id = servergroup.id '''Add a server to the config database''' def add_server(user_id, servergroup_id, name, superuser, port, discovery_id, comment): # Create a server object if needed, and store it. servers = Server.query.filter_by( user_id=user_id, discovery_id=svr_discovery_id).order_by("id") if servers.count() > 0: return svr = Server(user_id=user_id, servergroup_id=servergroup_id, name=name, host='localhost', port=port, maintenance_db='postgres', username=superuser, ssl_mode='prefer', comment=svr_comment, discovery_id=discovery_id) db.session.add(svr) db.session.commit() # Figure out what servers are present if winreg is not None: arch_keys = set() proc_arch = os.environ['PROCESSOR_ARCHITECTURE'].lower() try: proc_arch64 = os.environ['PROCESSOR_ARCHITEW6432'].lower() except Exception as e: proc_arch64 = None if proc_arch == 'x86' and not proc_arch64: arch_keys.add(0) elif proc_arch == 'x86' or proc_arch == 'amd64': arch_keys.add(winreg.KEY_WOW64_32KEY) arch_keys.add(winreg.KEY_WOW64_64KEY) for arch_key in arch_keys: for server_type in ('PostgreSQL', 'EnterpriseDB'): try: root_key = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\" + server_type + "\Services", 0, winreg.KEY_READ | arch_key) for i in xrange(0, winreg.QueryInfoKey(root_key)[0]): inst_id = winreg.EnumKey(root_key, i) inst_key = winreg.OpenKey(root_key, inst_id) svr_name = winreg.QueryValueEx( inst_key, 'Display Name')[0] svr_superuser = winreg.QueryValueEx( inst_key, 'Database Superuser')[0] svr_port = winreg.QueryValueEx(inst_key, 'Port')[0] svr_discovery_id = inst_id svr_comment = gettext( "Auto-detected %s installation with the data " "directory at %s" % (winreg.QueryValueEx(inst_key, 'Display Name')[0], winreg.QueryValueEx(inst_key, 'Data Directory')[0])) add_server(user_id, servergroup_id, svr_name, svr_superuser, svr_port, svr_discovery_id, svr_comment) inst_key.Close() except Exception as e: pass else: # We use the postgres-winreg.ini file on non-Windows try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigParser # Python 2 registry = ConfigParser() try: registry.read('/etc/postgres-reg.ini') sections = registry.sections() # Loop the sections, and get the data from any that are PG or PPAS for section in sections: if (section.startswith('PostgreSQL/') or section.startswith('EnterpriseDB/')): svr_name = registry.get(section, 'Description') svr_superuser = registry.get(section, 'Superuser') svr_port = registry.getint(section, 'Port') svr_discovery_id = section description = registry.get(section, 'Description') data_directory = registry.get(section, 'DataDirectory') if hasattr(str, 'decode'): description = description.decode('utf-8') data_directory = data_directory.decode('utf-8') svr_comment = gettext(u"Auto-detected %s installation " u"with the data directory at %s" % (description, data_directory)) add_server(user_id, servergroup_id, svr_name, svr_superuser, svr_port, svr_discovery_id, svr_comment) except Exception as e: pass @user_logged_in.connect_via(app) @user_logged_out.connect_via(app) def force_session_write(app, user): session.force_write = True ########################################################################## # Load plugin modules ########################################################################## for module in app.find_submodules('pgadmin'): app.logger.info('Registering blueprint module: %s' % module) app.register_blueprint(module) ########################################################################## # Handle the desktop login ########################################################################## @app.before_request def before_request(): """Login the default user if running in desktop mode""" # Check the auth key is valid, if it's set, and we're not in server # mode, and it's not a help file request. if not config.SERVER_MODE and app.PGADMIN_KEY != '': if (('key' not in request.args or request.args['key'] != app.PGADMIN_KEY) and request.cookies.get('PGADMIN_KEY') != app.PGADMIN_KEY and request.endpoint != 'help.static'): abort(401) if not config.SERVER_MODE and not current_user.is_authenticated: user = user_datastore.get_user(config.DESKTOP_USER) # Throw an error if we failed to find the desktop user, to give # the sysadmin a hint. We'll continue to try to login anyway as # that'll through a nice 500 error for us. if user is None: app.logger.error( 'The desktop user %s was not found in the configuration ' 'database.' % config.DESKTOP_USER) abort(401) login_user(user) @app.after_request def after_request(response): if 'key' in request.args: response.set_cookie('PGADMIN_KEY', value=request.args['key']) return response ########################################################################## # Minify output ########################################################################## # HTMLMIN doesn't work with Python 2.6. if not config.DEBUG and sys.version_info >= (2, 7): from flask_htmlmin import HTMLMIN HTMLMIN(app) @app.context_processor def inject_blueprint(): """Inject a reference to the current blueprint, if any.""" return { 'current_app': current_app, 'current_blueprint': current_blueprint } ########################################################################## # All done! ########################################################################## return app
# Richard Darst, April 2015 import datetime from flask import Flask #from flask.ext.sqlalchemy import SQLAlchemy from flask_sqlalchemy import SQLAlchemy from flask_mail import Mail from flask_user import login_required, UserManager, UserMixin, SQLAlchemyAdapter from config import app db = SQLAlchemy(app) mail = Mail(app) # Initialize Flask-Mail class User(db.Model, UserMixin): __tablename__ = 'user' uid = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(50), nullable=False, unique=True) password = db.Column(db.String(255), nullable=False, server_default='') reset_password_token = db.Column(db.String(100), nullable=False, server_default='') # User email information email = db.Column(db.String(255), nullable=False, unique=True) confirmed_at = db.Column(db.DateTime()) # User information active = db.Column('is_active',
from flask_mail import Mail from flask_migrate import Migrate from flask_login import LoginManager from .config import Config import os SESSION_TYPE = 'memcache' fapp = Flask(__name__) fapp.config.from_object(Config) login = LoginManager(fapp) login.login_view = 'login' db = SQLAlchemy(fapp) migrate = Migrate(fapp, db) mail = Mail(fapp) from app import routes, models, errors if not fapp.debug: if fapp.config['MAIL_SERVER']: auth = None if fapp.config['MAIL_USERNAME'] or fapp.config['MAIL_PASSWORD']: auth = (fapp.config['MAIL_USERNAME'], fapp.config['MAIL_PASSWORD']) secure = None if fapp.config['MAIL_USE_TLS']: secure = () mail_handler = SMTPHandler(
app.config['MAIL_USE_TLS'] = True app.config['MAIL_USERNAME'] = "******" app.config['MAIL_PASSWORD'] = "******" #app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME') # TODO export to your environs -- may want a new account just for this. It's expecting gmail, not umich #app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD') app.config['MAIL_SUBJECT_PREFIX'] = '[Songs App]' app.config['MAIL_SENDER'] = 'Admin <*****@*****.**>' # TODO fill in email #app.config['ADMIN'] = os.environ.get('ADMIN') app.config['ADMIN'] = "*****@*****.**" # Set up Flask debug stuff manager = Manager(app) db = SQLAlchemy(app) # For database use migrate = Migrate(app, db) # For database use/updating manager.add_command('db', MigrateCommand) # Add migrate mail = Mail(app) # For email sending # TODO: Run commands to create your migrations folder and get ready to create a first migration, as shown in the textbook and in class. ## Set up Shell context so it's easy to use the shell to debug def make_shell_context(): return dict(app=app, db=db, Tweet=Tweet, User=User, Hashtag=Hashtag) # Add function use to manager manager.add_command("shell", Shell(make_context=make_shell_context)) # TODO: Write a send_email function here. (As shown in examples.) def send_email(app, msg): with app.app_context(): mail.send(msg) def send_new_email(to, subject, template, **kwargs): # kwargs = 'keyword arguments', this syntax means to unpack any keyword arguments into the function in the invocation...
def __init__(self): self.mail = Mail(current_app)