예제 #1
0
파일: app.py 프로젝트: pybender/cloudml-ui
 def init_sql_db(self):
     self._sql_db = SQLAlchemy(self)
예제 #2
0
파일: app.py 프로젝트: Diya995/appredeshdj
'''------------------------------------------------------------------------------------------'''
import os
from flask import Flask, render_template, request
from flask.ext.sqlalchemy import SQLAlchemy
'''------------------------------------------------------------------------------------------'''
'''------------------------------------------------------------------------------------------'''
app = Flask(__name__)
'''------------------------------------------------------------------------------------------'''
'''------------------------------------------------------------------------------------------'''
#conectarBaseDatos
'''Realiza la conexion a la base de datos
Este metodo se encarga de realizar la conexion a la base de datos'''
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['DEBUG'] = True
bd = SQLAlchemy(app)
'''------------------------------------------------------------------------------------------'''
'''------------------------------------------------------------------------------------------'''


class Maquina(bd.Model):
    id_so = bd.Column(bd.Integer, primary_key=True)
    kernel = bd.Column(bd.String(100), unique=True)
    release = bd.Column(bd.String(100), unique=True)
    nodename = bd.Column(bd.String(100), unique=True)
    kernelv = bd.Column(bd.String(100), unique=True)
    machine = bd.Column(bd.String(100), unique=True)
    processor = bd.Column(bd.String(100), unique=True)
    so = bd.Column(bd.String(100), unique=True)
    hardware = bd.Column(bd.String(100), unique=True)
    user_logged = bd.Column(bd.String(100), unique=True)
예제 #3
0
class Testing(Config):
    TESTING = True
    CSRF_ENABLED = False
    SQLALCHEMY_DATABASE_URI = "sqlite:////tmp/%s_test.sqlite" % project_name
    SQLALCHEMY_ECHO = False


########NEW FILE########
__FILENAME__ = database
# -*- coding:utf-8 -*-

#--- SQLALCHEMY SUPPORT

# uncomment for sqlalchemy support
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()


def drop_all():
    db.drop_all()


def create_all():
    db.create_all()


def remove_session():
    db.session.remove()


#--- SQLALCHEMY SUPPORT END
예제 #4
0
#### config ####
################

application = Flask(__name__)
application.config.from_object('config.ProductionConfig')

####################
#### extensions ####
####################

login_manager = LoginManager()
login_manager.init_app(application)
bcrypt = Bcrypt(application)
mail = Mail(application)
toolbar = DebugToolbarExtension(application)
db = SQLAlchemy(application)

####################
#### blueprints ####
####################
with application.app_context():
    from main.views import main_blueprint
    from user.views import user_blueprint
    application.register_blueprint(main_blueprint)
    application.register_blueprint(user_blueprint)

####################
#### flask-login ####
####################

from models import User
예제 #5
0
def create_app(test_config=None):                   # For automated tests
    # Setup Flask and read config from ConfigClass defined above
    app = Flask(__name__)
    app.config.from_object(__name__+'.ConfigClass')

    # Load local_settings.py if file exists         # For automated tests
    try: app.config.from_object('local_settings')
    except: pass

    # Load optional test_config                     # For automated tests
    if test_config:
        app.config.update(test_config)

    # Initialize Flask extensions
    db = SQLAlchemy(app)                            # Initialize Flask-SQLAlchemy
    babel = Babel(app)                              # Initialize Flask-Babel
    mail = Mail(app)                                # Initialize Flask-Mail

    # Define the User data model. Make sure to add flask.ext.user UserMixin!!
    class User(db.Model, UserMixin):
        id = db.Column(db.Integer, primary_key=True)

        # User authentication information
        username = db.Column(db.String(50), nullable=True, 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=True, unique=True)
        confirmed_at = db.Column(db.DateTime())

        # User information
        active = db.Column('is_active', db.Boolean(), nullable=False, server_default='0')
        first_name = db.Column(db.String(100), nullable=False, server_default='')
        last_name = db.Column(db.String(100), nullable=False, server_default='')

        # Relationships
        roles = db.relationship('Role', secondary='user_roles',
                backref=db.backref('users', lazy='dynamic'))

    # Define UserEmail DataModel.
    class UserEmail(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

        # User email information
        email = db.Column(db.String(255), nullable=True, unique=True)
        confirmed_at = db.Column(db.DateTime())
        is_primary = db.Column(db.Boolean(), nullable=False, default=False)

        # Relationship
        user = db.relationship('User', uselist=False)

    class UserInvitation(db.Model):
        __tablename__ = 'user_invite'
        id = db.Column(db.Integer, primary_key=True)
        email = db.Column(db.String(255), nullable=False)
        # save the user of the invitee
        invited_by_user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
        # token used for registration page to identify user registering
        token = db.Column(db.String(100), nullable=False, server_default='')


    # Define the Role data model
    class Role(db.Model):
        id = db.Column(db.Integer(), primary_key=True)
        name = db.Column(db.String(50), unique=True)

    # Define the UserRoles data model
    class UserRoles(db.Model):
        id = db.Column(db.Integer(), primary_key=True)
        user_id = db.Column(db.Integer(), db.ForeignKey('user.id', ondelete='CASCADE'))
        role_id = db.Column(db.Integer(), db.ForeignKey('role.id', ondelete='CASCADE'))

    # Reset all the database tables
    db.create_all()

    # Setup Flask-User
    db_adapter = SQLAlchemyAdapter(db,  User, UserInvitationClass=UserInvitation)
    user_manager = UserManager(db_adapter, app)

    # Create regular 'member' user
    if not User.query.filter(User.username=='member').first():
        user = User(username='******', email='*****@*****.**', active=True,
                password=user_manager.hash_password('Password1'), confirmed_at=datetime.datetime.utcnow())
        db.session.add(user)
        db.session.commit()

    # Create 'user007' user with 'secret' and 'agent' roles
    if not User.query.filter(User.username=='user007').first():
        user1 = User(username='******', email='*****@*****.**', active=True,
                password=user_manager.hash_password('Password1'))
        user1.roles.append(Role(name='secret'))
        user1.roles.append(Role(name='agent'))
        db.session.add(user1)
        db.session.commit()

    # The '/' page is accessible to anyone
    @app.route('/')
    def home_page():
        # if current_user.is_authenticated():
        #     return user_profile_page()
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
            <h2>{%trans%}Home Page{%endtrans%}</h2>
            <p><a href="{{ url_for('user.login') }}">{%trans%}Sign in{%endtrans%}</a></p>
            {% endblock %}
            """)

    # The '/profile' page requires a logged-in user
    @app.route('/user/profile')
    @login_required                                 # Use of @login_required decorator
    @confirm_email_required
    def user_profile_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
            <h2>{%trans%}Profile Page{%endtrans%}</h2>
            <p> {%trans%}Hello{%endtrans%}
                {{ current_user.username or current_user.email }},</p>
            <p> <a href="{{ url_for('user.change_username') }}">
                {%trans%}Change username{%endtrans%}</a></p>
            <p> <a href="{{ url_for('user.change_password') }}">
                {%trans%}Change password{%endtrans%}</a></p>
            <p> <a href="{{ url_for('user.invite') }}">
                {%trans%}Invite User{%endtrans%}</a></p>
            <p> <a href="{{ url_for('user.logout') }}?next={{ url_for('user.login') }}">
                {%trans%}Sign out{%endtrans%}</a></p>
            {% endblock %}
            """)

    # The '/special' page requires a user that has the 'special' AND ('sauce' OR 'agent') role.
    @app.route('/special')
    @roles_required('secret', ['sauce', 'agent'])   # Use of @roles_required decorator
    def special_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
            <h2>{%trans%}Special Page{%endtrans%}</h2>
            {% endblock %}
            """)

    # For testing only
    app.db = db
    app.UserEmailClass = UserEmail

    return app
예제 #6
0
from flask_marshmallow import Marshmallow

import json

env = os.environ.get('FLASK_ENV', 'development')

app = Flask(__name__, static_folder="static")
app.config.from_pyfile('../config/config.py')

# setup logging
with open('config/logging-%s.yaml' % env) as f:
    import yaml
    logging.config.dictConfig(yaml.load(f))


db = SQLAlchemy(app, session_options={"autoflush": False})
# Define naming constraints so that Alembic just works
# See http://docs.sqlalchemy.org/en/rel_0_9/core/constraints.html#constraint-naming-conventions
db.metadata.naming_convention = {
    "ix": 'ix_%(column_0_label)s',
    "uq": "%(table_name)s_%(column_0_name)s_key",
    "ck": "ck_%(table_name)s_%(constraint_name)s",
    "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
    "pk": "pk_%(table_name)s"
}
migrate = Migrate(app, db, transaction_per_migration=True)
csrf = CsrfProtect(app)
mail = Mail(app)
ma = Marshmallow(app)

예제 #7
0
파일: webapp.py 프로젝트: xoraxax/dtg
from dtg.backgroundjobs import JOBS
from dtg.version import __version__


app = Flask("dtg")
app.config['SQLALCHEMY_DATABASE_URI'] = sys.dtg_db_path("main")
app.config["SQLALCHEMY_ECHO"] = sys.dtg_debug
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config["PROPAGATE_EXCEPTIONS"] = True
app.config['ASSETS_DEBUG'] = sys.dtg_debug
app.config['SESSION_COOKIE_NAME'] = "dtgsession"
SEQID_SLEEP = 10 # seconds
NIGHTLY_RUNTIME = time(1, 42), time(2, 42)

# initialize DB
db = SQLAlchemy(app, session_options=dict(autoflush=False))
generate_db_model(db)
from dtg.model import *
from dtg.forms import generate_forms
generate_forms(app, db)
from dtg.forms import *
db.create_all()
if not SystemInfo.query.first():
    initialize_db(db)

# setup secret key, do DB migrations
sys_info = SystemInfo.query.first()
app.secret_key = str(sys_info.secret_app_key)
if sys_info.db_rev != APP_DB_REV:
    if not sys.dtg_do_upgrade:
        raise Exception("Old database version, please backup your database and enable DB migrations.")
예제 #8
0
        # If the http response code is 200 then we process to add the
        # toolbar to the returned html response.
        if '__trace__' in real_request.args:
            for panel in self.debug_toolbars[real_request].panels:
                panel.process_response(real_request, response)

            if response.is_sequence:
                toolbar_html = self.debug_toolbars[real_request].render_toolbar()
                response.headers['content-type'] = 'text/html'
                response.response = [toolbar_html]
                response.content_length = len(toolbar_html)

        return response

db = SQLAlchemy(session_options={})
api = APIController(prefix='/api/0')
mail = Mail()
queue = Celery()
redis = Redis()
statsreporter = StatsReporter()
sentry = Sentry(logging=True, level=logging.WARN)


def create_app(_read_config=True, **config):
    app = flask.Flask(__name__,
                      static_folder=None,
                      template_folder=os.path.join(PROJECT_ROOT, 'templates'))

    # app.wsgi_app = TracerMiddleware(app.wsgi_app, app)
예제 #9
0
from flask import Flask
from flask import render_template
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.security import Security, SQLAlchemyUserDatastore, login_required, current_user

import config

application = Flask(__name__)
application.config.from_object(config)

database = SQLAlchemy(application)
from models import User, Role

data_store = SQLAlchemyUserDatastore(database, User, Role)
security = Security(application, data_store)


@application.before_first_request
def create_test_user():

    database.drop_all()
    database.create_all()

    data_store.create_user(email='*****@*****.**', password='******')

    database.session.commit()


@application.route('/')
@login_required
def index():
예제 #10
0
    CELERY_REDIS_MAX_CONNECTIONS = 5

    # Cache
    CACHE_TYPE = 'redis'
    CACHE_REDIS_URL = os.environ.get('REDIS_URL') or 'redis://localhost:6379'

    # Raygun
    RAYGUN_APIKEY = os.environ.get('RAYGUN_APIKEY') or 'debug'
    GEOCODE_APIKEY = os.environ.get('GEOCODE_APIKEY')


app = Flask(__name__)
app.config.from_object(__name__ + '.ConfigClass')

Compress(app)  # Initialize Flask-Compress
db = SQLAlchemy(app)  # Initialize Flask-SQLAlchemy
mail = Mail(app)  # Initialize Flask-Mail

if not app.debug:
    flask_raygun.Provider(app, app.config['RAYGUN_APIKEY']).attach()

celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)

cache = Cache(app,
              config={
                  'CACHE_TYPE': app.config['CACHE_TYPE'],
                  'CACHE_REDIS_URL': app.config['CACHE_REDIS_URL'],
              })

from app import views, models, forms, tasks
예제 #11
0
# -*- encoding: utf-8 -*-
"""
Python Aplication Template
Licence: GPLv3
"""

from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.pymongo import PyMongo
from flask.ext.login import LoginManager

app = Flask(__name__)

#Configuration of application, see configuration.py, choose one and uncomment.
#app.config.from_object('configuration.ProductionConfig')
app.config.from_object('app.configuration.DevelopmentConfig')
#app.config.from_object('configuration.TestingConfig')

bs = Bootstrap(app)  #flask-bootstrap
db = SQLAlchemy(app)  #flask-sqlalchemy

lm = LoginManager()
lm.setup_app(app)
lm.login_view = 'login'

from app import views, models
예제 #12
0
# Copyright (C) 2014-2016 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.

import json

from datetime import datetime
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.inspection import inspect

db = SQLAlchemy(session_options=dict(autoflush=True))
ALEMBIC_VERSION = "4b86bc0d40aa"


class Serializer(object):
    """Serialize a query result object."""
    def to_dict(self):
        ret = {}
        for key in inspect(self).attrs.keys():
            ret[key] = getattr(self, key)
        return ret


class StringList(db.TypeDecorator):
    """List of comma-separated strings as field."""
    impl = db.Text

    def process_bind_param(self, value, dialect):
        return ", ".join(value)

    def process_result_value(self, value, dialect):
예제 #13
0
import os

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy, Model
from flask.ext.cache import Cache
from flask.ext.sqlalchemy_cache import CachingQuery

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
app.config['DEBUG'] = True
app.config['CACHE_TYPE'] = 'memcached'

# set up Flask-SQLAlchemy with Caching Query
Model.query_class = CachingQuery
db = SQLAlchemy(app, session_options={'query_cls': CachingQuery})


class Country(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return self.name


class State(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
예제 #14
0
# csrf_token protect
csrf = SeaSurf(app)

# apply SSL termination handling
app.request_class = ProxiedRequest

# configuration file
if os.path.isfile('./DEV'):
    app.config.from_object('config.DebugConfiguration')
else:
    app.config.from_object('config.BaseConfiguration')

# other app'ish things
login_manager = LoginManager(app)  # login manager
manager = Manager(app)  # shell actions manager
db = SQLAlchemy(app)  # database connection
bcrypt = Bcrypt(app)  # hashing function

# users module blueprint
from webapp.handlers.userhandlers import mod as usersModule
app.register_blueprint(usersModule)

# configure module blueprint
from webapp.handlers.configurehandlers import mod as configureModule
app.register_blueprint(configureModule)

# api module blueprint
from webapp.handlers.apihandlers import mod as APIModule
app.register_blueprint(APIModule)

# socket module blueprint
예제 #15
0
from flask.ext.sqlalchemy import SQLAlchemy
from werkzeug import generate_password_hash, check_password_hash

db = SQLAlchemy()  # create SQLAlchemy object


class User(db.Model):  # Create a User class to use in the database
    # Properties
    __tablename__ = 'users'
    uid = db.Column(db.Integer, primary_key=True)
    firstname = db.Column(db.String(100))
    lastname = db.Column(db.String(100))
    email = db.Column(db.String(120), unique=True)
    pwdhash = db.Column(db.String(54))

    # Methods
    def __init__(self, firstname, lastname, email, password):
        self.firstname = firstname.title()
        self.lastname = lastname.title()
        self.email = email.lower()
        self.set_password(password)

    def set_password(self, password):  # password hash
        self.pwdhash = generate_password_hash(password)

    def check_password(self,
                       password):  # Used for checking if the password matches
        return check_password_hash(self.pwdhash, password)
예제 #16
0
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# =================================================================

from flask import Flask

from flask.ext.sqlalchemy import SQLAlchemy

APP = Flask(__name__)
APP.config.from_pyfile('config.py')
APP.config.from_pyfile('../instance/config.py')

DB = SQLAlchemy(APP)
예제 #17
0
"""
    This script initializes the web app
"""

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from pymongo import Connection

app = Flask(__name__)
dbSQL = SQLAlchemy(app)

# SQL DB for core/structured storage, such as  by organizing or parsing data from MongoDB
# Set up connection with postgresql
app.config.from_pyfile('config.py')

# MongoDB for fast unstructured data storage, such as info crawled from webpages, twitter, etc.
# Set up mongoDB engine
con = Connection()
# Get database record - businessDB which contains business lincense info
dbMongo = con.businessDB

from GreenMoon import views
예제 #18
0
# coding=utf-8
from flask import current_app
from flask.ext.sqlalchemy import SQLAlchemy

__author__ = 'GaoJie'

db = SQLAlchemy(session_options={'autocommit': True, 'autoflush': True})


def connected(engine):
    conn_map = {}

    def f(**kwargs):
        if not kwargs:
            # 默认参数
            kwargs = {"autocommit": True}
        v = ''.join(["%s%s" % (str(k), str(v)) for k, v in kwargs.items()])
        m5 = hashlib.md5()
        m5.update(v)
        key = m5.hexdigest()
        if key not in conn_map:
            conn_map[key] = engine.connect().execution_options(**kwargs)
        return conn_map[key]
    return f
예제 #19
0
파일: model.py 프로젝트: BenDoan/SPA
    def __init__(self, app):
        self.db = SQLAlchemy(app)
        db = self.db

        class User(self.db.Model):
            __tablename__ = 'users'

            id = db.Column(db.Integer, primary_key=True)
            username = db.Column(db.String(80), unique=True)
            email = db.Column(db.String(120))
            password = db.Column(db.String)
            authenticated = db.Column(db.Boolean())
            schedule = db.Column(db.String)

            def __init__(self, username, email):
                self.username = username
                self.email = email
                self.authenticated = False

            def __str__(self):
                return "User: {}".format((self.id, self.username, self.email,
                                          self.password, self.authenticated))

            def is_authenticated(self):
                return self.authenticated

            def is_active(self):
                return self.is_authenticated()

            def is_anonymous(self):
                return False

            def get_id(self):
                return self.username

        self.User = User

        class Course(self.db.Model):
            __tablename__ = 'courses'
            __table_args__ = (UniqueConstraint('college', 'number'), )

            id = db.Column(db.Integer, primary_key=True)
            number = db.Column(db.Integer, nullable=False)
            title = db.Column(db.String, nullable=False)
            desc = db.Column(db.String, nullable=False)
            _prereqs = db.Column(db.String)
            college = db.Column(db.String, nullable=False)
            credits = db.Column(db.Integer, nullable=False)

            def __init__(self, number="", title="", desc="", prereqs=""):
                self.number = number
                self.title = title
                self.desc = desc
                self._prereqs = prereqs

            @property
            def prereqs(self):
                IDENT_REGEX = r'([A-Z]{2,4}) ?([0-9]{4})'
                #FIXME: assumed course ident format, doesn't deal with ors
                chopped_preqreqs = self._prereqs.split("or")[0]
                matches = re.findall(IDENT_REGEX, chopped_preqreqs)

                return [" ".join(x) for x in matches]

            @prereqs.setter
            def prereqs(self, val):
                self._prereqs = val

            @property
            def ident(self):
                return "{} {}".format(self.college, self.number)

            def __getitem__(self,
                            compare):  #dirty hack to make sorting work...
                if compare == 'number':
                    return self.number
                elif compare == 'college':
                    return self.college

            def __str__(self):
                return "Course: {}".format(
                    (self.id, self.number, self.title, self.desc, self.prereqs,
                     self.college))

        self.Course = Course

        class Requirement(self.db.Model):
            __tablename__ = 'requirements'
            __table_args__ = (UniqueConstraint('major', 'name'), )

            id = db.Column(db.Integer, primary_key=True)
            name = db.Column(db.String)
            major = db.Column(db.String, nullable=False)
            credits = db.Column(db.Integer, nullable=False)

            def __init__(self, name, major, credits):
                self.name = name
                self.major = major
                self.credits = credits

            def __str__(self):
                return "Requirement: {}".format(
                    (self.id, self.name, self.major, self.credits))

        self.Requirement = Requirement

        class CourseRequirement(self.db.Model):
            __tablename__ = 'class_requirements'
            id = db.Column(db.Integer, primary_key=True)

            requirement_id = db.Column(db.Integer,
                                       db.ForeignKey('requirements.id'),
                                       nullable=False)
            requirement = db.relationship('Requirement',
                                          backref=db.backref(
                                              'CourseRequirement',
                                              lazy='dynamic'))

            course_id = db.Column(db.Integer,
                                  db.ForeignKey('courses.id'),
                                  nullable=False)
            course = db.relationship('Course',
                                     backref=db.backref('CourseRequirement',
                                                        lazy='dynamic'))

            def __init__(self, requirement, course):
                self.requirement = requirement
                self.course = course

            def __str__(self):
                return "CourseRequirement: {}".format(
                    (self.id, self.requirement, self.course))

        self.CourseRequirement = CourseRequirement

        class UserHistory(self.db.Model):
            id = db.Column(db.Integer, primary_key=True)

            course_id = db.Column(db.Integer, db.ForeignKey('courses.id'))
            course = db.relationship('Course',
                                     backref=db.backref('UserHistory',
                                                        lazy='dynamic'))

            user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
            user = db.relationship('User',
                                   backref=db.backref('UserHistory',
                                                      lazy='dynamic'))

            def __init__(self, course, user):
                self.course = course
                self.user = user

            def __str__(self):
                return "UserHistory: {}".format(
                    (self.id, self.course, self.user))

        self.UserHistory = UserHistory
예제 #20
0
"""
    The app core, initialize necessary objects
"""
from blinker import Namespace
from flask import session
from flask.ext.bouncer import Bouncer
from flask.ext.cas import CAS

from flask.ext.login import LoginManager, user_logged_in
from flask.ext.sqlalchemy import SQLAlchemy

# initialize database
db = SQLAlchemy(session_options={'expire_on_commit': False})

# initialize Flask-Bouncer
bouncer = Bouncer()

# initialize Flask-Login
login_manager = LoginManager()

# initialize CAS
cas = CAS()

# create custom namespace for signals
event = Namespace()


# subscribe user_logged_in signal to generate auth token
@user_logged_in.connect
def generate_session_token(sender, user, **extra):
    session['session_token'] = user.generate_session_token()
예제 #21
0
from flask import Flask, request, Response
from flask import render_template, send_from_directory, url_for
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.mobility import Mobility
from logging import StreamHandler, DEBUG
import utility
import config

basedir = config.basedir
baseurl = config.baseurl

flask_app = Flask(__name__, template_folder='public/template')
flask_app.config.from_object('config')
db = SQLAlchemy(flask_app)
Mobility(flask_app)

file_handler = StreamHandler()
flask_app.logger.setLevel(DEBUG)  # set the desired logging level here
flask_app.logger.addHandler(file_handler)

import models
import controllers
import scripts
예제 #22
0
from flask import Flask, request
from flask import render_template

from flask.ext.admin import Admin, BaseView, expose
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.admin.contrib.sqla import ModelView
from flask.ext import login

from consts import *

app = Flask(__name__)  #实现一个Flask类的实例
app.config[
    'SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost:3306/cherry'  #设置连接数据库地址
app.config['SECRET_KEY'] = '123456790'
db = SQLAlchemy(app)  #实现SQLAlchemy 类的实例
app.debug = True  #开启调试模式


class Menu(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    date = db.Column(db.String(64), unique=True)
    menu_str = db.Column(db.String(128))

    def __unicode__(self):
        return 'hello'


class OrderMeal(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    date = db.Column(db.String(64))
예제 #23
0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app_tests = Flask(__name__)
app_tests.config[
    'SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://api2k15:@127.0.0.1:3306/nba_flask_test'
app_tests.config['WHOOSH_BASE'] = 'path_tests/to/whoosh/base'
db_tests = SQLAlchemy(app_tests)
예제 #24
0
def create_app(test_config=None):  # For automated tests
    # Setup Flask and read config from ConfigClass defined above
    app = Flask(__name__)
    app.config.from_object(__name__ + '.ConfigClass')

    # Load local_settings.py if file exists         # For automated tests
    try:
        app.config.from_object('local_settings')
    except:
        pass

    # Over-write app config                         # For automated tests
    if test_config:
        for key, value in test_config.items():
            app.config[key] = value

    # Setup Flask-Mail, Flask-Babel and Flask-SQLAlchemy
    app.mail = Mail(app)
    app.babel = babel = Babel(app)
    app.db = db = SQLAlchemy(app)

    @babel.localeselector
    def get_locale():
        translations = [
            str(translation) for translation in babel.list_translations()
        ]
        return request.accept_languages.best_match(translations)

    # Define the User-Roles pivot table
    user_roles = db.Table(
        'user_roles', db.Column('id', db.Integer(), primary_key=True),
        db.Column('user_id', db.Integer(),
                  db.ForeignKey('user.id', ondelete='CASCADE')),
        db.Column('role_id', db.Integer(),
                  db.ForeignKey('role.id', ondelete='CASCADE')))

    # Define Role model
    class Role(db.Model):
        id = db.Column(db.Integer(), primary_key=True)
        name = db.Column(db.String(50), unique=True)

    # Define User model. Make sure to add flask.ext.user UserMixin!!
    class User(db.Model, UserMixin):
        id = db.Column(db.Integer, primary_key=True)
        user_profile_id = db.Column(db.Integer,
                                    db.ForeignKey('user_profile.id'),
                                    nullable=True,
                                    default=None)
        # Flask-User fields
        active = db.Column(db.Boolean(), nullable=False, default=False)
        email = db.Column(db.String(255), nullable=False, default='')
        password = db.Column(db.String(255), nullable=False, default='')
        # Relationships
        user_profile = db.relationship('UserProfile',
                                       uselist=False,
                                       foreign_keys=[user_profile_id])
        roles = db.relationship('Role',
                                secondary=user_roles,
                                backref=db.backref('users', lazy='dynamic'))

    class UserProfile(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        first_name = db.Column(db.String(50), nullable=False, default='')
        last_name = db.Column(db.String(50), nullable=False, default='')

    # Reset all the database tables
    db.create_all()

    # Setup Flask-User
    db_adapter = SQLAlchemyAdapter(db,
                                   UserClass=User,
                                   UserProfileClass=UserProfile)
    user_manager = UserManager(db_adapter, app, register_form=MyRegisterForm)

    # The '/' page is accessible to anyone
    @app.route('/')
    def home_page():
        if current_user.is_authenticated():
            return profile_page()
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
            <h2>{%trans%}Home Page{%endtrans%}</h2>
            <p><a href="{{ url_for('user.login') }}">{%trans%}Sign in{%endtrans%}</a></p>
            {% endblock %}
            """)

    # The '/profile' page requires a logged-in user
    @app.route('/profile')
    @login_required  # Use of @login_required decorator
    def profile_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
            <h2>{%trans%}Profile Page{%endtrans%}</h2>
            <p> {%trans%}Hello{%endtrans%}
                {{ current_user.user_profile.first_name }},</p>
            <p> <a href="{{ url_for('user.change_password') }}">
                {%trans%}Change password{%endtrans%}</a></p>
            <p> <a href="{{ url_for('user.logout') }}?next={{ url_for('user.login') }}">
                {%trans%}Sign out{%endtrans%}</a></p>
            {% endblock %}
            """)

    return app
예제 #25
0
def get_db():  # noqa
    """Get modified db object."""
    database = SQLAlchemy()

    class String(database.String):
        """Simple subclass of sqlalchemy.orm.String which provides a default
    length for `String` types to satisfy MySQL
    """

        # pylint: disable=too-few-public-methods
        # this class is just to set the default string length and is not meant to
        # do anything else, so it does not need any other public methods.

        def __init__(self, length=None, *args, **kwargs):
            # TODO: Check for MySQL and only apply when needed
            if length is None:
                length = 250
            super(String, self).__init__(length, *args, **kwargs)

    database.String = String

    database.session.plain_commit = database.session.commit

    database.session.commit_hooks_enable_flag = CommitHooksEnableFlag()

    def pre_commit_hooks():
        """All pre commit hooks handler."""
        with benchmark("pre commit hooks"):
            if not database.session.commit_hooks_enable_flag:
                return
            database.session.flush()
            if hasattr(database.session, "reindex_set"):
                database.session.reindex_set.indexing_hook()

    def post_commit_hooks():
        """All post commit hooks handler."""
        with benchmark("post commit hooks"):
            if not database.session.commit_hooks_enable_flag:
                return
            # delete flask caches in order to avoid
            # using cached instances after commit
            if hasattr(flask.g, "user_cache"):
                del flask.g.user_cache
            if hasattr(flask.g, "user_creator_roles_cache"):
                del flask.g.user_creator_roles_cache
            from ggrc.models.hooks import acl
            acl.after_commit()

    database.session.post_commit_hooks = post_commit_hooks
    database.session.pre_commit_hooks = pre_commit_hooks

    def hooked_commit(*args, **kwargs):
        """Commit override function.

    This function is meant for a single after commit hook that should only be
    used for ACL propagation.
    """
        database.session.pre_commit_hooks()
        with benchmark("plain commit"):
            database.session.plain_commit(*args, **kwargs)
        database.session.post_commit_hooks()

    database.session.commit = hooked_commit

    return database
예제 #26
0
파일: database.py 프로젝트: pyrog/skylines
from flask.ext.sqlalchemy import SQLAlchemy


def query(cls, **kw):
    q = db.session.query(cls)

    if kw:
        q = q.filter_by(**kw)

    return q


def get(cls, id):
    return cls.query().get(id)


def exists(cls, **kw):
    return cls.query(**kw).first() is not None


db = SQLAlchemy(session_options=dict(expire_on_commit=False))

db.Model.flask_query = db.Model.query
db.Model.query = classmethod(query)
db.Model.get = classmethod(get)
db.Model.exists = classmethod(exists)
import sys
import os
import hashlib
import random
import time
from datetime import datetime

print "importing sha3"
import sha3

from flask.ext.sqlalchemy import SQLAlchemy

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from apper import *

user_db = SQLAlchemy(app)


#https://github.com/mrjoes/flask-admin/blob/master/examples/auth/app.py
class User(user_db.Model):
    id = user_db.Column(user_db.Integer, primary_key=True)
    first_name = user_db.Column(user_db.String(100))
    last_name = user_db.Column(user_db.String(100))
    login = user_db.Column(user_db.String(80), unique=True)
    email = user_db.Column(user_db.String(120))
    password = user_db.Column(user_db.String(400))
    salt = user_db.Column(user_db.String(400))

    # Flask-Login integration
    def is_authenticated(self):
        return True
from flask import Flask, render_template, request
import requests
import datetime
from flask.ext.sqlalchemy import SQLAlchemy
central_server_app = Flask(__name__)

central_server_app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///investigations.db" #os.environ["DATABASE_URL"]
central_server_db = SQLAlchemy(central_server_app)

class InvestigationLogger(central_server_db.Model):
    __tablename__ = 'investigation_logger'
    id = central_server_db.Column(central_server_db.Integer, primary_key=True)
    investigation_id = central_server_db.Column(central_server_db.String(400))
    timestamp = central_server_db.Column(central_server_db.DateTime, default=datetime.datetime.now)
    
    def __init__(self,investigation_id):
        self.investigation_id = investigation_id 

    def __repr__(self):
        return '<investigation_id %r>' % self.investigation_id

@central_server_app.route("/<investigation_id>",methods=["GET","POST"])
def index(investigation_id):
    try:
        investigation_id = str(investigation_id)
        investigation_log = InvestigationLogger(investigation_id)
        central_server_db.session.add(investigation_log)
        central_server_db.session.commit()
        return "success"
    except:
        return "failure"
예제 #29
0
import datetime
from flask import Flask, render_template, request
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.bcrypt import Bcrypt

app = Flask(__name__)
app.config.from_pyfile('_config.py')
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)

from project.users.views import users_blueprint
from project.tasks.views import tasks_blueprint

#register blueprints
app.register_blueprint(users_blueprint)
app.register_blueprint(tasks_blueprint)


@app.errorhandler(404)
def not_found(error):
    if app.debug is not True:
        now = datetime.datetime.now()
        r = request.url
        with open('error.log', 'a') as f:
            current_timestamp = now.strftime("%d-%m-%Y %H:%M:%S")
            f.write("\n404 error at {}: {} ".format(current_timestamp, r))
    return render_template('404.html'), 404


@app.errorhandler(500)
def internal_error(error):
예제 #30
0
import glob
from utilities import CsvReader
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.security import Security, SQLAlchemyUserDatastore, roles_required, current_user, LoginForm
from collections import OrderedDict
from sqlalchemy import distinct, func
from apscheduler.scheduler import Scheduler
import united
from flask.ext.compress import Compress
import argparse
from sqlalchemy.exc import OperationalError

from oauth import OAuthSignIn

app = utilities.init_flask(__name__)
db = SQLAlchemy(app)
app.config.from_object(__name__)
app.config['SECURITY_REGISTERABLE'] = False
app.config['SECURITY_USER_IDENTITY_ATTRIBUTES'] = 'username'
app.config['BABEL_DEFAULT_LOCALE'] = 'he'
app.config['OAUTH_CREDENTIALS'] = {
    'facebook': {
        'id': os.environ.get('FACEBOOK_KEY'),
        'secret': os.environ.get('FACEBOOK_SECRET')
    },
    'google': {
        'id': os.environ.get('GOOGLE_LOGIN_CLIENT_ID'),
        'secret': os.environ.get('GOOGLE_LOGIN_CLIENT_SECRET')
    }
}