Beispiel #1
0
def create_app(object_name):
    scheduler = APScheduler()

    app = Flask(__name__)
    app.config.from_object(object_name)

    db.app = app
    db.init_app(app)
    Bootstrap(app)
    login_manager.init_app(app)
    bcrypt.init_app(app)
    scheduler.init_app(app)

    app.register_blueprint(admin_blueprint)
    app.register_blueprint(main_blueprint)
    app.register_blueprint(result_blueprint)
    app.register_blueprint(librarian_blueprint)
    app.register_blueprint(reader_blueprint)

    @app.route('/')
    def index():
        return redirect(url_for('main.index'))

    scheduler.start()
    return app
Beispiel #2
0
def create_app(config_name):
    # __name__ 决定应用根目录
    # app = Flask(__name__, static_url_path='', static_folder='')
    app = Flask(__name__)
    # 实例化flask_admin
    # 初始化app配置
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    # 扩展应用初始化
    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    configure_uploads(app, excels)
    flask_admin.init_app(app)
    flask_admin.add_view(MyBaseView(name='报表主页', endpoint='index'))
    flask_admin.add_view(MyUserView(User, db.session, name='用户管理'))
    flask_admin.add_view(MyBaobiaoView(BaobiaoToSet, db.session, name='报表名管理'))
    flask_admin.add_view(FileAdmin(staticfilepath, name='报表模板与生成文件管理'))

    # 注册蓝本
    from .main import _main as main_blueprint
    app.register_blueprint(main_blueprint, url_prefix='/main')
    from .auth import _auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')
    from .api import _api as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/api')
    from .baobiao import _baobiao as baobiao_blueprint
    app.register_blueprint(baobiao_blueprint, url_prefix='/baobiao')
    from .analyzingreport import _analyzingreport as analyzingreport_blueprint
    app.register_blueprint(analyzingreport_blueprint,
                           url_prefix='/analyzingreport')

    return app
Beispiel #3
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('config.py')
    db.init_app(app)

    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'login'

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(user_id)

    @app.route("/")
    def index():
        authenticated = current_user
        if current_user.is_authenticated:
            return redirect(url_for('index'))
        title = 'Меню Fake Шоколадницы '
        Products_list = Products.query.all()
        return render_template('index.html',
                               page_title=title,
                               Products_list=Products_list)

    @app.route('/login')
    def login():
        if current_user.is_authenticated:
            return redirect(url_for('index'))
        title = 'Авторизация'
        login_form = LoginForm()
        return render_template('login.html', page_title=title, form=login_form)

    @app.route('/process-login', methods=['POST'])
    def process_login():
        form = LoginForm()
        if form.validate_on_submit():
            user = User.query.filter_by(username=form.username.data).first()
            if user and user.check_password(form.password.data):
                login_user(user)
                flash('Вы вошли на сайт')
                return redirect(url_for('index'))

        flash('Неправильное имя пользователя или пароль')
        return redirect(url_for('login'))

    @app.route('/logout')
    def logout():
        logout_user()
        flash('Вы успешно разлогинились')
        return redirect(url_for('index'))

    @app.route('/admin')
    @login_required
    def admin_index():
        if current_user.is_admin:
            return 'Привет админ'
        else:
            return 'Ты не админ!'

    return app
Beispiel #4
0
def create_app(object_name):
    app = MyFlask(__name__)
    app.config.from_object(object_name)

    db.init_app(app)

    @app.route('/')
    def index():
        # statement = text("""SELECT COUNT(*) FROM position""")
        # result = db.engine.execute(statement)
        # print(result.fetchall())
        return redirect(url_for('main.home'))

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

    @app.errorhandler(500)
    def page_not_found(error):
        return render_template('error/500.html'), 500

    app.register_blueprint(main_blueprint)
    app.register_blueprint(analysis_blueprint)

    return app
Beispiel #5
0
def create_app():
    app = Flask(__name__)
    app.config['DEBUG'] = True
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///webapp/example.db'

    db.init_app(app)
    register_blueprints(app)

    return app
Beispiel #6
0
def create_app(object_name):
    app = Flask(__name__)
    app.config.from_object(object_name)

    db.init_app(app)

    @app.route('/')
    def index():
        return 'hello, world'

    return app
Beispiel #7
0
def create_app(object_name):
    app = Flask(__name__)
    app.config.from_object(object_name)

    db.init_app(app)

    @app.route('/')
    def index():
        return redirect(url_for('blog.home'))

    app.register_blueprint(blog_blueprint)

    return app
Beispiel #8
0
def create_app():
    print('Running with settings from: {}'
          .format(os.environ['APP_SETTINGS_FILE']))

    flask_app = Flask(__name__)
    flask_app.config.from_envvar('APP_SETTINGS_FILE')
    flask_app.secret_key = flask_app.config['SECRET_KEY']

    with flask_app.app_context():
        db.init_app(flask_app)  # Required by Flask-SQLAlchemy
        if not flask_app.config['TESTING']:
            db.create_all()
    return flask_app
Beispiel #9
0
def create_app(object_name):
    """

    :argument object_name: the python path of the config object
    :return: app
    """

    app = Flask(__name__)
    app.config.from_object(object_name)

    db.init_app(app)

    app.register_blueprint(main_blueprint)

    return app
Beispiel #10
0
def create_app(object_name):
    """
    An flask application factory, as explained here:
    http://flask.pocoo.org/docs/patterns/appfactories/

    Arguments:
        object_name: the python path of the config object,
                     e.g. project.config.ProdConfig
    """

    app = Flask(__name__)
    app.config.from_object(object_name)

    rest_api.add_resource(
        AuthApi,
        '/api/auth',
    )
    rest_api.add_resource(
        PostApi,
        '/api/post',
        '/api/post/<int:post_id>',
    )
    rest_api.init_app(app)

    db.init_app(app)
    mongo.init_app(app)
    bcrypt.init_app(app)
    login_manager.init_app(app)
    principals.init_app(app)

    @identity_loaded.connect_via(app)
    def on_identity_loaded(sender, identity):
        # Set the identity user object
        identity.user = current_user

        # Add the UserNeed to the identity
        if hasattr(current_user, 'id'):
            identity.provides.add(UserNeed(current_user.id))

        # Add each role to the identity
        if hasattr(current_user, 'roles'):
            for role in current_user.roles:
                identity.provides.add(RoleNeed(role.name))

    app.register_blueprint(main_blueprint)
    app.register_blueprint(blog_blueprint)

    return app
def create_app(object_name):
    app = Flask(__name__)
    app.config.from_object(object_name)

    db.init_app(app)
    csrf.init_app(app)
    mail.init_app(app)
    configure_uploads(app, icon)

    admin.init_app(app)

    app.register_blueprint(index_blue)
    app.register_blueprint(community_blue)
    app.register_blueprint(user_blue)

    return app
Beispiel #12
0
def create_app(object_name):
    """
    A flask application factory as explained here:
    http://flask.pocoo.org/docs/patterns/appfactories/
    :param   object_name: the python path of the config object
                        e.g. project.config.ProdConfig
    :return: app: The StudyBuddy application.
    """
    app = Flask(__name__)
    app.config.from_object(object_name)

    db.init_app(app)
    bcrypt.init_app(app)

    app.register_blueprint(main_blueprint)
    app.register_blueprint(sb_blueprint)

    return app
Beispiel #13
0
def create_app(object_name):
    """
    An flask application factory, as explained here:
    http://flask.pocoo.org/docs/patterns/appfactories/

    Arguments:
        object_name: the python path of the config object,
                     e.g. project.config.ProdConfig

    """
    from webapp.models import db
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://*****:*****@localhost:5432/test5'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config.from_object('webapp.config.ProdConfig')
    #app.config.from_object('webapp.config.DevConfig')
    db.init_app(app)
    try:
        db.create_all()
    except Exception as e:
        print(e)
    bcrypt.init_app(app)
    oid.init_app(app)
    login_manager.init_app(app)
    principals.init_app(app)
    # db.create_all()

    app.register_blueprint(account_blueprint)
    app.register_blueprint(drivers_blueprint)
    app.register_blueprint(dvir_blueprint)
    app.register_blueprint(logs_blueprint)
    app.register_blueprint(trucks_blueprint)
    app.register_blueprint(elogstation_blueprint)
    # Create admin
    import flask_admin as admin1

    admin = admin1.Admin(app, 'Example: Auth', index_view=MyAdminIndexView(), base_template='my_master.html')
    # Add view
    admin.add_view(MyModelView(User, db.session))
    admin.add_view(MyModelView(Person, db.session))
    admin.add_view(MyModelView(companyuser, db.session))
    admin.add_view(MyModelView(company1, db.session))
    admin.add_view(MyModelView(ELD, db.session))
    return app
Beispiel #14
0
def create_app():
    """Создание приложения"""

    app = Flask(__name__)
    app.config.from_pyfile('config.py')
    db.init_app(app)
    migrate = Migrate()
    migrate.init_app(app, db)

    @app.route('/')
    def index():
        """Главная страница: обработка входящих писем"""

        messages = fetch_mail()
        add_ticket(messages)

        return 'Работаем!'

    @app.route('/send')
    def email_form():
        """Форма отправки email"""

        form = SendForm()
        return render_template('email_form.html',
                               title='Отправка email',
                               form=form)

    @app.route('/email_proccess', methods=['POST'])
    def email_proccess():
        """Процесс отправки email"""

        form = SendForm()
        subject = 'Тестовая тема'
        message = 'Тестовое сообщение'

        if form.validate_on_submit():
            receiver = form.email.data
            message = send_email(receiver, subject, message)
            flash(message)

            return redirect(url_for('email_form'))

    return app
Beispiel #15
0
def create_app(object_name):
    # 实例一个flask项目
    app = Flask(__name__)

    # 调用选择的模式
    # 在config.py文件里面:webapp.config.DecConfig / webapp.config.ProConfig
    app.config.from_object(object_name)

    # 将数据库和app建立关联
    db.init_app(app)

    # 定义初始页
    @app.route('/')
    def index():
        return redirect(url_for('blog.home'))

    # 注册蓝图
    app.register_blueprint(blog_blueprint)
    return app
def create_app(object_name):
    """
    An flask application factory, as explained here:
    http://flask.pocoo.org/docs/patterns/appfactories/

    Arguments:
        object_name: the python path of the config object,
                     e.g. project.config.ProdConfig
    """

    app = Flask(__name__)
    app.config.from_object(object_name)

    db.init_app(app)

    app.register_blueprint(main_blueprint)
    app.register_blueprint(chart_blueprint)
    app.register_blueprint(monte_carlo_blueprint)

    return app
def create_app(object_name):
    app = Flask(__name__)
    app.config.from_object(object_name)

    db.init_app(app)

    bcrypt.init_app(app)
    login_manager.init_app(app)
    debug_toolbar.init_app(app)
    cache.init_app(app)

    rest_api = Api(app)
    rest_api.add_resource(PostApi,
            '/restapi/post',
            '/restapi/post/<int:post_id>',
            endpoint='restapi')

    app.register_blueprint(main_blueprint)
    app.register_blueprint(blog_blueprint)
    return app
Beispiel #18
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('config.py')
    db.init_app(app)
    #mail = Mail()
    #mail.init_app(app)
    migrate = Migrate(app, db)

    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'user.login'

    app.register_blueprint(admin_blueprint)
    app.register_blueprint(event_blueprint)
    app.register_blueprint(user_blueprint)

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(user_id)

    return app
def create_app(object_name):
    """
    An flask application factory, as explained here:
    http://flask.pocoo.org/docs/patterns/appfactories/

    Arguments:
        object_name: the python path of the config object,
                     e.g. webapp.settings.ProdConfig

        env: The name of the current environment, e.g. prod or dev
    """
    app = Flask(__name__)
    """SXI"""
    app.config.from_object(object_name)

    db = SQLAlchemy(app)
    # initialize the cache
    cache.init_app(app)

    # initialize the debug tool bar
    debug_toolbar.init_app(app)

    # initialize SQLAlchemy
    db.init_app(app)

    login_manager.init_app(app)

    # Import and register the different asset bundles
    assets_env.init_app(app)
    assets_loader = PythonAssetsLoader(assets)
    for name, bundle in assets_loader.load_bundles().items():
        assets_env.register(name, bundle)

    # register our blueprints
    app.register_blueprint(main)

    main.app = app

    return app
Beispiel #20
0
def create_app(object_name):
    app = Flask(__name__)
    app.config.from_object(object_name)

    db.init_app(app)
    bcrypt.init_app(app)
    login_manager.init_app(app)
    principals.init_app(app)
    celery.init_app(app)

    rest_api.add_resource(PostApi,
                          '/api/post',
                          '/api/post/<int:post_id>',
                          endpoint='api')
    rest_api.add_resource(AuthApi, '/api/auth')
    rest_api.init_app(app)

    @identity_loaded.connect_via(app)
    def on_identity_loaded(sender, identity):
        #set the identity user object
        identity.user = current_user

        #add the user need to the identity
        if hasattr(current_user, 'id'):
            identity.provides.add(UserNeed(current_user.id))

        #add each role to the identity
        if hasattr(current_user, 'roles'):
            for role in current_user.roles:
                identity.provides.add(RoleNeed(role.name))

    # @app.route('/')
    # def index():
    # 	return redirect(url_for('blog.home'))

    app.register_blueprint(blog_blueprint)
    app.register_blueprint(main_blueprint)

    return app
Beispiel #21
0
def create_app(object_name, env="prod"):
    """
    An flask application factory, as explained here:
    http://flask.pocoo.org/docs/patterns/appfactories/

    Arguments:
        object_name: the python path of the config object,
                     e.g. webapp.settings.ProdConfig

        env: The name of the current environment, e.g. prod or dev
    """

    app = Flask(__name__)

    app.config.from_object(object_name)
    app.config['ENV'] = env

    # initialize the cache
    cache.init_app(app)

    # initialize the debug tool bar
    debug_toolbar.init_app(app)

    # initialize SQLAlchemy
    db.init_app(app)

    login_manager.init_app(app)

    # Import and register the different asset bundles
    assets_env.init_app(app)
    assets_loader = PythonAssetsLoader(assets)
    for name, bundle in assets_loader.load_bundles().items():
        assets_env.register(name, bundle)

    # register our blueprints
    app.register_blueprint(main)

    return app
Beispiel #22
0
def create_app(object_name):
    """


    """
    from models import db
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///../databasetest.db'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config.from_object('config.ProdConfig')
    db.init_app(app)
    db.create_all()
    bcrypt.init_app(app)
    oid.init_app(app)
    login_manager.init_app(app)
    principals.init_app(app)
    celery.init_app(app)
    # Create admin
    import flask_admin as admin1
    admin = admin1.Admin(app, 'Elogstation', index_view=MyAdminIndexView())
    # Add view
    admin.add_view(MyModelView(User, db.session))
    return app
Beispiel #23
0
def create_app(object_name):
    app = Flask(__name__)
    app.config.from_object(object_name)

    bootatrap.init_app(app)
    db.init_app(app)
    admin.init_app(app)

    models = [User, Post, Comment, Tag]
    for model in models:
        admin.add_view(CustomModelView(model, db.session, category='models'))

    admin.add_view(
        CustomFileAdmin(os.path.join(os.path.dirname(__file__), 'static'),
                        '/static/',
                        name="Static Files"))

    @app.route('/')
    def index():
        return redirect(url_for('blog.home'))

    app.register_blueprint(blog_blueprint)

    return app
Beispiel #24
0
from flask_script import Manager, Server
from webapp import create_app
from webapp.models import db, User, Post, Comment, Tag, tags, Role, roles, Download
app = create_app('webapp.config.DevConfig')
manager = Manager(app)
manager.add_command('server', Server())
db.init_app(app)


@manager.shell
def make_shell_context():
    return dict(app=app,
                db=db,
                User=User,
                Post=Post,
                Tag=Tag,
                tags=tags,
                Comment=Comment,
                Role=Role,
                roles=roles,
                Download=Download)


if __name__ == "__main__":
    manager.run()
import unittest

import webapp.controllers.blog as blog
from webapp import test_app
from webapp.models import db
from manage import populate_default_data

db.init_app(test_app)


class BlogRoutesTestCase(unittest.TestCase):
    def setUp(self):
        populate_default_data(db, test_app)

    def tearDown(self):
        db.session.remove()
        db.drop_all()

    def test_example(self):
        self.assertTrue(True)

    # Routes:
    # '/', home
    # '/new' new_post (GET, POST)
    # '/edit/<int>' edit_post (GET, POST)
    #  '/post/<int>' post (GET, POST)
    # '/tag/<string>'
    # '/user/<int>


class MainRoutesTestCase(unittest.TestCase):
Beispiel #26
0
def create_app(object_name):
    app = Flask(__name__)
    app.config.from_object(object_name)

    db.init_app(app)
    event.listen(Reminder, 'after_insert', on_reminder_save)
    bcrypt.init_app(app)
    oid.init_app(app)
    login_manager.init_app(app)
    principals.init_app(app)
    rest_api.add_resource(PostApi,
                          '/api/post',
                          '/api/post/<int:post_id>',
                          endpoint='api')
    rest_api.add_resource(AuthApi, '/api/auth', endpoint='auth')
    rest_api.init_app(app)
    celery.init_app(app)
    debug_toolbar.init_app(app)
    cache.init_app(app)
    assets_env.init_app(app)
    assets_env.register("main_js", main_js)
    assets_env.register("main_css", main_css)
    admin.init_app(app)
    # admin.add_view(CustomView(name="Custom"))
    # models = [User, Role, Post, Comment, Tag, Reminder]
    # for model in models:
    #     if model is not Post:
    #         admin.add_view(
    #             CustomModelView(model, db.session, category="models")
    #         )
    #     else:
    #         admin.add_view(
    #             PostView(Post, db.session, category="models")
    #         )
    admin.add_view(CustomView(name='Custom'))
    admin.add_view(CustomModelView(User, db.session, category="Models"))
    admin.add_view(CustomModelView(Role, db.session, category="Models"))
    #
    # Need to use a special view for Posts to get the CKEditor functionality
    #
    admin.add_view(PostView(Post, db.session, category="Models"))
    admin.add_view(CustomModelView(Comment, db.session, category="Models"))
    admin.add_view(CustomModelView(Tag, db.session, category="Models"))
    admin.add_view(CustomModelView(Reminder, db.session, category="Models"))
    admin.add_view(
        CustomFileAdmin(os.path.join(os.path.dirname(__file__), 'static'),
                        '/static/',
                        name='Static Files'))
    mail.init_app(app)
    youtube_ext.init_app(app)
    #
    # The gzip extension and the debug toolbar can't both be running...
    #
    #    flask_gzip.init_app(app)

    @identity_loaded.connect_via(app)
    def on_identity_loaded(sender, identity):
        identity.user = current_user
        if hasattr(current_user, 'id'):
            identity.provides.add(UserNeed(current_user.id))
        if hasattr(current_user, 'roles'):
            for role in current_user.roles:
                identity.provides.add(RoleNeed(role.name))

    #
    # Routes
    #
    @app.route('/')
    def index():
        return redirect(url_for('blog.home'))

    app.register_blueprint(blog_blueprint)
    app.register_blueprint(main_blueprint)

    return app
Beispiel #27
0
import random
import datetime

from flask.ext.script import Manager, Server
from flask.ext.script.commands import ShowUrls, Clean

from webapp import dev_app
from webapp.models import db, User, Post, Tag, Comment, Reminder

db.init_app(dev_app)

manager = Manager(dev_app)
manager.add_command("server", Server())
manager.add_command("show-urls", ShowUrls())
manager.add_command("clean", Clean())


@manager.shell
def make_shell_context():
    return dict(dev_app=dev_app, db=db, User=User, Post=Post, Tag=Tag, Comment=Comment, Reminder=Reminder)


@manager.command
def init_db():
    "create and populate db with default dev data"
    populate_default_data(db, dev_app)


def populate_default_data(db, app):
    db.app = app
    db.create_all()
Beispiel #28
0
def create_app(object_name):
    app = Flask(__name__)
    app.config.from_object(object_name)
    db.init_app(app)
    # db从app的config中获取URI
    event.listen(Reminder, 'after_insert', on_reminder_save)
    # SQLAlchemy在Reminder上注册回调函数,当after_insert发生后,执行on_reminder_save
    bcrypt.init_app(app)
    oid.init_app(app)
    login_manager.init_app(app)
    principals.init_app(app)
    celery.init_app(app)
    debug_toolbar.init_app(app)
    cache.init_app(app)
    admin.init_app(app)

    assets_env.init_app(app)
    assets_env.register('main_js', main_js)
    assets_env.register('main_css', main_css)

    rest_api.add_resource(PostApi,
                          '/api/post',
                          '/api/post/<int:post_id>',
                          endpoint='post')
    rest_api.add_resource(AuthApi, '/api/auth', endpoint='auth')
    rest_api.add_resource(CommentApi,
                          '/api/comment',
                          '/api/post/<int:post_id>/comment',
                          endpoint='comment')
    # add_resource(self, resource, *urls, **kwargs),api管理的是resource,将resource和url绑定
    # 绑定app后添加出错?
    rest_api.init_app(app)
    mail.init_app(app)
    youku.init_app(app)
    # flask_gzip.init_app(app)

    @identity_loaded.connect_via(app)
    def on_identity_loaded(sender, identity):
        # 设置identity的user对象?
        identity.user = current_user  # 注释掉好像也没影响

        # 将user的权限加入当前的Identity
        if hasattr(current_user, 'id'):
            identity.provides.add(UserNeed(current_user.id))
            # 基于id的权限
        if hasattr(current_user, 'roles'):
            for role in current_user.roles:
                identity.provides.add(RoleNeed(role.name))
                # 基于角色的权限

    app.register_blueprint(blog_blueprint, url_prefix='/blog')
    app.register_blueprint(main_blueprint)

    admin.add_view(CustomView(name='Custom'))
    models = [User, Role, Comment, Tag, Reminder]

    for model in models:
        admin.add_view(CustomModelView(
            model, db.session, category='models'))  # 同一个category的视图会放在同一个下拉菜单

    admin.add_view(PostView(Post, db.session, name='PostManager'))
    admin.add_view(
        CustomFileAdmin(op.join(op.dirname(__file__), 'static'),
                        '/static/',
                        name='Static Files'))
    # @app.route('/')
    # def index():
    #     return redirect(url_for('blog.home'))

    return app
Beispiel #29
0
def init_app(app):
    db.init_app(app)
    migrate.init_app(app, db)
    api.init_app(app)
from webapp import create_app
from webapp.config import DevConfig
from webapp.models import db
from webapp.tasks import log

def make_celery(app):
    celery = Celery(
            app.import_name,
            broker=app.config['CELERY_BROKER_URL'],
            backend=app.config['CELERY_BACKEND_URL']
            )
    celery.conf.update(app.config)
    TaskBase = celery.Task

    class ContextTask(TaskBase):
        abstract = True

        def __call__(self, *args, **kwargs):
            with app.app_context():
                return TaskBase.__call__(self, *args, **kwargs)

    celery.Task = ContextTask

    return celery

# make a dev app (with no REST)
flask_app = create_app(DevConfig)
db.init_app(flask_app)
celery = make_celery(flask_app)