Esempio n. 1
0
def test_on_model_change_delete():
    app, db, admin = setup()
    Model1, _ = create_models(db)
    db.create_all()

    class ModelView(CustomModelView):
        def on_model_change(self, form, model, is_created):
            model.test1 = model.test1.upper()

        def on_model_delete(self, model):
            self.deleted = True

    view = ModelView(Model1, db.session)
    admin.add_view(view)

    client = app.test_client()

    client.post('/admin/model1/new/',
                data=dict(test1='test1large', test2='test2'))

    model = db.session.query(Model1).first()
    eq_(model.test1, 'TEST1LARGE')

    url = '/admin/model1/edit/?id=%s' % model.id
    client.post(url, data=dict(test1='test1small', test2='test2large'))

    model = db.session.query(Model1).first()
    eq_(model.test1, 'TEST1SMALL')

    url = '/admin/model1/delete/?id=%s' % model.id
    client.post(url)
    ok_(view.deleted)
Esempio n. 2
0
def create_app(name, config_filename):
    app = Flask(name,
                template_folder='app/templates',
                static_folder='app/static')
    app.config.from_pyfile(config_filename)

    from app.models import db
    db.init_app(app)
    db.app = app
    from app.sms import mail
    mail.init_app(app)
    mail.app = app

    from app.views import main
    app.register_blueprint(main)

    #TODO: Secure admin view
    admin = Admin()
    admin.init_app(app)
    admin.app = app
    admin.add_view(ModelView(User, db.session))

    if not (app.debug or app.config.get('LOGGING_DISABLE', False)):
        import logging
        from logging import Formatter
        from logging.handlers import SMTPHandler, RotatingFileHandler
        mail_handler = SMTPHandler(mailhost=app.config['MAIL_SERVER'],
                                   fromaddr=app.config['LOGGING_SENDER'],
                                   toaddrs=app.config['ADMINS'],
                                   subject='dci-notify Server Error',
                                   credentials=(app.config['MAIL_USERNAME'],
                                                app.config['MAIL_PASSWORD']))

        file_handler = RotatingFileHandler(filename=os.path.join(
            basedir, 'app.log'),
                                           maxBytes=1048756,
                                           backupCount=5)

        mail_handler.setLevel(logging.ERROR)
        file_handler.setLevel(logging.WARNING)
        mail_handler.setFormatter(
            Formatter('''
            Message type:       %(levelname)s
            Location:           %(pathname)s:%(lineno)d
            Module:             %(module)s
            Function:           %(funcName)s
            Time:               %(asctime)s

            Message:

            %(message)s
        '''))

        file_handler.setFormatter(
            Formatter('%(asctime)s %(levelname)s: %(message)s '
                      '[in %(pathname)s:%(lineno)d]'))
        app.logger.addHandler(mail_handler)
        app.logger.addHandler(file_handler)

    return app
Esempio n. 3
0
def create_app(name=__name__, config={},
               static_folder='static', template_folder='templates'):

    app = Flask(name, static_folder=static_folder,
                template_folder=template_folder)
    app.secret_key = os.environ.get('SECRET', 'secret')
    app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DB_URI']
    app.config['DEBUG'] = bool(os.environ.get('DEBUG', False))

    app.config.update(config)

    from finance.models import db
    db.init_app(app)

    from finance.main import main_module
    app.register_blueprint(main_module, url_prefix='')

    admin = Admin(app, name='finance', template_mode='bootstrap3')
    from finance.models import (
        Account, Asset, AssetValue, Portfolio, Record, Transaction, User)
    classes = [Account, Asset, AssetValue, Portfolio, Record, Transaction,
               User]
    for cls in classes:
        admin.add_view(ModelView(cls, db.session,
                                 endpoint=cls.__name__))

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

    from finance.utils import date_range
    app.jinja_env.filters['date_range'] = date_range

    return app
Esempio n. 4
0
def activate(admin=True):
    """Activate each registered model for non-admin use"""
    with app.app_context():
        if getattr(current_app, 'endpoint_classes', None) is None:
            current_app.endpoint_classes = {}
            current_app.classes_by_name = {}
            current_app.table_to_endpoint = {}
            current_app.classes = []
        if not current_app.endpoint_classes:
            db.metadata.reflect(bind=db.engine)
            for name, table in db.metadata.tables.items():
                try:
                    cls = type(str(name), (sandman_model, db.Model),
                               {'__tablename__': name})
                    register(cls)
                except:
                    print name + ' unable to be registered'
        else:
            Model.prepare(db.engine)
    if admin:
        _prepare_relationships()
        admin = Admin(app)
        with app.app_context():
            for cls in (cls for cls in current_app.classes
                        if cls.use_admin == True):
                admin.add_view(ModelView(cls, db.session))
        webbrowser.open('http://localhost:5000/admin')
Esempio n. 5
0
def create_app(config='dev'):
    """ Flask application factory
    :param str config: type of app to build, either "prod" or "dev"
    """
    # Create flask application
    app = Flask(__name__)
    app.config.from_object('settings')
    app.config['ENV'] = config
    app.jinja_env.trim_blocks = True

    # Debug toolbar (when debug=true)
    debug_toolbar = DebugToolbarExtension(app)
    app.config['DEBUG_TB_PROFILER_ENABLED'] = True
    app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False

    # Register Blueprints
    app.register_blueprint(views_base.base)
    app.register_blueprint(views_blog.blog)

    # Flask-Assets; bundles all css/js files in minifed file
    assets = Environment(app)
    css_all = Bundle('css/bootstrap-flatly.min.css', 'css/highlightjs.min.css', 'css/font-awesome.css', 'css/main.css',
                     filters='cssmin', output='gen/style.css')
    js_all = Bundle('js/vendor/jquery.min.js', 'js/vendor/bootstrap.min.js', 'js/vendor/showdown-gfm.min.js',
                    'js/vendor/highlight.min.js', 'js/main.js', filters='jsmin', output='gen/libs.js')
    assets.register('css_all', css_all)
    assets.register('js_all', js_all)
    if app.config['DEBUG']:
        assets.debug = True
        app.config['ASSETS_DEBUG'] = True

    # Set up Flask-User
    babel = Babel(app)
    db_adapter = SQLAlchemyAdapter(db, User)
    user_manager = UserManager(db_adapter, app)  # Init Flask-User and bind to app

    # Init the cache
    cache.init_app(app)

    Moment(app)  # moment.js
    Misaka(app, autolink=True,  # Misaka Markdown
           fenced_code=True, lax_html=True, strikethrough=True,
           superscript=True, tables=True, wrap=True)

    # Init Admin page
    admin = Admin(app, index_view=AdminMain(endpoint='admin'))
    admin.add_view(PostAdminView())
    admin.add_view(NewPostView())
    admin.add_view(ModelView(Comment, db.session))
    static_path = os.path.join(BASE_DIR, 'app', 'static')
    admin.add_view(FileAdminView(static_path, '/static/', name='Static Files'))

    # Initialize DB
    db.init_app(app)

    return app
Esempio n. 6
0
def test_multiple_delete():
    app, db, admin = setup()
    M1, _ = create_models(db)

    db.session.add_all([M1('a'), M1('b'), M1('c')])
    db.session.commit()
    eq_(M1.query.count(), 3)

    view = ModelView(M1, db.session)
    admin.add_view(view)

    client = app.test_client()

    rv = client.post('/admin/model1/action/', data=dict(action='delete', rowid=[1, 2, 3]))
    eq_(rv.status_code, 302)
    eq_(M1.query.count(), 0)
Esempio n. 7
0
def register_admin(app):
    """注册Flask-Admin"""
    from flask.ext.admin import Admin
    from flask.ext.admin.contrib.sqla import ModelView
    from .models import db, Work, WorkImage, WorkType, Dynasty, Artist, Museum

    admin = Admin(app)
    admin.add_view(ModelView(Work, db.session))
    admin.add_view(ModelView(WorkImage, db.session))
    admin.add_view(ModelView(WorkType, db.session))
    admin.add_view(ModelView(Dynasty, db.session))
    admin.add_view(ModelView(Artist, db.session))
    admin.add_view(ModelView(Museum, db.session))
Esempio n. 8
0
    def __repr__(self):
        return "<Tasks({})>".format(self.title)


class Tasks_day(db.Model):
    __tablename__ = 'tasks_day'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(200))
    hours = db.Column(db.Integer)
    # done = db.Column(db.Boolean, unique=False)

    # def __repr__(self):
    #     return "<Tasks({})>".format(self.title)


class Private(db.Model):
    __tablename__ = 'private'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    fullAddressEn = db.Column(db.String(200))
    latitude = db.Column(db.String(200))
    longitude = db.Column(db.String(200))


admin.add_view(ModelView(Tasks, db.session))
admin.add_view(ModelView(Tasks_day, db.session))
admin.add_view(ModelView(Private, db.session))

from views import *

if __name__ == '__main__':
    manager.run()
Esempio n. 9
0
def init_flaskadmin(urlprefix="",
                    secret="fKY7kJ2xSrbPC5yieEjV",
                    override_admin=None,
                    override_flaskadminapp=None):
    global flaskadminapp, admin

    if not override_flaskadminapp:
        flaskadminapp = Flask(__name__)
        flaskadminapp.debug = True
        flaskadminapp.secret_key = secret
        flaskadminapp.config.update(dict(PREFERRED_URL_SCHEME='https'))
    else:
        flaskadminapp = override_flaskadminapp

        # lets add our template directory
        my_loader = jinja2.ChoiceLoader([
            flaskadminapp.jinja_loader,
            jinja2.FileSystemLoader(resole_uri("gengine:templates")),
        ])
        flaskadminapp.jinja_loader = my_loader

    flaskadminapp.add_url_rule('/static_gengine/<path:filename>',
                               endpoint='static_gengine',
                               view_func=get_static_view(
                                   'gengine:flask_static', flaskadminapp))

    @flaskadminapp.context_processor
    def inject_version():
        return {
            "gamification_engine_version":
            pkg_resources.get_distribution("gamification-engine").version
        }

    if not override_admin:
        admin = Admin(flaskadminapp,
                      name="Gamification Engine - Admin Control Panel",
                      base_template='admin_layout.html',
                      url=urlprefix + "/admin")
    else:
        admin = override_admin

    admin.add_view(ModelViewAchievement(DBSession, category="Rules"))
    admin.add_view(ModelViewGoal(DBSession, category="Rules"))
    admin.add_view(
        ModelView(AchievementAchievementProperty,
                  DBSession,
                  category="Rules",
                  name="Achievement Property Values"))
    admin.add_view(
        ModelView(AchievementReward,
                  DBSession,
                  category="Rules",
                  name="Achievement Reward Values"))
    admin.add_view(
        ModelView(GoalGoalProperty,
                  DBSession,
                  category="Rules",
                  name="Goal Property Values"))
    admin.add_view(ModelViewTranslationVariable(DBSession, category="Rules"))
    admin.add_view(ModelView(Translation, DBSession, category="Rules"))

    admin.add_view(ModelViewAchievementCategory(DBSession,
                                                category="Settings"))
    admin.add_view(ModelViewVariable(DBSession, category="Settings"))
    admin.add_view(
        ModelViewAchievementProperty(DBSession,
                                     category="Settings",
                                     name="Achievement Property Types"))
    admin.add_view(
        ModelViewReward(DBSession,
                        category="Settings",
                        name="Achievement Reward Types"))
    admin.add_view(
        ModelViewGoalProperty(DBSession,
                              category="Settings",
                              name="Goal Property Types"))
    admin.add_view(ModelView(Language, DBSession, category="Settings"))
    admin.add_view(
        MaintenanceView(name="Maintenance",
                        category="Settings",
                        url="maintenance"))

    admin.add_view(ModelViewValue(DBSession, category="Debug"))
    admin.add_view(ModelViewGoalEvaluationCache(DBSession, category="Debug"))
    admin.add_view(ModelViewUser(DBSession, category="Debug"))
    admin.add_view(ModelView(AchievementUser, DBSession, category="Debug"))
Esempio n. 10
0
    for index, user in enumerate(users):
        users[index] = user.__dict__

    quiz_model = quiz_model.__dict__

    print quiz_model

    thr = Thread(target=send_emails_to_all_users_async,
                 args=[app, quiz_model, users])
    thr.start()


Reply_form = model_form(Reply, Form)

Quiz_model_controller = ModelView(Quiz, db.session)
Quiz_model_controller.after_model_change = after_quiz_model_change_hook

admin.add_view(ModelView(User, db.session))
admin.add_view(Quiz_model_controller)
admin.add_view(ModelView(Reply, db.session))


@app.route("/")
def index():

    msg = Message("Hello",
                  sender="*****@*****.**",
                  recipients=["*****@*****.**"])

    mail.send(msg)
Esempio n. 11
0
def event_attend():
	if request.method == 'POST':
		event_id = request.form['event_id']
		user_id = request.form['user_id']
		if event_id and user_id:
			attend = Attend(event_id=event_id, user_id=user_id)
			db.session.add(attend)
			db.session.commit()
	return 'F**k yeah'

@app.route('/users/list')
def users_show():
  result = db.session.query(User).all()
  result_list =  []
  for i in result:
  	result_list.append(i.to_json())
  return json.dumps(result_list)

@app.route('/event/search')
def event_search():
    return 'Hello World!'

admin = Admin(app, name='Can lah!')
admin.add_view(ModelView(User, db.session))
admin.add_view(ModelView(Event, db.session))
admin.add_view(ModelView(Category, db.session))
admin.add_view(ModelView(Attend, db.session))

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80)
Esempio n. 12
0
from project.server.models import Appointment
from project.server.models import Treatment
from project.server.models import Symptom
from project.server.models import User_Symptom
from project.server.models import User_Symptom_Treatment
from project.server.models import Attachment
from project.server.models import Provider

admin = Admin(app)

class AdminView(BaseView):
    @expose('/')
    def index(self):
        return self.render('admin/index.html')

admin.add_view(ModelView(User, db.session, endpoint='users'))
admin.add_view(ModelView(Appointment, db.session))
admin.add_view(ModelView(Treatment, db.session))
admin.add_view(ModelView(Symptom, db.session))
admin.add_view(ModelView(User_Symptom, db.session))
admin.add_view(ModelView(User_Symptom_Treatment, db.session))
admin.add_view(ModelView(Attachment, db.session))
admin.add_view(ModelView(Provider, db.session))

########################
#### error handlers ####
########################

@app.errorhandler(401)
def unauthorized_page(error):
    return render_template("errors/401.html"), 401
Esempio n. 13
0
# coding=utf-8

from flask.ext.admin import Admin
from flask.ext.admin.menu import MenuLink
from web_site.admin.views import IndexView
from flask.ext.admin.contrib.sqla import ModelView
from web_site import db
from web_site.user.models import Role, User

admin = Admin(index_view=IndexView(name='首页'))

admin.add_view(
    ModelView(Role, db.session, endpoint="model_role", category="User"))
admin.add_view(
    ModelView(User, db.session, endpoint="model_user", category="User"))

admin.add_link(MenuLink('返回前台', url='/'))
Esempio n. 14
0
import os
from app import create_app, db
from app.models import *
#from app.models import Role, User, Product, ProductType, Province, City, District
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView
import data_add

app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)

admin = Admin(app)
admin.add_view(ModelView(User, db.session))
admin.add_view(ModelView(Product, db.session))
admin.add_view(ModelView(ProductType, db.session))
admin.add_view(ModelView(Order, db.session))
admin.add_view(ModelView(OrderProduct, db.session))


def make_shell_context():
    return dict(app=app,
                db=db,
                User=User,
                Role=Role,
                Product=Product,
                ProductType=ProductType,
                Province=Province,
                City=City,
Esempio n. 15
0
            collects.append({
                "id": u.id,
                "imgurl": p.icon,
                "top_img": u.top_img,
                "top_title": u.top_title,
                "username": p.nickname,
                "house_type": u.house_type,
                "usable_area": u.usable_area
            })
        return jsonify({'ret': 'true', 'data': collects})
    else:
        return jsonify({'ret': 'true', 'data': {'state': 0}})  # 查询失败


from flask.ext.admin.contrib.sqla import ModelView

admin.add_view(ModelView(Personal, db.session, name='个人资料'))
admin.add_view(ModelView(Collects, db.session, name='收藏'))
admin.add_view(ModelView(Design, db.session, name='设计'))
admin.add_view(ModelView(Diary, db.session, name='日记'))
admin.add_view(ModelView(Information, db.session, name='系统消息'))
admin.add_view(ModelView(Posts, db.session, name='问题'))
admin.add_view(ModelView(Styles, db.session, name='灵感'))
admin.add_view(ModelView(Topics, db.session, name='文章'))
admin.add_view(ModelView(Topics_one, db.session, name='话题标题'))
admin.add_view(ModelView(Topics_udcontent, db.session, name='话题内容'))
admin.add_view(ModelView(UnderDiscussion, db.session, name='讨论标题'))
admin.add_view(ModelView(Udcontent, db.session, name='讨论内容'))
admin.add_view(ModelView(Users, db.session, name='用户密码'))
admin.add_view(FileAdmin(base_dir, '/static/upload/', name='文件管理'))
Esempio n. 16
0

class RestaurantAdmin(ModelView):
    column_choice = {'spicy_level': Restaurant.TYPES}
    form_choices = {'spicy_level': Restaurant.TYPES}


class UserAdmin(ModelView):
    column_exclude_list = ['password', 'openid']

    def on_model_change(self, form, user, is_created=False):
        user.password = bcrypt.generate_password_hash(form.password.data)


class PointAdmin(ModelView):
    can_edit = False
    column_default_sort = ('avg', True)


admin = Admin()
models = [(PersonalRestaurantInfor, u'个人餐厅信息'), (Image, u'餐厅图片')]

for m in models:
    _model = ModelView(m[0], db.session, endpoint=m[0].__name__, name=m[1])
    admin.add_view(_model)

admin.add_view(
    RestaurantAdmin(Restaurant, db.session, endpoint='Restaurant', name=u'餐厅'))
admin.add_view(UserAdmin(User, db.session, endpoint='User', name=u'用户'))
admin.add_view(PointAdmin(Point, db.session, endpoint='Point', name=u'读书评分'))
Esempio n. 17
0
# -*- coding: utf8 -*-
from flask.ext.admin.contrib.sqla import ModelView
from flask.ext.admin import Admin
from flask import g
from website import app, db
from website.models.models import User, Anime, Torrent, AnimeReview, ActorQuote


class AdminRequiredView(ModelView):
    def is_accessible(self):
        if g.user:
            return True
        return False


class LoginRequiredView(ModelView):
    def is_accessible(self):
        if g.user:
            return True
        return False


admin = Admin(app, endpoint='admin')
admin.add_view(AdminRequiredView(User, db.session))
admin.add_view(ModelView(Anime, db.session))
admin.add_view(ModelView(Torrent, db.session))
admin.add_view(ModelView(AnimeReview, db.session))
admin.add_view(ModelView(ActorQuote, db.session))
Esempio n. 18
0
def init_admin():
    admin = Admin(app, name=u"gMission Admin Control Panel")
    for model in all_models():
        print 'to add in admin portal:', model.__name__
        admin.add_view(ModelView(model, db.session,
                                 name="%s" % model.__name__))
Esempio n. 19
0
from flask import Flask, render_template, abort, url_for, redirect, request
from flask.ext.admin import Admin, BaseView, expose
from flask.ext.admin.contrib.sqla import ModelView
from models import db, Person

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
db.init_app(app)
with app.app_context():
    db.create_all()

# Create an admin view for editing the data
# TODO: Make this password-protected or similar
admin = Admin(app, name='UoT CS Genealogy')
admin.add_view(ModelView(Person, db.session))


# Render the homepage
@app.route('/')
def home():
    return render_template('home.html')


@app.route('/search')
def search():
    query = request.args.get('q', '')
    if query:
        people = db.session.query(Person).filter(
            Person.name.like('%' + query + '%'))
    else:
        return redirect(url_for('home'))
Esempio n. 20
0
import os.path as op

from flask import request, Response
from werkzeug.exceptions import HTTPException
from flask_admin import Admin
from flask.ext.admin.contrib.sqla import ModelView
from flask.ext.admin.contrib.fileadmin import FileAdmin

from app import app, db
from app.models import User, Donation


admin = Admin(app, name='Admin', template_mode='bootstrap3')

class ModelView(ModelView):

    def is_accessible(self):
        auth = request.authorization or request.environ.get('REMOTE_USER')  # workaround for Apache
        if not auth or (auth.username, auth.password) != app.config['ADMIN_CREDENTIALS']:
            raise HTTPException('', Response('You have to an administrator.', 401,
                {'WWW-Authenticate': 'Basic realm="Login Required"'}
            ))
        return True

# Users
admin.add_view(ModelView(User, db.session))
admin.add_view(ModelView(Donation, db.session))
# Static files
path = op.join(op.dirname(__file__), 'static')
admin.add_view(FileAdmin(path, '/static/', name='Static'))
Esempio n. 21
0
from flask import Flask, request, session, g, redirect, url_for, abort, \
     render_template, flash
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView
from flask.ext.admin.contrib.fileadmin import FileAdmin

app = Flask(__name__)

app.config.from_envvar('TEMPLATEAPP_SETTINGS', silent=True)
app.config.from_object('config')

db = SQLAlchemy(app)

import models

# Create Database if doesn't already exist
if not os.path.isfile(app.config['SQLALCHEMY_DATABASE_PATH']):
  with app.app_context():
    db.create_all()

# Enable Django Admin-like interface for the Users Model...
admin = Admin(app)
admin.add_view(ModelView(models.User, db.session))

# ... and also static files.
path = os.path.join(os.path.dirname(__file__), 'static')
admin.add_view(FileAdmin(path, '/static/', name='Static Files'))

import routes
Esempio n. 22
0
from flask import render_template, redirect, url_for, flash
from app import app
from app import db
from app import admin
from app.forms import AddRepair, SelectReport
from app.models import Repairs
from flask.ext.admin.contrib.sqla import ModelView

# Admin views for modifying records
# need to make this available via log in only.
admin.add_view(ModelView(Repairs, db.session))


#Home page route
@app.route('/')
@app.route('/index', methods=['GET', 'POST'])
def index():
    # Get repairs for display on home page
    repairs = Repairs.query.order_by('date desc').all()
    # Render the home page with list of repairs
    return render_template('index.html', repairs=repairs)


# Route for data entry (Repairs)
@app.route('/repairs', methods=['GET', 'POST'])
def addrepair():
    form = AddRepair()
    # Logic for inserting data into repair.db
    if form.validate_on_submit():
        new_repair = Repairs(date=form.date.data,
                             pc_num=form.pc_num.data,
Esempio n. 23
0
def init_admin():
    admin = Admin(app, name=u"gMission Admin Control Panel")
    for model in all_models():
        admin.add_view(ModelView(model, db.session, name=model.__name__))
                          os.environ.get('INITIAL_ADMIN_PASSWORD')))
    #install_rec = Install(instance_id, app.name, app.source_url)
    install_rec = Install(instance_id, app.name, app.source_url, r.status_code,
                          r.reason)
    db.session.add(install_rec)
    db.session.commit()
    pass


manager.create_api(Extensions,
                   methods=['GET', 'POST', 'DELETE'],
                   preprocessors={
                       'GET_SINGLE': [pre_get_catalog],
                       'GET_MANY': [pre_get_catalog]
                   },
                   results_per_page=None)
manager.create_api(Metadata,
                   methods=['GET', 'POST', 'DELETE'],
                   results_per_page=None)
manager.create_api(Install,
                   methods=['GET', 'POST', 'DELETE'],
                   preprocessors={
                       'GET_SINGLE': [pre_get_installapp],
                       'GET_MANY': [pre_get_installapp]
                   },
                   results_per_page=None)

admin.add_view(ModelView(Extensions, db.session))
admin.add_view(ModelView(Metadata, db.session))
admin.add_view(ModelView(Install, db.session))
Esempio n. 25
0
reload(sys)
sys.setdefaultencoding('utf-8')

manager = Manager(app)
migrate = Migrate(app, db)
admin = Admin(app, name='MuxiBook')


def make_shell_context():
    """自动加载环境"""
    return dict(app=app, db=db, Book=Book, User=User)


manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
admin.add_view(ModelView(Book, db.session))
admin.add_view(ModelView(User, db.session))


@manager.command
def test():
    """运行测试"""
    import unittest
    tests = unittest.TestLoader().discover('test')
    unittest.TextTestRunner(verbosity=2).run(tests)


if __name__ == '__main__':
    app.debug = True
    manager.run()
Esempio n. 26
0
    candidate_id = db.Column(db.Integer, db.ForeignKey('candidates.id'))
    candidate = db.relationship('Candidate', backref=db.backref('submissions', order_by=id))
    problem_id  = db.Column(db.Integer, db.ForeignKey('problems.id'))
    problem = db.relationship('Problem')

    def get_default_filename(self):
        return (self.candidate.name + '-' + self.problem.name).lower().replace(' ', '_')
    
    def __repr__(self):
        return "submission:{}->{}".format(self.candidate.name if self.candidate else "??",
                                          self.problem.name if self.problem else "??")


admin = Admin(app, url="/admin2")
admin.add_view(ModelView(Candidate, db.session))
admin.add_view(ModelView(Problem, db.session))
admin.add_view(ModelView(Submission, db.session))

def init_db():
    db.drop_all()
    db.create_all()

@app.route('/admin')
def admin():
    if not session.get('logged_in'):
        return redirect(url_for('login'))
    
    problems = Problem.query.order_by(Problem.name)
    candidates = Candidate.query.order_by(Candidate.name)
Esempio n. 27
0
telephony_server.config['SECRET_KEY'] = SECRET_KEY

#prep the socket type, address for zmq
telephony_server.config['ZMQ_SOCKET_TYPE'] = zmq.PUB
telephony_server.config['ZMQ_BIND_ADDR'] = ZMQ_FORWARDER_SPITS_OUT

logger = init_logging('telephony_server')

from rootio.extensions import db  # expects symlink of rootio in own directory
telephony_server.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
db = SQLAlchemy(telephony_server)

from rootio.telephony.models import *
from rootio.radio.models import *

admin.add_view(ModelView(PhoneNumber, db.session))
admin.add_view(ModelView(Message, db.session))
admin.add_view(ModelView(Call, db.session))
admin.add_view(ModelView(Person, db.session))
admin.add_view(ModelView(Location, db.session))
admin.add_view(ModelView(Station, db.session))
admin.add_view(ModelView(Program, db.session))
admin.add_view(ModelView(Episode, db.session))
admin.add_view(ModelView(Role, db.session))
admin.add_view(ModelView(Gateway, db.session))


def get_or_create(session, model, **kwargs):
    instance = session.query(model).filter_by(**kwargs).first()
    if instance:
        return instance
            if not form.validate():
                flash('Datos incorrectos')
                return self.render('intro-challenge.html', form=form)
            else:
                #valid = Pkchallenge.is_valid_answer('test2')
                valid = Pkchallenge.is_valid_answer(form.answer.data)
                message = 'Respuesta incorrecta'
                if valid:
                    message = 'Respuesta correcta'
                flash(message)
                return self.render('intro-challenge.html')
        elif request.method == 'GET':
            return self.render('intro-challenge.html', form=form)
        return self.render('intro-challenge.html', form=form)


admin = Admin(app, name="WMS", index_view=IndexView(name='Inicio'))
#admin.add_view(IndexView(name='Inicio'))

admin.add_view(TestChallengeView(name='Competir', endpoint='intro-challenge', category='Retos'))
admin.add_view(ModelView(Pkchallenge, db.session, name='Reto', endpoint='reto', category='Retos'))
admin.add_view(ModelView(Pkanswer, db.session, name='Respuesta', endpoint='respuesta', category='Respuestas'))
admin.add_view(ModelView(Ckanswertype, db.session, name='Tipo de Respuesta', endpoint='tipo-respuesta', category='Respuestas'))


@app.route('/')
def index():
    return redirect("/admin/")

if __name__ == '__main__':
    app.run(debug=True)
Esempio n. 29
0
    
    form_ajax_refs = {
        'author': {
            'fields': (User.name, User.email),
        },
    }
    
class UserModelView(SlugModelView):
    column_list = ['email', 'name', 'active', 'created_timestamp']
    column_filters = ('email', 'name', 'active')
    column_searchable_list = ['email', 'name']
    form_columns = ['email', 'password', 'name', 'active']
    
    form_extra_fields = {
        'password': PasswordField('New password'),
    }
    def on_model_change(self, form, model, is_created):
        if form.password.data:
            model.password_hash = User.make_password(form.password.data)
            return super(UserModelView, self).on_model_change(form, model, is_created)


admin = Admin(app, 'Blog Admin', index_view=IndexView())
admin.add_view(EntryModelView(Entry, db.session))
admin.add_view(ModelView(Tag, db.session))
admin.add_view(UserModelView(User, db.session))
admin.add_view(
    BlogFileAdmin(app.config['STATIC_DIR'], '/static/', name='Static Files'))


Esempio n. 30
0
admin = Admin(app, name='Admin', template_mode='bootstrap3')


class ModelView(ModelView):

    def is_accessible(self):
        """Authenticating the User"""

        # workaround for apache
        auth = request.authorization or request.environ.get('REMOTE_USER')
        if not auth or (auth.username,
                        auth.password) != app.config['ADMIN_CREDENTIALS']:
            raise HTTPException('',
                                Response('You have to an administrator.', 401,
                                         {'WWW-Authenticate':
                                          'Basic realm="Login Required"'}
                                         )
                                )
        return True


# Users
admin.add_view(ModelView(User, db.session))
admin.add_view(ModelView(InstaInfluencer, db.session))
admin.add_view(ModelView(UserInfluencerMap, db.session))

# Static files
path = op.join(op.dirname(__file__), 'static')
admin.add_view(FileAdmin(path, '/static/', name='Static'))