Example #1
0
def test_send_email():
    mailForm= MailForm()
    if mailForm.validate_on_submit():#表单提交成功的判断
        try:
            app = Flask(__name__)
            app.config['SECRET_KEY'] = 'qiyeboy'
            #下面是SMTP服务器配置
            app.config['MAIL_SERVER'] = 'smtp.163.com' #电子邮件服务器的主机名或IP地址
            app.config['MAIL_PORT'] = '25' #电子邮件服务器的端口
            app.config['MAIL_USE_TLS'] = True #启用传输层安全
            app.config['MAIL_USERNAME'] ='13259744109@163.com' #os.environ.get('MAIL_USERNAME') #邮件账户用户名
            app.config['MAIL_PASSWORD'] = 'hywd1993'#os.environ.get('MAIL_PASSWORD') #邮件账户的密码

            mail = Mail(app)
            receiverName = mailForm.receiver.data #收件人文本框的内容
            styledata = mailForm.style.data#主题文本框的内容
            bodydata  = mailForm.body.data#正文文本框的内容
            msg = Message(styledata,sender='13259744109@163.com',recipients=[receiverName])#发件人,收件人
            msg.body = bodydata
            # send_email('2531145412@qq.com','Test email-function',)
            mail.send(msg)
            flash('邮件发送成功!')#提示信息
            return redirect(url_for('.index'))
        except:
            flash('邮件发送失败!')
            return redirect(url_for('.index'))
    return render_template('testemail.html',form=mailForm,name ='13259744109@163.com' )#渲染网页



# @main.route('/secret')
# @login_required
# def secret():
#     return 'Only authenticated users are allowed!'
Example #2
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(Conf)
    print('create_app')
    # redis
    app.redis_store = redis.Redis(host=app.config["REDIS_HOST"], port=app.config["REDIS_PORT"], decode_responses=True)

    app.config['SQLALCHEMY_DATABASE_URI'] = Conf.MYSQL_INFO
    app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    # Mail
    app.config['MAIL_SERVER'] = Conf.MAIL_SERVER
    app.config['MAIL_PORT'] = Conf.MAIL_PORT
    app.config['MAIL_USE_TLS'] = Conf.MAIL_USE_TLS


    # 蓝图
    from app.admin import admin_api as admin_api_blueprint
    app.register_blueprint(admin_api_blueprint, url_prefix='/api/admin')

    from app.api.v1_0_0 import api_v1_0_0 as api_1_0_blueprint
    app.register_blueprint(api_1_0_blueprint, url_prefix='/api/v1.0.0')

    from app.api.v1_0_1 import api_v1_0_1 as api_1_1_blueprint
    app.register_blueprint(api_1_1_blueprint, url_prefix='/api/v1.0.1')

    # init
    db.init_app(app)
    return app
Example #3
0
	def create_app():

		global db, bootstrap, mail, login_manager, moment, pagedown
		app = Flask(__name__)

		from main import main as main_blueprint
		from auth import auth as auth_blueprint
		from admin import admin as admin_blueprint

		app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://flask:gf37888676@172.17.0.25/flask'
		app.config['SQLAlCHEMY_COMMIT_ON_TEARDOWN'] = True
		app.config['FLASK_ADMIN'] = 'iamawar3player@163.com'
		app.config['FLASK_MAIL_SUBJECT_PREFIX'] = '[Flasky]'
		app.config['FLASK_MAIL_SENDER'] = 'Flasky Admin <iamawar3player@163.com>'
		app.config['MAIL_SERVER'] = 'smtp.163.com'
		app.config['MAIL_PORT'] = 25
		app.config['MAIL_USE_TLS'] = False
		app.config['MAIL_USERNAME'] = 'iamawar3player@163.com'
		app.config['MAIL_PASSWORD'] = 'fan86797121'
		app.config['DEBUG'] = True
		app.config['FLASKY_POSTS_PER_PAGE'] = 10
		app.config['SECRET_KEY'] = 'gf37888676'
		app.register_blueprint(main_blueprint)
		app.register_blueprint(auth_blueprint, url_prefix='/auth')
		app.register_blueprint(admin_blueprint, url_prefix='/admin')

		db = db.init_app(app)
		mail = mail.init_app(app)
		bootstrap = bootstrap.init_app(app)
		login_manager = login_manager.init_app(app)
		moment = moment.init_app(app)
		pagedown = pagedown.init_app(app)

		return app
Example #4
0
def create_app():
    app = Flask(__name__)
    app.config.update(
        CELERY_BROKER_URL='redis://localhost:6379/0',
        CELERY_RESULT_BACKEND='redis://localhost:6379/0'
    )
    app.config['MAIL_SERVER'] = 'smtp.gmail.com'
    app.config['MAIL_PORT'] = 587
    app.config['MAIL_USE_TLS'] = True
    app.config['MAIL_USERNAME'] = admin_imap
    app.config['MAIL_PASSWORD'] = admin_pass
    app.config['MAIL_DEFAULT_SENDER'] = 'server-error@example.com'

    return app
Example #5
0
    database_url = os.environ["DATABASE_URL"]

app.config['SQLALCHEMY_DATABASE_URI'] = database_url
app.config['GCLIENT_ID'] = os.environ['GCLIENT_ID']
app.config['GCLIENT_SECRET'] = os.environ['GCLIENT_SECRET']
app.config['DATE_FORMAT'] = '%Y-%m-%d'
app.config['PAGE_SIZE'] = os.environ.get('PAGE_SIZE', '20')
app.config['URL_ROOT'] = os.environ['URL_ROOT']
app.config['HASH_KEY'] = os.environ['HASH_KEY']

# Mail setup
app.config['EMAIL_FROM'] = os.environ.get("EMAIL_FROM", "portal@example.com")
app.config['MAIL_SERVER'] = os.environ.get("MAIL_SERVER", "smtp.gmail.com")
app.config['MAIL_SERVER_IMAP'] = os.environ.get(
    "MAIL_SERVER_IMAP", "imap.gmail.com")
app.config['MAIL_PORT'] = os.environ.get("MAIL_PORT", 25)
app.config['MAIL_PORT_IMAP'] = os.environ.get("MAIL_PORT_IMAP", 993)
app.config['MAIL_USERNAME'] = os.environ.get("MAIL_USERNAME")
app.config['MAIL_PASSWORD'] = os.environ.get("MAIL_PASSWORD")
if os.environ.get("MAIL_USE_TLS") == "True":
    app.config['MAIL_USE_TLS'] = True
if os.environ.get("MAIL_USE_SSL") == "True":
    app.config['MAIL_USE_SSL'] = True

app.config['FILESTORE_URL'] = os.environ.get("FILESTORE_URL")
app.config['FILESTORE_SITE'] = os.environ.get("FILESTORE_SITE")
app.config['FILESTORE_USER'] = os.environ.get("FILESTORE_USER")
app.config['FILESTORE_PASSWORD'] = os.environ.get("FILESTORE_PASSWORD")

app.debug = True if os.environ.get("DEBUG", False) else False
Example #6
0
from flask.ext.mail import Mail
from flask.ext.mail import Message


config = configparser.ConfigParser()
config.readfp(codecs.open("../config/config.ini", "r", "utf-8"))

app = Flask(__name__)

app.config['HEADERS'] = {'Referer': 'http://music.163.com'}
app.config['OFFSET'] = 0
app.config['LIMIT'] = 100
app.config['JSON_AS_ASCII'] = False

app.config['MAIL_SERVER'] = config['MAIL']['SERVER']
app.config['MAIL_PORT'] = int(config['MAIL']['PORT'])
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = config['MAIL']['USERNAME']
app.config['MAIL_PASSWORD'] = config['MAIL']['PASSWORD']

mail = Mail(app)


"""
API website template related
"""

@app.route('/', methods=['GET'])
def host():
	return redirect('/v1')
Example #7
0
# services
SERVICE_POD = "pod"
SERVICE_TLP = "tlp"
SERVICES = [SERVICE_POD, SERVICE_TLP]

# models
MODELS_POD_OCR = "ocr"
MODELS_POD_BAYES_SPAM = "bayes_spam"
MODELS_POD_FACE_DETECT = "face_detect"
MODELS = [MODELS_POD_OCR, MODELS_POD_BAYES_SPAM, MODELS_POD_FACE_DETECT]


# mail settings
PRAXYK_API_APP.config['MAIL_SERVER']   = 'smtp.googlemail.com'
PRAXYK_API_APP.config['MAIL_PORT']     = 587
PRAXYK_API_APP.config['MAIL_USE_TLS']  = True
PRAXYK_API_APP.config['MAIL_USE_SSL']  = False
# gmail authentication
PRAXYK_API_APP.config['MAIL_USERNAME'] = apiconf['email']
PRAXYK_API_APP.config['MAIL_PASSWORD'] = apiconf['emailpassword']

mail = Mail(PRAXYK_API_APP)

# mail accounts
PRAXYK_API_APP.config['MAIL_DEFAULT_SENDER'] = 'from@example.com'

# default access token expiration time (24 hours)
TOKEN_EXPIRATION = apiconf['token_expiration']

Example #8
0
# This program is used for testing flask-mail extension .
# something wrong in my app, so I must learn how to use this extension .
# password nwntuhwdkrrbbbbe

from flask import Flask
from flask_mail import Mail, Message
from flask_script import Manager
app = Flask(__name__)

app.config['MAIL_SERVER'] = 'smtp.qq.com'
app.config['MAIL_PORT'] = '25'
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USE_SSL'] = False
app.config['MAIL_USERNAME'] = '80551xx'
app.config['MAIL_PASSWORD'] = 'nwntuhwdkrrbbbbe'
app.config['FLASKY_MAIL_SENDER'] = "80551xx@qq.com"

mail = Mail(app)
manager = Manager(app)


@app.route('/')
def index():
    msg = Message('subject', sender=app.config['FLASKY_MAIL_SENDER'], recipients=['228787xx@qq.com'])
    msg.body = 'body'
    msg.html = '<b>HTML</b> body'
    mail.send(msg)

    return '<h1>Sent successfully</h1>'

if __name__ == "__main__":
Example #9
0
from forms import ContactForm
from wsgi import ReverseProxied
from ConfigParser import RawConfigParser
import os
import re

CONFIG_ENV = 'CONTACT_POTION_CONFIG'

config_filename = os.getenv(CONFIG_ENV, 'sample.config')
config = RawConfigParser()
config.read(config_filename)

app = Flask(__name__)
app.secret_key = config.get('GLOBAL', 'secret_key')
app.config['MAIL_SERVER'] = config.get('GLOBAL', 'mailserver')
app.config['MAIL_PORT'] = config.getint('GLOBAL', 'mailport')
app.config['MAIL_USE_SSL'] = config.getboolean('GLOBAL', 'mailusessl')
app.config['MAIL_USERNAME'] = config.getint('GLOBAL', 'username')
app.config['MAIL_PASSWORD'] = config.getboolean('GLOBAL', 'password')

mail = Mail()
mail.init_app(app)

app.wsgi_app = ReverseProxied(app.wsgi_app)

@app.route('/', methods=['GET', 'POST'])
def contact():
    request_config = get_request_config()
    form = ContactForm()
    form.category.choices = ((choice, choice)
                             for choice in request_config['categories'])
Example #10
0
# Define the database object which is imported
# by modules and controllers
# --------------------------------------------
app.config['SQLALCHEMY_DATABASE_URI'] = app.config['CLOUD_SESSION_PROPERTIES']['database.url']
logging.debug("Initializing database connection: %s", app.config['SQLALCHEMY_DATABASE_URI'])

db = SQLAlchemy(app)


app.config['MAIL_SERVER'] = app.config['CLOUD_SESSION_PROPERTIES']['mail.host']
logging.debug("Configuring SMTP properties for %s", app.config['MAIL_SERVER'])

# Set the correct server port for encrypted vs unencrypted communications
if app.config['CLOUD_SESSION_PROPERTIES']['mail.port'] is None:
    if app.config['CLOUD_SESSION_PROPERTIES']['mail.tls']:
        app.config['MAIL_PORT'] = 587
    else:
        app.config['MAIL_PORT'] = 25

    logging.info("Email server default port set to port %s", app.config['MAIL_PORT'])
else:
    app.config['MAIL_PORT'] = app.config['CLOUD_SESSION_PROPERTIES']['mail.port']

app.config['MAIL_USE_TLS'] = app.config['CLOUD_SESSION_PROPERTIES']['mail.tls']
app.config['MAIL_USE_SSL'] = app.config['CLOUD_SESSION_PROPERTIES']['mail.ssl']
app.config['MAIL_DEBUG'] = app.config['CLOUD_SESSION_PROPERTIES']['mail.debug']
app.config['MAIL_USERNAME'] = app.config['CLOUD_SESSION_PROPERTIES']['mail.user']
app.config['MAIL_PASSWORD'] = app.config['CLOUD_SESSION_PROPERTIES']['mail.password']
app.config['DEFAULT_MAIL_SENDER'] = app.config['CLOUD_SESSION_PROPERTIES']['mail.from']

Example #11
0
def create_app(testing=False, live=False):
    from bhs_api.models import User, Role
    from bhs_api.forms import LoginForm

    app = Flask(__name__)
    app.testing = testing

    # load the config file
    conf = get_conf()
    app.conf = conf
    # Our config - need to move everything here
    app.config['VIDEO_BUCKET_URL'] = "https://storage.googleapis.com/bhs-movies"
    app.config['IMAGE_BUCKET_URL'] = "https://storage.googleapis.com/bhs-flat-pics"

    # Set app config
    app.config['DEBUG'] = True
    app.config['FRONTEND_SERVER'] = conf.frontend_server
    app.config['DEFAULT_NEXT'] = '/mjs'
    # Security Config
    app.config['SECRET_KEY'] = conf.secret_key
    app.config['WTF_CSRF_ENABLED'] = False
    app.config['SECURITY_PASSWORDLESS'] = True
    app.config['SECURITY_EMAIL_SENDER'] = 'BH Databases<support@bh.org.il>'
    app.config['SECURITY_USER_IDENTITY_ATTRIBUTES'] = 'email'
    app.config['SECURITY_EMAIL_SUBJECT_PASSWORDLESS'] = 'Login link for Your Jewish Story'
    app.config['SECURITY_POST_LOGIN_VIEW'] = '/mjs'
    app.config['SECURITY_USER_IDENTITY_ATTRIBUTES'] = ('email', 'username', 'hash')
    # Mail Config
    app.config['MAIL_SERVER'] = conf.mail_server
    app.config['MAIL_PORT'] = conf.mail_port
    # Mail optional username and password
    try:
        app.config['MAIL_USERNAME'] = conf.mail_username
        app.config['MAIL_PASSWORD'] = conf.mail_password
    except AttributeError:
        pass

    # DB Config
    app.config['MONGODB_DB'] = conf.user_db_name
    app.config['MONGODB_HOST'] = conf.user_db_host
    app.config['MONGODB_PORT'] = conf.user_db_port
    # Redis
    app.config['REDIS_HOST'] = conf.redis_host
    app.config['REDIS_PORT'] = conf.redis_port
    app.config['REDIS_PASSWORD'] = getattr(conf, 'redis_password', None)

    # CACHING
    app.config['CACHING_TTL'] = conf.caching_ttl

    app.mail = Mail(app)
    app.db = MongoEngine(app)
    app.user_datastore = MongoEngineUserDatastore(app.db, User, Role)
    app.security = Security(app, app.user_datastore,
                            passwordless_login_form=LoginForm)
    # Create database connection object
    app.client_data_db = pymongo.MongoClient(conf.data_db_host, conf.data_db_port,
                    read_preference=pymongo.ReadPreference.SECONDARY_PREFERRED)
    app.data_db = app.client_data_db[conf.data_db_name]

    # Create the elasticsearch connection
    app.es = elasticsearch.Elasticsearch(conf.elasticsearch_host)
    app.es_data_db_index_name = getattr(conf, "elasticsearch_data_index", app.data_db.name)

    # Add the user's endpoints
    from bhs_api.user import user_endpoints
    app.register_blueprint(user_endpoints)
    # Add the v1 endpoint
    from bhs_api.v1_endpoints import v1_endpoints
    app.register_blueprint(v1_endpoints, url_prefix='/v1')
    # Initialize autodoc - https://github.com/acoomans/flask-autodoc
    #allow CORS
    cors = CORS(app, origins=['*'], headers=['content-type', 'accept',
                                            'authentication-token', 'Authorization'])
    # logging
    if live:
        app.config['PROPAGATE_EXCEPTIONS'] = True
        try:
            fh = logging.FileHandler(conf.log_file)
            formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
            fh.setFormatter(formatter)
            app.logger.addHandler(fh)
        except AttributeError:
            pass

    # redis
    try:
        app.redis = redis.StrictRedis(host=conf.redis_host,
                                      port=conf.redis_port,
                                      password = app.config['REDIS_PASSWORD'],
                                      db=0)
    except AttributeError:
        app.redis = None

    return app, conf
Example #12
0
        "MAIL_PORT": 587,
        "MAIL_USE_SSL": "True",
        "MAIL_USERNAME": "user@mailserver",
        "MAIL_PASSWORD": "secret"
    }
    with open("config.json","w") as data_file:
        json.dump(tempConfig,data_file)

# Create app
app = Flask(__name__)
myConfig=load_json()
app.config['DEBUG'] = myConfig['DEBUG']
app.config['SECRET_KEY'] = myConfig['SECRET_KEY']
app.config['SQLALCHEMY_DATABASE_URI'] = myConfig['SQLALCHEMY_DATABASE_URI']
app.config['MAIL_SERVER'] = myConfig['MAIL_SERVER']
app.config['MAIL_PORT'] = myConfig['MAIL_PORT']
app.config['MAIL_USE_SSL'] = myConfig['MAIL_USE_SSL']
app.config['MAIL_USERNAME'] = myConfig['MAIL_USERNAME']
app.config['MAIL_PASSWORD'] = myConfig['MAIL_PASSWORD']
mail = Mail(app)
db = SQLAlchemy(app)

# Define models
roles_users = db.Table('roles_users',
        db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
        db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))

class Role(db.Model, RoleMixin):
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(80), unique=True)
    description = db.Column(db.String(255))
Example #13
0
# app.config['PROPAGATE_EXCEPTIONS'] = True

# Forms protection
app.config['CSRF_ENABLED'] = True
app.config['WTF_CSRF_ENABLED'] = True
app.config['SECRET_KEY'] = get_encryption_key()

app.config['STREAM_MAX_TIME'] = 1800
app.config['BASECOLOR'] = BASECOLOR
app.config['WITH_ML_SUBSYSTEM'] = WITH_ML_SUBSYSTEM
app.config['EXTRA_INFO'] = EXTRA_INFO

# Plug-ins: email server
if GMAIL_ACCOUNT and GMAIL_APP_PASSWORD:
    app.config['MAIL_SERVER'] = 'smtp.gmail.com'
    app.config['MAIL_PORT'] = 587  # 465
    app.config['MAIL_USE_TLS'] = True
    app.config['MAIL_USE_TLS'] = True
    app.config['MAIL_USE_SSL'] = False
    app.config['MAIL_USERNAME'] = GMAIL_ACCOUNT
    app.config['MAIL_DEFAULT_SENDER'] = GMAIL_ACCOUNT
    app.config['MAIL_PASSWORD'] = GMAIL_APP_PASSWORD
    mail = Mail(app)
else:
    mail = None
# Plug-ins: API Auto-doc:
auto = Autodoc(app)

# Views
# noinspection PyUnresolvedReferences,PyPep8
from enerpiweb import (views, views_filehandler, utils, rt_stream,
Example #14
0
from flask_wtf import Form
from flask_mail import (Mail, Message)
from flask_sqlalchemy import SQLAlchemy
from wtforms import (StringField, SubmitField)
from wtforms.validators import Required


app = Flask(__name__)

# smtplib mail
import sys
sys.path.append("/data/python/")
import data
# mail headers
app.config['MAIL_SERVER'] = data.MAIL_SERVER
app.config['MAIL_PORT'] = data.MAIL_PORT
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = data.MAIL_USERNAME
app.config['MAIL_PASSWORD'] = data.MAIL_PASSWD
# mail message
app.config['MAIL_SUBJECT'] = "[bamboo web]"
app.config['MAIL_SENDER'] = data.MAIL_USERNAME
app.config['MAIL_ADMIN'] = data.MAIL_ADMIN

# sqlite db
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = \
    'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
Example #15
0
    __delattr__ = dict.__delitem__

# Instanciate config
config = Config()

# Instanciate FLASK
app = Flask(__name__)

# Flask settings
app.config['SESSION_TYPE'] = 'memcached'
app.config['SECRET_KEY'] = config.secret_key
app.config['TAP'] = config

# Setup Mail
app.config['MAIL_SERVER'] = config.mail_host.split(":")[0]
app.config['MAIL_PORT'] = int(config.mail_host.split(":")[1])
app.config['MAIL_USERNAME'] = config.mail_user
app.config['MAIL_PASSWORD'] = config.mail_pass
app.config['MAIL_DEFAULT_SENDER'] = config.mail_from
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USE_SSL'] = False
mail = Mail(app)

# Setup Storage
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///database.db"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

# Setup CORS
cors = CORS(app, resources={r".*/api/v1/.*": {"origins": "*"}})
Example #16
0
from collections import defaultdict
import random
import flask.ext.login as flask_login

# Security sensitive constants are imported from a file not being synced with github
from tpbeta_security import *

app = Flask(__name__)

app.secret_key = tpbeta_app_secret_key

app.config['SQLALCHEMY_DATABASE_URI'] = tpbeta_sqlalchemy_db_uri
app.config['SQLALCHEMY_POOL_RECYCLE'] = 280

app.config['MAIL_SERVER'] = tpbeta_mail_server
app.config['MAIL_PORT'] = tpbeta_mail_port
app.config['MAIL_USERNAME'] = tpbeta_mail_username
app.config['MAIL_PASSWORD'] = tpbeta_mail_password
app.config['MAIL_DEFAULT_SENDER'] = tpbeta_mail_default_sender
app.config['MAIL_USE_SSL'] = True

app.debug = True
db = SQLAlchemy(app)
mail = Mail(app)

login_manager = flask_login.LoginManager()
login_manager.init_app(app)
teachers = tpbeta_teacher_usernames


Example #17
0
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# tmpl_dir = os.path.join(BASE_DIR, 'templates')

webapp = Flask(__name__)

webapp.logger.addHandler(logging.StreamHandler(sys.stdout))
webapp.logger.setLevel(logging.ERROR)

webapp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(BASE_DIR, 'db/app.db')
# webapp.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', 'sqlite:////tmp/flask_app.db')
webapp.config['SECRET_KEY'] = 'foo'
webapp.config['WTF_CSRF_KEY'] = 'foo'

webapp.config['MAIL_SERVER'] = 'smtp.gmail.com'
webapp.config['MAIL_PORT'] = 465
webapp.config['MAIL_USE_TLS'] = False
webapp.config['MAIL_USE_SSL'] = True
webapp.config['MAIL_USERNAME'] = 'mahesh.thipparthi@gmail.com'
webapp.config['MAIL_PASSWORD'] = 'XXXXXX'
webapp.config['DEFAULT_MAIL_SENDER'] = 'mahesh.thipparthi@gmail.com'

db.init_app(webapp)

login_manager = LoginManager()
login_manager.init_app(webapp)

bcrypt = Bcrypt()

mail = Mail()
mail.init_app(webapp)
Example #18
0
lm.login_view = 'login'
oid = OpenID(app, os.path.join(settings.BASE_DIR, 'tmp'))

# Configure database
app.config['SQLALCHEMY_DATABASE_URI'] = settings.DATABASE_URI
db = SQLAlchemy(app)
migrate = Migrate(app, db)

# Configure Flask-Script
manager = Manager(app)
manager.add_command('runserver', Server(host=settings.APP_HOST, port=settings.APP_PORT))
manager.add_command('db', MigrateCommand)

# Configure Flask-Mail
app.config['MAIL_SERVER'] = settings.MAIL_SERVER
app.config['MAIL_PORT'] = settings.MAIL_PORT
app.config['MAIL_USE_TLS'] = settings.MAIL_USE_TLS
app.config['MAIL_USERNAME'] = settings.MAIL_USERNAME
app.config['MAIL_PASSWORD'] = settings.MAIL_PASSWORD
mail = Mail(app)

# Configure Flask-Cache
app.config['CACHE_TYPE'] = settings.CACHE_BACKEND
cache = Cache(app)

# Configure Babel
babel = Babel(app)


# Configure Flask-Assets
assets = Environment(app)
Example #19
0
ENCRYPTION_KEY = SettingsUtil.EncryptionKey.get(RUN_MODE == 'development')

app = Flask(__name__)

app.secret_key = CryptoUtil.decrypt(config.ENCRYPTED_SESSION_KEY,ENCRYPTION_KEY)

app.config['STRIPE_TOKEN'] = CryptoUtil.decrypt(config.ENCRYPTED_STRIPE_TOKEN, ENCRYPTION_KEY)
app.config['DATABASE_PASSWORD'] = CryptoUtil.decrypt(config.ENCRYPTED_DATABASE_PASSWORD, ENCRYPTION_KEY)
app.config['STRIPE_CACHE_REFRESH_MINUTES'] = config.STRIPE_CACHE_REFRESH_MINUTES
app.config['STRIPE_CACHE_REBUILD_MINUTES'] = config.STRIPE_CACHE_REBUILD_MINUTES
app.config['STRIPE_CACHE_REFRESH_BACKREACH_MIN'] = config.STRIPE_CACHE_REFRESH_BACKREACH_MIN
app.config['ACCESS_CONTROL_HOSTNAME'] = config.ACCESS_CONTROL_HOSTNAME
app.config['ACCESS_CONTROL_SSH_PORT'] = config.ACCESS_CONTROL_SSH_PORT

app.config['MAIL_SERVER'] = config.MAIL_SERVER
app.config['MAIL_PORT'] = config.MAIL_PORT
app.config['MAIL_USE_TLS'] = config.MAIL_USE_TLS
app.config['MAIL_USE_SSL'] = config.MAIL_USE_SSL
app.config['MAIL_USERNAME'] = CryptoUtil.decrypt(config.ENCRYPTED_MAIL_USERNAME,ENCRYPTION_KEY)
app.config['MAIL_PASSWORD'] = CryptoUtil.decrypt(config.ENCRYPTED_MAIL_PASSWORD,ENCRYPTION_KEY)
app.config['ADMIN_PASSPHRASE'] = CryptoUtil.decrypt(config.ENCRYPTED_ADMIN_PASSPHRASE,ENCRYPTION_KEY)
app.config['LOG_FILE'] = config.LOG_FILE

# Logging
file_handler = logging.FileHandler(app.config['LOG_FILE'])
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s: %(message)s'))
file_handler.setLevel(logging.INFO)
app.logger.setLevel(logging.INFO)
app.logger.addHandler(file_handler)

app.logger.info("------------------------------")
Example #20
0
# class ConfigClass(object):
#     #Flask settings
#     SECRET_KEY = os.getenv('SECRET_KEY', 'bantz')
#     SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL',

#App instantiation
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']
app.secret_key = 'bantz'

#Flask-Mail settings
app.config['MAIL_USERNAME'] = 'giacomo.arrighini@gmail.com'
app.config['MAIL_PASSWORD'] = 'kYhkPeDtlOCZCm0eh1BJ5A'
app.config['MAIL_DEFAULT_SENDER'] = 'noreply@example.com'
app.config['MAIL_SERVER'] = 'smtp.mandrillapp.com'
app.config['MAIL_PORT'] = int('465')
app.config['MAIL_USE_SSL'] = int(True)

#DB connection instantiation
db = SQLAlchemy(app)
mail = Mail(app) #Initialize Flask-Mail, TODO: set config 

#Define user data model, according to Flask_user basic app tutorial
class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    
    #User authenttication information
    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='')
    
Example #21
0
# encoding:utf-8
from flask import Flask,render_template,session,redirect,url_for,flash,request
from flask.ext.bootstrap import Bootstrap
from flask.ext.moment import Moment
from datetime import datetime
from flask.ext.wtf import Form
from wtforms import SubmitField,StringField
from wtforms.validators import required
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.mail import Mail
from flask.ext.mail import Message
from threading import Thread
import RealIP
import dbconfig

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
#初始化Flask 实例,添加秘钥,数据库参数配置,邮箱配置
app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string'
app.config['SQLALCHEMY_DATABASE_URI'] = dbconfig.SQLALCHEMY_DATABASE_URI
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = dbconfig.SQLALCHEMY_COMMIT_ON_TEARDOWN
app.config['MAIL_SERVER'] = 'smtp.139.com'
app.config['MAIL_PORT'] = 25
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = '18898761417@139.com'
app.config['MAIL_PASSWORD'] = '***************'
app.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Flasky]'
app.config['FLASKY_MAIL_SENDER'] = 'Flasky Admin <18898761417@139.com>'
Example #22
0
# music_tracker/__init__.py # -*- coding: utf-8 -*-
import os

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.wtf.csrf import CsrfProtect
from flask.ext.login import LoginManager
from flask.ext.mail import Mail

if os.environ.get('HEROKU'):
    app = Flask(__name__)
    app.config.from_pyfile('../config.py')
    app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')
    app.config['MAIL_SERVER'] = os.environ.get('MAIL_SERVER')
    app.config['MAIL_PORT'] = os.environ.get('MAIL_PORT')
    app.config['MAIL_USE_SSL'] = os.environ.get('MAIL_USE_SSL')
    app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME')
    app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')
else:
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object('config')
    app.config.from_pyfile('config.py')

CsrfProtect(app)

mail = Mail(app)

db = SQLAlchemy(app)

from flask.ext.bcrypt import Bcrypt
Example #23
0
########################################################################
app = Flask(__name__)

manager = Manager(app)
mail = Mail(app)
login_manager.init_app(app)
bootstrap = Bootstrap(app)
app.config['SECRET_KEY'] = cfg.get("Secret", "wtf_secret_key")

# app.config['SERVER_NAME'] = "www.circl.lu:443"
# app.config['APPLICATION_ROOT'] = '/cve-portal'
# app.config['WTF_CSRF_ENABLED'] = True

# SMTP email config #
app.config['MAIL_SERVER'] = cfg.get('SMTP', 'server')
app.config['MAIL_PORT'] = cfg.get('SMTP', 'port')
app.config['MAIL_USE_TLS'] = cfg.get('SMTP', 'tls')
app.config['DEFAULT_MAIL_SENDER'] = cfg.get('SMTP', 'sender')

# Super Admin #
app.config['PORTAL_ADMIN'] = cfg.get('ADMIN', 'mail')

#  REDIS CONNECTION  #
r = redis.StrictRedis(host=cfg.get('REDIS', 'host'),
                      port=cfg.get('REDIS', 'port'),
                      db=cfg.get('REDIS', 'db'))

#  MONGO  #
app.config['MONGO_DBNAME'] = cfg.get('MONGO', 'dbname')
m = PyMongo(app)
Example #24
0
from flask.ext.wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import Required
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.mail import Mail

basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string'
app.config['SQLALCHEMY_DATABASE_URI'] =\
    'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['MAIL_SERVER'] = 'smtp.139.com'
app.config['MAIL_PORT'] = '553'
app.config['MAIL_USER'] = '18217325390@139.com'
app.config['MAIL_PASSWORD'] = '1qaz@WSX3edc'


manager = Manager(app)
bootstrap = Bootstrap(app)
moment = Moment(app)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
mail = Mail(app)


class Role(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer, primary_key=True)
Example #25
0
stripe_keys = {
    'secret_key': os.environ['SECRET_KEY'],
    'publishable_key': os.environ['PUBLISHABLE_KEY']
}

stripe.api_key = stripe_keys['secret_key']

app = Flask(__name__)
heroku = Heroku(app)

#need to explicity define the mail gun smtp port since flask_heroku
#leaves this out

app.config["MAIL_SERVER"] = os.environ["MAILGUN_SMTP_SERVER"]
app.config['MAIL_PORT'] = os.environ["MAILGUN_SMTP_PORT"]
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = os.environ["MAILGUN_SMTP_LOGIN"]
app.config['MAIL_PASSWORD'] = os.environ["MAILGUN_SMTP_PASSWORD"]

mail = Mail(app)

app.config["MONGODB_USERNAME"] = app.config['MONGODB_USER'] #flask_heroku naming convention mismatch, with MongoEngine this time
db = MongoEngine(app)

if not 'Production' in os.environ:
    app.debug = True
    from flask_cake import Cake
    cake = Cake(app, ["build"]) #this converts our coffeescript to javascript
    from flask.ext.less import LESS
    less = LESS(app)
Example #26
0
basedir = os.path.abspath(os.path.dirname(__file__))

# Application configurations
app = Flask(__name__)
app.debug = True
app.static_folder = 'static'
app.config['SECRET_KEY'] = 'hardtoguessstringfromsi364thisisnotsupersecurebutitsok'
# app.config['SQLALCHEMY_DATABASE_URI'] =\
    # 'sqlite:///' + os.path.join(basedir, 'data.sqlite') # Determining where your database file will be stored, and what it will be called
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get('DATABASE_URL') or "postgresql://postgres:T0ky0Bound@localhost/songs_data" # TODO: decide what your new database name will be, and create it in postgresql, before running this new application (it's similar to an old one, but has some more to it)
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# Set up email config stuff
app.config['MAIL_SERVER'] = 'smtp.googlemail.com'
app.config['MAIL_PORT'] = 587 #default
app.config['MAIL_USE_TLS'] = True
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 <youremail@example.com>' # TODO fill in email
app.config['ADMIN'] = os.environ.get('ADMIN') or "Admin <youremail@example.com>"


# Set up Flask debug stuff
manager = Manager(app)
# moment = Moment(app) # For time # Later
db = SQLAlchemy(app) # For database use
migrate = Migrate(app, db) # For database use/updating
manager.add_command('db', MigrateCommand) # Add migrate command to manager
mail = Mail(app) # For email sending
Example #27
0
    def build_user(self, data):
        user = super(GitHugAuth, self).build_user(data)
        user.avatar_url = data['user']['avatar_url']
        user.email = data['user'].get('email', '').strip() or None
        return user


#
# Setup
#
import requests

app = Flask(__name__)
app.secret_key = os.environ['SECRET']
app.config['MAIL_SERVER'] = os.environ.get('MAIL_SERVER', 'localhost')
app.config['MAIL_PORT'] = int(os.environ.get('MAIL_PORT', 25))
app.config['MAIL_USE_TLS'] = bool(os.environ.get('MAIL_USE_TLS', False))
app.config['MAIL_USE_SSL'] = bool(os.environ.get('MAIL_USE_SSL', False))
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME', None)
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD', None)
app.config['DEFAULT_MAIL_SENDER'] = 'hugs@githugs.org'
app.local = os.environ.get('LOCAL', None) is not None
app.debug = bool(app.local)
heroku = Heroku(app)
if app.config.get('SENTRY_DSN'):
    sentry = Sentry(app)
db = connect(
    app.config['MONGODB_DB'],
    host=app.config['MONGODB_HOST'],
    port=app.config['MONGODB_PORT'],
    username=app.config['MONGODB_USER'],
Example #28
0
def create_app(configfile=None):
    app = Flask(__name__)
    handler = RotatingFileHandler('urlabuse.log', maxBytes=10000, backupCount=5)
    handler.setFormatter(Formatter('%(asctime)s %(message)s'))
    app.wsgi_app = ReverseProxied(app.wsgi_app)
    app.logger.addHandler(handler)
    app.logger.setLevel(logging.INFO)
    Bootstrap(app)
    q = Queue(connection=conn)

    # Mail Config
    app.config['MAIL_SERVER'] = 'localhost'
    app.config['MAIL_PORT'] = 25
    mail = Mail(app)

    app.config['SECRET_KEY'] = 'devkey'
    app.config['BOOTSTRAP_SERVE_LOCAL'] = True
    app.config['configfile'] = config_path

    parser = configparser.SafeConfigParser()
    parser.read(app.config['configfile'])

    replacelist = make_dict(parser, 'replacelist')
    auth_users = prepare_auth()
    ignorelist = [i.strip()
                  for i in parser.get('abuse', 'ignore').split('\n')
                  if len(i.strip()) > 0]
    autosend_threshold = 5

    def _get_user_ip(request):
        ip = request.headers.get('X-Forwarded-For')
        if ip is None:
            ip = request.remote_addr
        return ip

    @app.route('/', methods=['GET', 'POST'])
    def index():
        form = URLForm()
        return render_template('index.html', form=form)

    @app.route('/urlreport', methods=['GET'])
    def url_report():
        return render_template('url-report.html')

    @app.errorhandler(404)
    def page_not_found(e):
        ip = request.headers.get('X-Forwarded-For')
        if ip is None:
            ip = request.remote_addr
        if request.path != '/_result/':
            app.logger.info('404 of {} on {}'.format(ip, request.path))
        return render_template('404.html'), 404

    def authenticate():
        """Sends a 401 response that enables basic auth"""
        return Response('Could not verify your access level for that URL.\n'
                        'You have to login with proper credentials', 401,
                        {'WWW-Authenticate': 'Basic realm="Login Required"'})

    def check_auth(username, password):
        """This function is called to check if a username /
        password combination is valid.
        """
        if auth_users is None:
            return False
        else:
            db_pass = auth_users.get(username)
            return db_pass == password

    @app.route('/login', methods=['GET', 'POST'])
    def login():
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return redirect(url_for('index'))

    @app.route("/_result/<job_key>", methods=['GET'])
    def check_valid(job_key):
        if job_key is None:
            return json.dumps(None), 200
        job = Job.fetch(job_key, connection=conn)
        if job.is_finished:
            return json.dumps(job.result), 200
        else:
            return json.dumps("Nay!"), 202

    @app.route('/start', methods=['POST'])
    def run_query():
        data = json.loads(request.data)
        url = data["url"]
        ip = _get_user_ip(request)
        app.logger.info('{} {}'.format(ip, url))
        if get_submissions(url) >= autosend_threshold:
            send(url, '', True)
        is_valid = q.enqueue_call(func=is_valid_url, args=(url,), result_ttl=500)
        return is_valid.get_id()

    @app.route('/urls', methods=['POST'])
    def urls():
        data = json.loads(request.data)
        url = data["url"]
        u = q.enqueue_call(func=url_list, args=(url,), result_ttl=500)
        return u.get_id()

    @app.route('/resolve', methods=['POST'])
    def resolve():
        data = json.loads(request.data)
        url = data["url"]
        u = q.enqueue_call(func=dns_resolve, args=(url,), result_ttl=500)
        return u.get_id()

    @app.route('/phishtank', methods=['POST'])
    def phishtank():
        data = json.loads(request.data)
        if not os.path.exists('phishtank.key'):
            return None
        url = parser.get("PHISHTANK", "url")
        key = open('phishtank.key', 'r').readline().strip()
        query = data["query"]
        u = q.enqueue_call(func=phish_query, args=(url, key, query,), result_ttl=500)
        return u.get_id()

    @app.route('/virustotal_report', methods=['POST'])
    def vt():
        data = json.loads(request.data)
        if not os.path.exists('virustotal.key'):
            return None
        url = parser.get("VIRUSTOTAL", "url_report")
        url_up = parser.get("VIRUSTOTAL", "url_upload")
        key = open('virustotal.key', 'r').readline().strip()
        query = data["query"]
        u = q.enqueue_call(func=vt_query_url, args=(url, url_up, key, query,), result_ttl=500)
        return u.get_id()

    @app.route('/googlesafebrowsing', methods=['POST'])
    def gsb():
        data = json.loads(request.data)
        if not os.path.exists('googlesafebrowsing.key'):
            return None
        url = parser.get("GOOGLESAFEBROWSING", "url")
        key = open('googlesafebrowsing.key', 'r').readline().strip()
        url = url.format(key)
        query = data["query"]
        u = q.enqueue_call(func=gsb_query, args=(url, query,), result_ttl=500)
        return u.get_id()

    @app.route('/urlquery', methods=['POST'])
    def urlquery():
        data = json.loads(request.data)
        if not os.path.exists('urlquery.key'):
            return None
        url = parser.get("URLQUERY", "url")
        key = open('urlquery.key', 'r').readline().strip()
        query = data["query"]
        u = q.enqueue_call(func=urlquery_query, args=(url, key, query,), result_ttl=500)
        return u.get_id()

    @app.route('/ticket', methods=['POST'])
    def ticket():
        if not request.authorization:
            return ''
        data = json.loads(request.data)
        server = parser.get("SPHINX", "server")
        port = int(parser.get("SPHINX", "port"))
        url = parser.get("ITS", "url")
        query = data["query"]
        u = q.enqueue_call(func=sphinxsearch, args=(server, port, url, query,),
                           result_ttl=500)
        return u.get_id()

    @app.route('/whois', methods=['POST'])
    def whoismail():
        if not request.authorization:
            return ''
        server = parser.get("WHOIS", "server")
        port = parser.getint("WHOIS", "port")
        data = json.loads(request.data)
        query = data["query"]
        u = q.enqueue_call(func=whois, args=(server, port, query, ignorelist, replacelist),
                           result_ttl=500)
        return u.get_id()

    @app.route('/pdnscircl', methods=['POST'])
    def dnscircl():
        url = parser.get("PDNS_CIRCL", "url")
        user, password = open('pdnscircl.key', 'r').readlines()
        data = json.loads(request.data)
        query = data["query"]
        u = q.enqueue_call(func=pdnscircl, args=(url, user.strip(), password.strip(),
                                                 query,), result_ttl=500)
        return u.get_id()

    @app.route('/bgpranking', methods=['POST'])
    def bgpr():
        data = json.loads(request.data)
        query = data["query"]
        u = q.enqueue_call(func=bgpranking, args=(query,), result_ttl=500)
        return u.get_id()

    @app.route('/psslcircl', methods=['POST'])
    def sslcircl():
        url = parser.get("PSSL_CIRCL", "url")
        user, password = open('psslcircl.key', 'r').readlines()
        data = json.loads(request.data)
        query = data["query"]
        u = q.enqueue_call(func=psslcircl, args=(url, user.strip(), password.strip(),
                                                 query,), result_ttl=500)
        return u.get_id()

    @app.route('/get_cache', methods=['POST'])
    def get_cache():
        data = json.loads(request.data)
        url = data["query"]
        data = cached(url)
        dumped = json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))
        return dumped

    def digest(data):
        to_return = ''
        all_mails = set()
        for entry in data:
            for url, info in list(entry.items()):
                to_return += '\n{}\n'.format(url)
                if info.get('whois'):
                    all_mails.update(info.get('whois'))
                    to_return += '\tContacts: {}\n'.format(', '.join(info.get('whois')))
                if info.get('vt') and len(info.get('vt')) == 4:
                    vtstuff = info.get('vt')
                    to_return += '\t{} out of {} positive detections in VT - {}\n'.format(
                        vtstuff[2], vtstuff[3], vtstuff[1])
                if info.get('gsb'):
                    to_return += '\tKnown as malicious on Google Safe Browsing: {}\n'.format(info.get('gsb'))
                if info.get('phishtank'):
                    to_return += '\tKnown as malicious on PhishTank\n'
                if info.get('dns'):
                    ipv4, ipv6 = info.get('dns')
                    if ipv4 is not None:
                        for ip in ipv4:
                            to_return += '\t' + ip + '\n'
                            data = info[ip]
                            if data.get('bgp'):
                                to_return += '\t\t(PTR: {}) is announced by {} ({}).\n'.format(*(data.get('bgp')[:3]))
                            if data.get('whois'):
                                all_mails.update(data.get('whois'))
                                to_return += '\t\tContacts: {}\n'.format(', '.join(data.get('whois')))
                    if ipv6 is not None:
                        for ip in ipv6:
                            to_return += '\t' + ip + '\n'
                            data = info[ip]
                            if data.get('whois'):
                                all_mails.update(data.get('whois'))
                                to_return += '\t\tContacts: {}\n'.format(', '.join(data.get('whois')))
            to_return += '\tAll contacts: {}\n'.format(', '.join(all_mails))
        return to_return

    def send(url, ip='', autosend=False):
        if not get_mail_sent(url):
            set_mail_sent(url)
            data = cached(url)
            if not autosend:
                subject = 'URL Abuse report from ' + ip
            else:
                subject = 'URL Abuse report sent automatically'
            msg = Message(subject, sender='urlabuse@circl.lu', recipients=["info@circl.lu"])
            msg.body = digest(data)
            msg.body += '\n\n'
            msg.body += json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))
            mail.send(msg)

    @app.route('/submit', methods=['POST'])
    def send_mail():
        data = json.loads(request.data)
        url = data["url"]
        if not get_mail_sent(url):
            ip = _get_user_ip(request)
            send(url, ip)
        return redirect(url_for('index'))

    return app
Example #29
0
    print "*** Running without DB ***"
    rdb = None

app = Flask(__name__, static_url_path='')
app.debug = True
#app.debug = False
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///wv.db'

app.config['SECURITY_TRACKABLE'] = True
app.config['SECURITY_REGISTERABLE'] = True
app.config['SECURITY_EMAIL_SENDER'] = 'no-reply@pollywss.paldeploy.com'

app.config['MAIL_SERVER'] = '192.168.20.18'
app.config['MAIL_PORT'] = 25
#app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USE_SSL'] = False
app.config['MAIL_USERNAME'] = 'flycam'
app.config['MAIL_PASSWORD'] = 'flyspec'
mail = Mail(app)

socketio = SocketIO(app)

# Create database connection object
db = SQLAlchemy(app)

# Define models
roles_users = db.Table('roles_users',
        db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
        db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))
Example #30
0
File: app.py Project: Fize/cvpn
db = SQLAlchemy(app)
migrate = Migrate(app, db)


def parser(field, key):
    a = Parser(os.path.join(basedir, 'config.ini'))
    return a.get(field, key)


#config
app.config['SECRET_KEY'] = parser('secret', 'key')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' + parser('cvpn', 'data_path')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['MAIL_SERVER'] = parser('mail', 'smtp_server')
app.config['MAIL_PORT'] = int(parser('mail', 'smtp_port'))
app.config['MAIL_USE_TLS'] = parser('mail', 'mail_tls')
app.config['MAIL_USE_SSL'] = parser('mail', 'mail_ssl')
app.config['MAIL_USERNAME'] = parser('mail', 'mail_user')
app.config['MAIL_PASSWORD'] = parser('mail', 'mail_password')
app.config['FLASK_MAIL_SUBJECT_PREFIX'] = parser('mail', 'prefix')
app.config['FLASK_MAIL_SENDER'] = 'cvpn admin<%s>' % app.config['MAIL_USERNAME']


mail = Mail(app)


def send_email(to, subject, template, **kwargs):
    msg = Message(app.config['FLASK_MAIL_SUBJECT_PREFIX'] + subject,
                  sender=app.config['FLASK_MAIL_SENDER'], recipients=[to])
    msg.body = render_template(template + '.txt', **kwargs)