Example #1
0
def run():

    app = Flask(__name__)

    # Database
    config.db = db_conn(app)
    app.config[ 'SQLALCHEMY_BINDS' ] = SQLALCHEMY_BINDS

    # Blueprint
    bp_init(app)

    app.run(debug=True,host='0.0.0.0', port=5000)
Example #2
0
    def main():
        app = Flask(__name__)
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
        app.config['SQLALCHEMY_BINDS'] = {
            'data_1': 'sqlite:///:memory:',
            'data_2': 'sqlite:///:memory:',
            'log': 'sqlite:///:memory:'
        }

        db = Database(app)

        class User(db.Model):
            __bind_key__ = db.bind_key_pattern('data_\d')

            id = db.Column(db.Integer, primary_key=True)
            nickname = db.Column(db.String(64), index=True, unique=True)

            def __repr__(self):
                return "<User nickname='%s'>" % self.nickname

        class UserLog(db.Model):
            __bind_key__ = 'log'

            id = db.Column(db.Integer, primary_key=True)
            msg = db.Column(db.String(64))

        if not os.access('temp/test', os.R_OK):
            os.makedirs('temp/test')

        db.drop_all()
        db.create_all()

        with db.bind_key('data_1'):
            user = User(nickname='a')
            db.session.add(user)
            db.session.commit()

        with db.bind_key('data_2'):
            user = User(nickname='b')
            db.session.add(user)
            db.session.commit()

        user_log = UserLog(msg='x')
        db.session.add(user_log)
        db.session.commit()

        with db.bind_key('data_1'):
            print User.query.all()

        with db.bind_key('data_2'):
            print User.query.all()
Example #3
0
def _createDummyAppFromUri(dburi,trace=False):
    """
    Creates a dummy Flask app from a given dburi
    """
    # create a dummy app to attach to FlaskSQLAlchemy
    dummyApp = Flask("dummy")
    
    dummyApp.config['SQLALCHEMY_DATABASE_URI'] = dburi
    dummyApp.config['SQLALCHEMY_BINDS'] = {
        "mgd": dburi,
    }
    if trace:
        dummyApp.config['SQLALCHEMY_ECHO'] = True
        
    return dummyApp
Example #4
0
def create_app(config_name):
    app = Flask(__name__)
    #csrf = CSRFProtect(app)
    app.config['SQLALCHEMY_DATABASE_URI']='mysql://ilya:ilya@localhost/testapp?charset=utf8'
    app.config['SQLALCHEMY_BINDS']={'recipe':'mysql://ilya:ilya@localhost/recipe?charset=utf8'}
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS']='False'
    app.debug = True
    app.secret_key='super secret key'
    
    Bootstrap(app)
    db.init_app(app)
    migrate = Migrate(app, db)
    
    from app import models

    from .finance import finance as finance_blueprint
    app.register_blueprint(finance_blueprint)

    from .home import home as home_blueprint
    app.register_blueprint(home_blueprint)

    from .recipeapp import recipeapp as recipeapp_blueprint
    app.register_blueprint(recipeapp_blueprint)

    from .shopapp import shopapp as shopapp_blueprint
    app.register_blueprint(shopapp_blueprint)

    @app.errorhandler(404)
    def page_not_found(error):
        return render_template('errors/404.html')

    @app.errorhandler(500)
    def internal_server_error(error):
        return render_template('errors/500.html')

    return app
Example #5
0
import os
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView
import sys
import subprocess

	
if os.path.isfile('/etc/supervisor/conf.d/gunicorn.conf'):
	sys.exit()
	
app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///local.db'
app.config['SQLALCHEMY_BINDS'] = {
	'config':        'sqlite:///config.db',
	'games':      'sqlite:///games_master.db'
}


app.config['SECRET_KEY'] = 'jdhq7864r8uihblk'


db = SQLAlchemy(app)


class GPioneer(db.Model):
	__tablename__ = 'gpioneer'
	__bind_key__ = 'config'
	id = db.Column(db.Integer, primary_key=True)
	name = db.Column(db.Text)
	command = db.Column(db.Text)
Example #6
0
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask import abort
from flask import request
from flask import jsonify
from config import AUTH_PUBLIC_URI, ADMIN_TOKEN, CDN_LOG_DB
import json
import httplib
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost/cloud_cdn'
app.config['SQLALCHEMY_BINDS'] = {
    'cdn_log': CDN_LOG_DB
}
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

db = SQLAlchemy(app)

@app.errorhandler(401)
def page_not_found(error):
    return 'Unauthorized', 401


@app.before_request
def before_request():
    token = request.headers.get("X-Auth-Token")
    if request.path == "/cdn_api/tokens":
        pass
Example #7
0
from cas import cas
from cestadb import *
from places import places
from details import details
from gettingstarted import gettingstarted
import uuid
import phpass
from cloudinary.uploader import upload
import json

app = Flask(__name__)

app.config['SQLALCHEMY_POOL_RECYCLE'] = 60
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['MYSQL_DB']
app.config['SQLALCHEMY_BINDS'] = {
    'db1': app.config['SQLALCHEMY_DATABASE_URI'],
    'db2': os.environ['WORDPRESS_DB']
}

app.secret_key = os.environ['APP_SECRET_KEY']


db.init_app(app)

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
login_manager.login_message = u"Prihl%ss sa pou%sit%sm prihl. %sdajov CestaSNP.sk." %(u"\u00E1", u"\u017E", u"\u00ED", u"\u00FA")

#path = '/Users/lcicon/Documents/Openshift/sledovanie/img/'
#path = '/home/hasty/Developement/web/OpenShift/sledovanie/wsgi/img/'
path = 'img/'
Example #8
0
    settings.DB_USERNAME,
    settings.DB_PASSWORD,
    settings.DB_HOSTNAME,
    settings.DB_PORT,
    settings.DB_NAME)

db_binds = {
    settings.DB_NAME: db_str,
}


app.config['DEBUG'] = False
app.config['TOKEN'] = settings.TOKEN
app.config['SQLALCHEMY_DATABASE_URI'] = db_str
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SQLALCHEMY_BINDS'] = db_binds
app.config['SECRET_KEY'] = settings.SECURITY_SECRET

app.config['SECURITY_LOGIN_URL'] = '/security/login'
app.config['SECURITY_LOGOUT_URL'] = '/security/logout'
app.config['SECURITY_REGISTER_URL'] = '/security/register'
app.config['SECURITY_REGISTERABLE'] = True
app.config['SECURITY_SEND_REGISTER_EMAIL'] = False
app.config['SECURITY_PASSWORD_HASH'] = 'sha512_crypt'
app.config['SECURITY_PASSWORD_SALT'] = settings.SECURITY_SECRET
app.config['SECURITY_LOGIN_USER_TEMPLATE'] = '/security/login.html'
app.config['SECURITY_REGISTER_USER_TEMPLATE'] = '/security/register.html'
app.config['SECURITY_POST_REGISTER_VIEW'] = '/admin'

db = SQLAlchemy(app)
Example #9
0
Bootstrap(app)

try:
    with open('config.json', 'r') as f:
        config = json.load(f)
        app.secret_key = config["secret_key"]
        app.config['databaseUser'] = config["mysql_user"]
        app.config['databasePwd'] = config["mysql_passwd"]
        app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
        app.config['SQLALCHEMY_NATIVE_UNICODE'] = True
        if config["Test_Mode"]:
            app.config['SQLALCHEMY_ECHO'] = True

        mysql_url = 'mysql+pymysql://{0}:{1}@localhost:{2}/'.format(config["mysql_user"], config["mysql_passwd"],
                                                                    config["mysql_port"])
        app.config['SQLALCHEMY_BINDS'] = {"activity": mysql_url + config["database"]}
        app.config['SQLALCHEMY_DATABASE_URI'] = mysql_url + config["database"]
        baseurl = config["baseurl"]

except:
    print("Config File Open Fail!")
    exit(-1)

import web.Views


@app.errorhandler(401)
def not_authed(err=None):
    return render_template('errors/401.html'), 401

Example #10
0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.json import JSONEncoder
from datetime import date, datetime
import os

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://%s:%s@localhost/csa?charset=utf8' % (
    os.environ['CSA_DB_USERNAME'], os.environ['CSA_DB_PASSWORD']
)

sqlite_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                           'db.sqlite')
app.config['SQLALCHEMY_BINDS'] = {
    'wallet': 'sqlite:///' + sqlite_path
}
app.config['SQLALCHEMY_ECHO'] = False
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True

db = SQLAlchemy(app)


class CustomJSONEncoder(JSONEncoder):
    def default(self, obj):
        try:
            if isinstance(obj, date):
                return JSONEncoder.default(
                    self,
                    datetime(obj.year, obj.month, obj.day))
            iterable = iter(obj)
        except TypeError:
Example #11
0
#!/usr/bin/env python3

import os
import random
from flask import Flask, render_template
from flask_script import Manager
from flask_sqlalchemy import SQLAlchemy

basedir_booksdb = os.path.abspath(os.path.dirname('metadata.db'))
basedir_usersdb = os.path.abspath(os.path.dirname('.'))

app = Flask(__name__)
app.config['SQLALCHEMY_BINDS'] = {'booksdb': 'sqlite:///{}'.format(os.path.join(basedir_booksdb, 'metadata.db')),
                                  'usersdb': 'sqlite:///{}'.format(os.path.join(basedir_usersdb, 'users.sqlite'))}
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True


db = SQLAlchemy(app)
manager = Manager(app)


#######################
# Classi database
#######################
class Authors(db.Model):
    __bind_key__ = 'booksdb'
    __tablename__ = 'authors'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Text, nullable=False)
    sort = db.Column(db.Text)
    
Example #12
0
                    elif type(table_bind_key) is str and table_bind_key == bind:
                        result.append(table)

        return result


if __name__ == '__main__':
    import os

    from flask import Flask

    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
    app.config['SQLALCHEMY_BINDS'] = {
        'data_1': 'sqlite:///../temp/test_data_1.db',
        'data_2': 'sqlite:///../temp/test_data_2.db',
        'log':  'sqlite:///../temp/test_log.db'
    }

    db = SQLAlchemy(app)

    class User(db.Model):
        __bind_key__ = db.BindingKeyPattern('data_\d')

        id = db.Column(db.Integer, primary_key=True)
        nickname = db.Column(db.String(64), index=True, unique=True)

        def __repr__(self):
            return "<User nickname='%s'>" % (self.nickname)

    class UserLog(db.Model):
Example #13
0
from base64 import b64encode, b64decode
import os, json

#this class from itsdangerous implements token<->user
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import SignatureExpired, BadSignature

import env

fsdir = env.getenv('FS_PREFIX')

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+fsdir+'/global/sys/UserTable.db'
app.config['SQLALCHEMY_BINDS'] = {
    'history': 'sqlite:///'+fsdir+'/global/sys/HistoryTable.db',
    'beansapplication': 'sqlite:///'+fsdir+'/global/sys/BeansApplication.db',
    'system': 'sqlite:///'+fsdir+'/global/sys/System.db'
    }
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
try:
    secret_key_file = open(env.getenv('FS_PREFIX') + '/local/token_secret_key.txt')
    app.secret_key = secret_key_file.read()
    secret_key_file.close()
except:
    from os import urandom
    secret_key = urandom(24)
    secret_key = b64encode(secret_key).decode('utf-8')
    app.secret_key = secret_key
    secret_key_file = open(env.getenv('FS_PREFIX') + '/local/token_secret_key.txt', 'w')
    secret_key_file.write(secret_key)
    secret_key_file.close()
    __bind_key__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    nickname = db.Column(db.String(80), unique=True)

    login_logs = db.relationship(lambda: LoginLog, backref='owner')


class LoginLog(db.Model):
    __bind_key__ = 'log'
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey(User.id))
    ctime = db.Column(db.DateTime, default=datetime.now(), nullable=False)

if __name__ == '__main__':
    app.config['SQLALCHEMY_ECHO'] = True
    app.config['SQLALCHEMY_BINDS'] = {
        'user': 'sqlite:///./user.db',
        'log':  'sqlite:///./log.db', 
    }
        
    db.drop_all()
    db.create_all()

    user = User(nickname='jaru')
    db.session.add(user)
    db.session.commit()

    login_log = LoginLog(owner=user)
    db.session.add(login_log)
    db.session.commit()
Example #15
0
# -*- coding: utf-8 -*-
from flask import Flask, render_template, jsonify, make_response, request, flash, json
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.sql import text
import datetime, collections
  
app = Flask(__name__)

#app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqldb://root:root@localhost:3306/sinfominer?charset=utf8'
SQLALCHEMY_BINDS = {
    'db_commits': 'mysql+mysqldb://root:root@localhost:3306/sinfominer?charset=utf8',
    'db_events': 'mysql+mysqldb://root:root@localhost:3306/uedashboard?charset=utf8'
}

app.config['SQLALCHEMY_BINDS'] = SQLALCHEMY_BINDS
db = SQLAlchemy(app) 

user = "arthurmacedo"

months_map = { '1' : "Jan", '2' : "Feb", '3' : "Mar", '4' : "Apr", '5' : "May", '6' : "Jun", '7' : "Jul", '8' : "Aug", '9' : "Sep", '10' : "Oct" , '11' : "Nov", '12' : "Dec" }

def get_all_users():
	sql = text('select distinct developer from commit;')
	result = db.get_engine(app, 'db_commits').execute(sql)

	users = []

	for row in result:
		users.append(str(row["developer"]))
	result.close()
	return users
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.security import Security, SQLAlchemyUserDatastore, \
    login_required, UserMixin, RoleMixin
import flask.ext.security.utils as security_utils


###########################################################################
# Configuration
###########################################################################

app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'super-secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///databases/security.db'
app.config['SQLALCHEMY_BINDS'] = {
    'security':        'sqlite:///databases/security.db',
    'application':     'sqlite:///databases/application.db'
}
app.config['SECURITY_PASSWORD_HASH'] = 'sha512_crypt'
app.config['SECURITY_PASSWORD_SALT'] = '9yAPe05Nsjl6UjJEMlXOTsiuyPlcvfr9n26OLVuCReIs3Pw3SGnHv39'
app.config['SECURITY_REGISTERABLE'] = True
app.config['SECURITY_CHANGABLE'] = True
app.config['SECURITY_RECOVERABLE'] = True
app.config['SECURITY_CONFIRMABLE'] = False


# Mail
mail = Mail()
app.config["MAIL_SERVER"] = "smtp.gmail.com"
app.config["MAIL_PORT"] = 587
app.config["MAIL_USE_SSL"] = False
app.config["MAIL_USE_TLS"] = True
Example #17
0
https://flask-migrate.readthedocs.io/en/latest/
"""

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from flask_security import (
    Security, SQLAlchemyUserDatastore, UserMixin, RoleMixin, login_required,
    roles_required, current_user
)

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://myhngn5_user:Hnggr0upLLC$@localhost/myhngn5_hng'
app.config['SQLALCHEMY_BINDS'] = {
                                    'myhngn5_admin' : 'mysql://myhngn5_user:Hnggr0upLLC$@localhost/myhngn5_admin'
                                    }
db = SQLAlchemy(app)
migrate = Migrate(app, db)

manager = Manager(app)
manager.add_command('db', MigrateCommand)

# Define Flask-SQLAlchemy 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')),
        info={'bind_key': 'myhngn5_admin'})

class Role(db.Model, RoleMixin):
    __bind_key__ ='myhngn5_admin'
Example #18
0
    })
     

# setup all the logging for our app
logging_setup.setup(app)
        
        
# testing postgres dburi
dburi = "postgresql+psycopg2://%s:%s@%s/%s"%(PG_USER,PG_PASS,
	PG_SERVER,PG_DBNAME)

# configure the multiple db binds
# 'mgd' is for mgd 
app.config['SQLALCHEMY_DATABASE_URI'] = dburi
app.config['SQLALCHEMY_BINDS'] = {
	"mgd": dburi,
}

# initialise the global db object
from mgipython import modelconfig
modelconfig.createDatabaseEngineFromApp(app, appCache=cache)
db = modelconfig.db

from mgipython.model.query import performQuery
try:
    performQuery("select 1 from mgi_dbinfo")
except:
    pass


    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey(User.id))
    ctime = db.Column(db.DateTime, default=datetime.now(), nullable=False)

    def __repr__(self):
        return "%s<id=%d, uer_id=%d, ctime='%s'>" % (self.__class__.__name__, self.id, self.user_id, repr(self.ctime))

if __name__ == '__main__':
    import os

    app.config['SQLALCHEMY_ECHO'] = True
    app.config['SQLALCHEMY_BINDS'] = {
        'global': 'sqlite:///./global.db',
        'master_user': 'sqlite:///./master_user.db',
        'slave_user': 'sqlite:///./slave_user.db',
        'master_log':  'sqlite:///./master_log.db', 
        'slave_log':  'sqlite:///./slave_log.db', 
    }
        
    db.drop_all()
    db.create_all()

    notice = Notice(msg='NOTICE1')
    db.session.add(notice)
    db.session.commit()

    with db.binding('master_user'):
        notice = Notice(msg='NOTICE2')
        db.session.add(notice)
        db.session.commit()
Example #20
0
basedir = os.path.abspath(os.path.dirname(__file__))
app =  Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(60)

userDb = 'sqlite:///' + os.path.join(basedir, 'db/reasonUser.db')
spdxDb = 'postgresql://spdx:spdx@host:5432/spdx'


databases = {
    'userDb': userDb,
    
}



app.config['SQLALCHEMY_BINDS'] = databases
# Debug configuration
app.config['DEBUG'] = True
db = SQLAlchemy(app)

login_manager = LoginManager()
login_manager.session_protection = "strong"
login_manager.login_view = "login"
login_manager.init_app(app)
# Debug Configuration
#DEBUG_TB_INTERCEPT_REDIRECTS = False
#toolbar = DebugToolbarExtension(app)

ALLOWED_EXTENSIONS = set(['xml', 'jar'])
moment = Moment(app)
Example #21
0
else:
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'

app.config['SECRET_KEY'] = 'something secret'
app.config.update( DEBUG = True )

# contains functions/helpers form sqlalchemy and sqlalchemy.orm
db = SQLAlchemy(app)

# migrate database -- doesn't overwrite tables
db.create_all()


#Provide interface to connect with potential Single Stop Org database 
app.config['SQLALCHEMY_BINDS'] = {
    'singleStopOrg':      'sqlite:////tmp/some.db'
}
db.create_all(bind = ['singleStopOrg'])


# stuff need by twillio to send messages
account_sid = "AC529852db190279bf7ed541ae7340fd4a"
auth_token = "8953ef895b2a097f71a4e3e7937ced28"
client = TwilioRestClient(account_sid,auth_token)

current_user = None

#-------------------------------------------------------------------------------
# Models
#-------------------------------------------------------------------------------
Example #22
0
config.read(['wiin.cfg', prefix + '/etc/wiin.cfg'])

frontend_path = os.path.join(os.path.dirname(__file__), 'frontend')
templates_path = os.path.join(frontend_path, 'templates')
static_path = os.path.join(frontend_path, 'static')

app = Flask(__name__, template_folder=templates_path, static_folder=static_path,
            static_url_path='/static')

app.config['SECRET_KEY'] = config.get('Main', 'SECRET_KEY')
app.config['SQLALCHEMY_DATABASE_URI'] = config.get('Main', 'SQLALCHEMY_DATABASE_URI')
# noinspection PyArgumentList
app.config['SQLALCHEMY_BINDS'] = {
    'db1': config.get('Main', 'SQLALCHEMY_DATABASE_URI_DB1',
                      app.config['SQLALCHEMY_DATABASE_URI']),
    # 'db2': config.get('Main', 'SQLALCHEMY_DATABASE_URI_DB2'),
    # 'db3': config.get('Main', 'SQLALCHEMY_DATABASE_URI_DB3'),
    # 'db4': config.get('Main', 'SQLALCHEMY_DATABASE_URI_DB4'),
}
app.config['SQLALCHEMY_ECHO'] = config.getboolean('Main', 'SQLALCHEMY_ECHO')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = config.getboolean(
    'Main', 'SQLALCHEMY_COMMIT_ON_TEARDOWN'
)
app.config['FACEBOOK'] = {
    'consumer_key': config.get('FACEBOOK', 'consumer_key'),
    'consumer_secret': config.get('FACEBOOK', 'consumer_secret'),
    'frontend_redirect_url': config.get('FACEBOOK', 'frontend_redirect_url'),
    'api_redirect_url': config.get('FACEBOOK', 'frontend_redirect_url'),
}

api = restful.Api(app)
#!/bin/env python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app1.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_BINDS'] = {
    "db1": "sqlite:///app2.db",
}

db = SQLAlchemy(app)


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(128))


class Group(db.Model):
    __bind_key__ = 'db1'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(128))

migrate = Migrate(app, db)

manager = Manager(app)
manager.add_command('db', MigrateCommand)
Example #24
0
from os import getenv, path

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import tmdbsimple as tmdb

# TMDB initialization
tmdb.API_KEY = getenv('tmdb_api_key')
config = tmdb.Configuration()
config.info()

# Flask initialization
app = Flask(__name__)
app.secret_key = getenv('flask_secret_key')
app.config['SQLALCHEMY_DATABASE_URI'] = getenv('flexget_engine')
module_path = path.dirname(path.abspath(__file__))
app.config['SQLALCHEMY_BINDS'] = {
    'flexqueue': 'sqlite:///' + module_path + '/upload/flexqueue.db'
}
app.config['UPLOAD_DIR'] = path.join(module_path, 'upload')
db = SQLAlchemy(app)

from flexqueue.models import Feed

db.create_all(bind=['flexqueue'])

import flexqueue.views
# @date 2016/03/11
# @auther yaoelvon
# @desc Flask-SQLAlchemy的bind功能例子代码
# @reference http://docs.jinkan.org/docs/flask-sqlalchemy/binds.html
#

import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy 
basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'role_test.db')

app.config['SQLALCHEMY_BINDS'] = {
    'user': 'sqlite:///' + os.path.join(basedir, 'user_test.db')
}

db = SQLAlchemy()
db.init_app(app)


class Role(db.Model):
    # 使用默认的SQLALCHEMY_DATABASE_URI数据库
    __tablename__ = 'roless'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), unique=True)
    users = db.relationship('User', backref='roless')

    def __init__(self, name):
        self.name = name
Example #26
0
#    License for the specific language governing permissions and limitations
#    under the License.
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask import abort
from flask import request
from flask import jsonify
from config import KEYSTONE, DATABASE, DATABASE_CMDB, DATABASE_CLOUD, logging
from flask import g
import urlparse
import json
import re
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE
app.config['SQLALCHEMY_BINDS'] = {
    'cmdb': DATABASE_CMDB,
    'cloud': DATABASE_CLOUD
}

db = SQLAlchemy(app)
logger = logging.getLogger(__name__)

@app.errorhandler(401)
def page_not_found(error):
    return 'Unauthorized', 401

from apiUtil import http_request

@app.before_request
def before_request():
    token = request.headers.get("X-Auth-Token")
    g.party = request.headers.get("Sp-Agent", "default")
Example #27
0
app.config['MIKROTIK_PASSWORD'] = config.get('mikrotik', 'password')
app.config['MIKROTIK_FTP_USER'] = config.get('mikrotik', 'ftp_user')
app.config['MIKROTIK_FTP_PASSWORD'] = config.get('mikrotik', 'ftp_password')
app.config['MIKROTIK_FTP_PORT'] = config.getint('mikrotik', 'ftp_port')
app.config['MIKROTIK_HOTSPOT_DIR'] = config.get('mikrotik', 'hotspot_dir')

# radius
app.config['RADIUS_DBTYPE'] = config.get('radius', 'dbtype')
app.config['RADIUS_HOST'] = config.get('radius', 'host')
app.config['RADIUS_PORT'] = config.get('radius', 'port')
app.config['RADIUS_DBNAME'] = config.get('radius', 'dbname')
app.config['RADIUS_USER'] = config.get('radius', 'user')
app.config['RADIUS_PASSWORD'] = config.get('radius', 'password')
app.config['RADIUS_GROUP'] = config.get('radius', 'group')
app.config['SQLALCHEMY_BINDS'] = {'radius': '%s://%s:%s@%s:%s/%s' %
        (app.config['RADIUS_DBTYPE'], app.config['RADIUS_USER'],
        app.config['RADIUS_PASSWORD'], app.config['RADIUS_HOST'],
        app.config['RADIUS_PORT'], app.config['RADIUS_DBNAME'])}


# initialize db
db = SQLAlchemy(app)
db.create_all(bind=None)

# load login extensions
login_manager = LoginManager(app)
principal = Principal(app)

login_manager.login_view = 'login'
login_manager.login_message = 'Silahkan login terlebih dahulu'

# mikrotik
Example #28
0
    def log_requests():
        """
        Log only access requests
        """
        app.logger.info("ACCESS - \"%s\"" % request.path)
        
        
# testing postgres dburi
dburi = "postgresql+psycopg2://%s:%s@%s/%s"%(PG_USER, PG_PASS,
	PG_SERVER, PG_DBNAME)

# configure the multiple db binds
# 'mgd' is for mgd 
app.config['SQLALCHEMY_DATABASE_URI'] = dburi
app.config['SQLALCHEMY_BINDS'] = {
	"wts": dburi,
}

# initialise the global db object
#pylint: disable=wrong-import-order
from mgipython import modelconfig
modelconfig.createDatabaseEngineFromApp(app)
db = modelconfig.db


# set the secret key.  keep this really secret:
app.secret_key = 'ThisIsASecretKey;-)'

# prepare the db connections for all requests
@app.before_request
def before_request():
Example #29
0
login_manager.init_app(app)


# Getting the working directory where the SQLite file will be saved
script_dir = os.path.abspath(os.path.dirname(__file__))

"""
Local SQLite for development purposes, will eventually switch to use one of the Relational DBMS' below
"""
# Configure binds connections
db_one_bind = 'sqlite:///' + os.path.join(script_dir, 'bind_one.db')
db_two_bind = 'sqlite:///' + os.path.join(script_dir, 'bind_two.db')
db_three_bind = 'sqlite:///' + os.path.join(script_dir, 'bind_three.db')

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(script_dir, 'sqlist.db')
app.config['SQLALCHEMY_BINDS'] = {'db_one': db_one_bind, 'db_two': db_two_bind, 'db_three': db_three_bind}


# Initialize 'db'
db = SQLAlchemy(app)


from sqlist import models
from sqlist import views

"""
Default MS SQL Driver + pymssql // Windows
"""
# app.config['SQLALCHEMY_DATABASE_URI'] = 'mssql+pymssql://USER:PASSWORD@@INSTANCE_HOST_NAME:1433/DB_ONE'
# app.config['SQLALCHEMY_BINDS'] = { 'SQList_DB_2': 'mssql+pymssql://USER:PASSWORD@INSTANCE_HOST_NAME:1433/DB_TWO',
#                                    'users': 'mssql+pymssql://USER:PASSWORD@INSTANCE_HOST_NAME:1433/DB_THREE' }
Example #30
0
import BrowserSaver
import amazonBrowser
from splinter import Browser

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

app = Flask(__name__)

app.secret_key = os.urandom(24).encode('hex')

# 配置 sqlalchemy  数据库驱动://数据库用户名:密码@主机地址:端口/数据库?编码
# app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:123456@localhost:3306/userData?charset=utf8'
app.config['SQLALCHEMY_BINDS'] = {
    'master': 'mysql://root:123456@localhost:3306/userData?charset=utf8',
    'slave': 'mysql://root:123456@localhost:3306/userData?charset=utf8'
}
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# 初始化
db = SQLAlchemy(app)


class Trade(db.Model):
    """
    取引先のチャージ情報

    :param email:amazonログインイーメール
    :param start:チャージが始まる時間
    :param finish:チャージ終了の時間
    :param status:取引処理状態(0:未処理, 1:処理中, 2:処理完了, 3:エラー発生)
    """