def register_debug_extensions(app):
  from flask_debugtoolbar import DebugToolbarExtension
  toolbar = DebugToolbarExtension()
  toolbar.init_app(app)

  from flask_admin.contrib.mongoengine import ModelView
  import flask_admin as admin
  admin = admin.Admin(app, 'TimeTracker:Admin')

  # Add views
  from models import User, Role
  admin.add_view(ModelView(User))
  admin.add_view(ModelView(Role))
Exemplo n.º 2
0
                        'name': {
                            'style': 'color: red'
                        }
                    }
                }
            }
        }
    }


# Flask views
@app.route('/')
def index():
    return redirect('/static/app.html')


if __name__ == '__main__':
    # Create admin
    admin = admin.Admin(app, 'Xpress Taxi', template_mode="bootstrap3")

    # Add views
    admin.add_view(UserView(Users))
    admin.add_view(DrivingsView(Drivings))
    # admin.add_view(ModelView(Tag))
    # admin.add_view(PostView(Post))
    # admin.add_view(ModelView(File))
    # admin.add_view(ModelView(Image))

    # Start app
    app.run(debug=True, port=80, host="0.0.0.0")
Exemplo n.º 3
0
        return {
            'public_dsn': sentry.client.get_public_dsn('http')
        }
    else:
        return {
            'public_dsn': None
        }


@app.context_processor
def inject_user():
    return dict(current_user=current_user)

db = MongoEngine(app)

#
from .models import User, Role, Category, PolygonType  # noqa
user_datastore = MongoEngineUserDatastore(db, User, Role)
security = Security(app, user_datastore)

admin = admin.Admin(app, 'Knotmarker', index_view=AdminIndexView(), template_mode='bootstrap3')
admin.add_view(UserModelView(User))
admin.add_view(UserModelView(Role))
admin.add_view(UserModelView(Category))
admin.add_view(UserModelView(PolygonType))

from .forms import *  # noqa
from .views import *  # noqa
from .api import *  # noqa
from .filters import *
Exemplo n.º 4
0
        Moreover, support for association proxies to association proxies
        (e.g.: keywords_values) is currently limited to column_list only."""

    column_list = ('id', 'name', 'keywords', 'keywords_values')
    column_sortable_list = ('id', 'name')
    column_filters = ('id', 'name', 'keywords')
    form_columns = ('name', 'keywords')


class KeywordAdmin(sqla.ModelView):
    column_list = ('id', 'keyword')


# Create admin
admin = admin.Admin(app, name='Example: SQLAlchemy Association Proxy', template_mode='bootstrap3')
admin.add_view(UserAdmin(User, db.session))
admin.add_view(KeywordAdmin(Keyword, db.session))

if __name__ == '__main__':

    # Create DB
    db.create_all()

    # Add sample data
    user = User('log')
    for kw in (Keyword('new_from_blammo'), Keyword('its_big')):
        user.keywords.append(kw)

    db.session.add(user)
    db.session.commit()
Exemplo n.º 5
0
#flask view
	
'''
class myview(BaseView):

	def is_accessible(self):
		return True
	@expose('/')
	def index(self):
		return self.render('admin.html')
'''


init_login()

admin = admin.Admin(app, index_view=MyAdminIndexView(),
		base_template='my_master.html')
	  

admin.add_view(MyModelView(User , db.session))
admin.add_view(MyModelView(Post , db.session))
admin.add_view(MyModelView(Category , db.session))
admin.add_view(MyModelView(Tag , db.session))

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


    # Pass additional parameters to 'path' to FileUploadField constructor
    form_args = {
        'filename': {
            'label': 'File',
            'base_path': path,
            'allow_overwrite': True}}
    # Use same rule set for edit page
>>>>>>> parent of 9e7bcc7... Mering with master
    
class AdminLogout(BaseView):
    @login_required
    @roles_accepted("Admin")
    @expose('/')
    def AdminLogout(self):
        return redirect('/logout')

<<<<<<< HEAD
=======
admin.add_view(FileDataAdmin(File, name='Files'))
admin.add_view(AdminUpload(name='Upload', endpoint='upload'))
#admin.add_view(AdminUpload(File, name='Upload'))
#admin.add_view(MyFileAdmin(path, '/static/' , name='FileUpload'))
admin.add_view(NotificationAdmin(Notification))
admin.add_view(RequestAdmin(Request))
admin.add_view(PostAdmin(Post))
>>>>>>> parent of 9e7bcc7... Mering with master
admin.add_view(UserAdmin(User))
admin.add_view(RoleAdmin(Role))
admin.add_view(UserRolesAdmin(UserRole))
admin.add_view(AdminLogout(name='Logout', endpoint='logout'))
Exemplo n.º 7
0
           role = db_session.query(Role).filter(Role.id==2).first()
           user.roles.append(role)
           db_session.add(user)
           db_session.commit()
           flash('The user was created successfully')
       return self.render('open_account.html', form=formAccount)

    def is_visible(self):
        return login.current_user.is_authenticated()


init_login()

admin = admin.Admin(app, 'ANYWAY Administration Panel', index_view=AdminIndexView(), base_template='admin_master.html')

admin.add_view(AdminView(User, db_session, name='Users', endpoint='AllUsers', category='Users'))
admin.add_view(OpenNewOrgAccount(name='Open new organization account', endpoint='OpenAccount', category='Users'))
admin.add_view(SendToSubscribersView(name='Send To Subscribers'))
admin.add_view(ViewHighlightedMarkers(name='View Highlighted Markers'))


lms_dictionary = {}

@app.before_first_request
def read_dictionaries():
    global lms_dictionary
    for directory in glob.glob("{0}/{1}/*/*".format(app.static_folder, 'data/lms')):
        main_dict = dict(get_dict_file(directory))
        if len(main_dict) == 0:
            return
        if len(main_dict) == 1:
Exemplo n.º 8
0
            return True
        else:
            return False
class backView(BaseView):
    @expose('/')
    def index(self):
        admin.name = "Admin"
        session['dataset_id'] = ""
        return redirect('/admin/usersview/')
    def is_visible(self):
        if session['dataset_id'] == "":
            return False
        else:
            return True

admin = admin.Admin(app, name='Admin',index_view=admin.AdminIndexView(name=' ',url='/admin'))
# Create admin
admin.add_view(usersView(Users, db.session))
admin.add_view(datasetsView(Datasets, db.session))
admin.add_view(classView(Class, db.session))
admin.add_view(imageView(Image, db.session))
admin.add_view(tasksView(Tasks, db.session))

admin.add_view(backView(name='Back'))
admin.add_view(MyView(name='Logout'))


if __name__ == '__main__':
    # Start app
    app.run(debug=True)
Exemplo n.º 9
0
    if focusedUser.id != userID:
        return "Not permited."  #todo

    eventId = request.form.get('id')
    content = request.form.get('content')
    event = Event.query.filter_by(id=eventId).first()
    event.content = content
    db.session.commit()
    logger.warning("UserID = %d, update event, eventID = %s" %
                   (userID, eventId))
    return "Good!"


# Initialize flask-login
init_login()

# Create admin, with view MyAdminIndexView
admin = admin.Admin(app,
                    'Week report system',
                    index_view=MyAdminIndexView(name='Home'),
                    base_template='my_master.html')

# Add view
admin.add_view(UserProfileView(name='Profile'))
admin.add_view(UserView(User, db.session, name='User Management'))
# admin.add_view(TreeView(TreeNode, db.session, name='Organization'))
admin.add_view(HelpView(name='Help'))

app.debug = True
app.run(host='0.0.0.0', port=8080)
Exemplo n.º 10
0

from wtforms import Form, BooleanField, TextField, validators


@app.route('/new', methods=['GET', 'POST'])
def new():
    if request.method == 'POST':
        if not request.form['name'] or not request.form[
                'city'] or not request.form['addr']:
            flash('Please enter all the fields', 'error')
        else:
            student = students(request.form['name'], request.form['city'],
                               request.form['addr'], request.form['pin'])

            db.session.add(student)
            db.session.commit()

            flash('Record was successfully added')
            return redirect(url_for('show_all'))
    return render_template('new.html')


# Create admin
admin = admin.Admin(app, name='31form', template_mode='bootstrap3')
admin.add_view(CarAdmin(Car, db.session))

if __name__ == '__main__':
    db.create_all()
    app.run(debug=True)
Exemplo n.º 11
0
            Thu_chi.thoi_gian.between(form.tu_ngay.data,
                                      form.den_ngay.data)).all()
        hoa_don = dbSession.query(Hoa_don).filter(
            Hoa_don.ngay_tao_hoa_don.between(form.tu_ngay.data,
                                             form.den_ngay.data)).all()
        tieu_de = 'Tính từ ngày ' + form.tu_ngay.data.strftime(
            "%d-%m-%Y") + ' đến ngày ' + form.den_ngay.data.strftime(
                "%d-%m-%Y")
    tong_chi_phi = 0
    for item in ds_chi:
        tong_chi_phi += item.so_tien
    tong_loi_nhuan = 0
    for hoa_don in ds_hoa_don:
        don_hang = dbSession.query(Don_hang).filter(
            Don_hang.ma_hoa_don == hoa_don.ma_hoa_don).all()
        for dh in don_hang:
            tong_loi_nhuan += dh.loi_nhuan
    return render_template('Quan_ly/QL_doanh_thu/Tong_ket.html',
                           tong_chi_phi=tong_chi_phi,
                           tong_loi_nhuan=tong_loi_nhuan,
                           tieu_de=tieu_de,
                           form=form)


init_login()
admin = Admin(app,
              name="Admin",
              index_view=MyAdminIndexView(name="Admin"),
              template_mode='bootstrap3')
admin.add_view(admin_view(Loai_nguoi_dung, dbSession, 'Loại người dùng'))
admin.add_view(admin_view(Nguoi_dung, dbSession, 'Người dùng'))
Exemplo n.º 12
0
# ----------------------------------------------------------------------------
# Flask Views
# ----------------------------------------------------------------------------

# root route


@app.route('/')
def index():
    # return redirect("/admin/", code=302)
    # return "<h1><a href='/admin/'>View Inventory</a></h1>"
    return render_template('/pages/index.html')


# Create admin
admin = admin.Admin(app,
                    name="{0} | {1}".format(app.config['ORG_NAME'],
                                            app.config['APP_TITLE']),
                    template_mode='bootstrap3')

# Add model views
admin.add_view(SaleView(Sale, db.session))
admin.add_view(SupplierView(Supplier, db.session))
admin.add_view(ProductView(Product, db.session))
admin.add_view(ModelView(Tag, db.session))
admin.add_view(ModelView(Staff, db.session))
# add custom views
admin.add_view(InventoryView(name='Inventory', endpoint='inventory'))
admin.add_view(AnalyticsView(name='Analytics', endpoint='analytics'))
Exemplo n.º 13
0
app = Flask(__name__)
app.secret_key = "Shrinking-Spell"


@app.route('/admin')
def index_admin():
    return MyView().render('index.html')


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/login')
def login_template():
    return render_template('login.html')


@app.route('/register')
def register_template():
    return render_template('register.html')


admin = admin.Admin(name="Example: Simple Views", template_mode='bootstrap3')
admin.add_view(MyAdminView(name="view1", category='Test'))
admin.add_view(AnotherAdminView(name="view2", category='Test'))
admin.init_app(app)
if __name__ == "__main__":
    app.run(port=5000, debug=True)
Exemplo n.º 14
0
def create_app():

    app = Flask(__name__,
                static_url_path='/static',
                static_folder='static',
                template_folder='templates',
                instance_relative_config=True)
    app.config.from_object(config.Config)

    db.init_app(app)

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)

    security = Security(app, user_datastore, login_form=LoginForm)
    babel = Babel(app, default_locale='ru')

    with app.test_request_context():
        if not os.path.isfile(
                app.config.get('SQLALCHEMY_DATABASE_URI').replace(
                    'sqlite:///', '')):
            db.create_all()

            admin_role = Role('admin')
            db.session.add(admin_role)
            db.session.commit()

            linux = OperationSystemType('Linux')
            windows = OperationSystemType('Windows')
            db.session.add_all([linux, windows])
            db.session.commit()

            ct_agent = Agent('CerediraTess', windows)
            ct_agent.add_role(admin_role)
            db.session.add(ct_agent)
            db.session.commit()

            user_datastore.create_user(email='*****@*****.**',
                                       password=hash_password("admin"),
                                       roles=[admin_role],
                                       username='******')
            db.session.commit()

    with app.app_context():
        import flask_admin as admin
        # Create admin
        admin = admin.Admin(app,
                            'CerediraTess',
                            template_mode='bootstrap4',
                            index_view=MyAdminIndexView(),
                            base_template='my_master.html',
                            static_url_path='../static')

        admin.add_link(
            MenuLink(name='Выполнение запросов',
                     category='',
                     url='/CerediraTess.html'))
        admin.add_link(
            MenuLink(name='Блокировка агентов',
                     category='',
                     url='/AgentLocker.html'))

        admin.add_view(
            UserModelView(User,
                          db.session,
                          endpoint='User',
                          name='Пользователи'))
        admin.add_view(
            RoleModelView(Role, db.session, endpoint='Role', name='Роли'))
        admin.add_view(
            OperationSystemTypeModelView(OperationSystemType,
                                         db.session,
                                         endpoint='OperationSystemType',
                                         name='Типы ОС'))
        admin.add_view(
            AgentModelView(Agent, db.session, endpoint='Agent', name='Агенты'))
        admin.add_view(
            ScriptModelView(Script,
                            db.session,
                            endpoint='Script',
                            name='Скрипты'))

        from ceredira_tess.commons import app as app2
        app.register_blueprint(app2)

    @babel.localeselector
    def get_locale():
        # Put your logic here. Application can store locale in
        # user profile, cookie, session, etc.
        return 'ru'

    @app.context_processor
    def inject_url():
        return dict(admin_view=admin.index_view, get_url=url_for, role=Role)

    @security.context_processor
    def security_context_processor():
        return dict(admin_base_template=admin.base_template,
                    admin_view=admin.index_view,
                    h=helpers,
                    get_url=url_for,
                    role=Role)

    return app
Exemplo n.º 15
0
Arquivo: app.py Projeto: th-ms/Jokemon
            user = discord.fetch_user()
            user_data = json.loads(
                dumps(db.users.find_one({"discordId": user.id})))
            return user_data['admin']
        else:
            return False

    def inaccessible_callback(self, name, **kwargs):
        return redirect(url_for('index'))


app = Flask(__name__)
admin = admin.Admin(app,
                    template_mode="bootstrap3",
                    index_view=MyAdminIndexView())
admin.add_view(UserView(db.users))
admin.add_view(JokemonView(db.jokemon))
admin.add_view(MoveView(db.moves))
socketio = SocketIO(app)

app.config["SECRET_KEY"] = "swagmoneybigbubby"
app.config["DISCORD_CLIENT_ID"] = 763102007703109682
app.config["DISCORD_CLIENT_SECRET"] = os.getenv("DISCORD_SECRET")
app.config["DISCORD_REDIRECT_URI"] = "http://127.0.0.1:5000/callback"
app.config["DISCORD_BOT_TOKEN"] = os.getenv("DISCORD_TOKEN")
app.config["OAUTHLIB_INSECURE_TRANSPORT"] = True

discord = DiscordOAuth2Session(app)

rarity_vals = [
    {
Exemplo n.º 16
0
class AnotherAdminView(admin.BaseView):
    @admin.expose('/')
    def index(self):
        return self.render('anotheradmin.html')

    @admin.expose('/test/')
    def test(self):
        return self.render('test.html')


# Create flask app
app = Flask(__name__, template_folder='templates')
app.debug = True

# Flask views
@app.route('/')
def index():
    return '<a href="/admin/">Click me to get to Admin!</a>'

# Create admin interface
admin = admin.Admin(name="Example: Simple Views")
admin.add_view(MyAdminView(name="view1", category='Test'))
admin.add_view(AnotherAdminView(name="view2", category='Test'))
admin.init_app(app)

if __name__ == '__main__':

    # Start app
    app.run()
Exemplo n.º 17
0
# from .views import MyAdminIndexView
# class MyView(BaseView):

class MyAdminIndexView(admin.AdminIndexView):
	"""rewrite is_authenticated method"""
	def is_accessible(self):
		# return login.current_user.is_authenticated
		return login.current_user.is_admin()

admin = Admin(
		app, name="木muxi犀", template_mode="bootstrap3",
		index_view=MyAdminIndexView(),
		base_template='my_master.html'
        )
from .models import User, Share, Blog, Book, Comment
admin.add_view(ModelView(User, db.session))
admin.add_view(ModelView(Book, db.session))
admin.add_view(ModelView(Share, db.session))
admin.add_view(ModelView(Comment, db.session))
admin.add_view(ModelView(Blog, db.session))


# 蓝图注册
from .book import books
app.register_blueprint(books, url_prefix='/book')

from .muxi import muxi
app.register_blueprint(muxi, url_prefix='/muxi')

from .share import shares
app.register_blueprint(shares, url_prefix='/share')
Exemplo n.º 18
0
        def post(self, cls):
            return cls.render('test.html', request=request, name="API_v1")

    @admin.expose_plugview('/_api/2')
    class API_v2(MethodView):
        def get(self, cls):
            return cls.render('test.html', request=request, name="API_v2")

        def post(self, cls):
            return cls.render('test.html', request=request, name="API_v2")


# Create flask app
app = Flask(__name__, template_folder='templates')


# Flask views
@app.route('/')
def index():
    return redirect('/admin')


if __name__ == '__main__':
    # Create admin interface
    admin = admin.Admin(name="Example: MethodView")
    admin.add_view(ViewWithMethodViews())
    admin.init_app(app)

    # Start app
    app.run(debug=True)
Exemplo n.º 19
0
        'products': {
            'form_rules': ('title', rules.HTML('<hr>'), 'code')
        }
    }

class DepartamentsView(ModelView):
	column_filters = ['title']
	column_searchable_list = ('title', )
	form_subdocuments = {
        'personal': {
            'form_rules': ('name', rules.HTML('<hr>'), 'code')
        }
    }

admin = admin.Admin(app, 'Нефтебаза: администрирование')
admin.add_view(DilersView(Dilers))
admin.add_view(CallBackView(CallBack))
admin.add_view(CategoriesView(Categories))
admin.add_view(DepartamentsView(Departaments))
admin.add_view(ContactsView(Contacts))
admin.add_view(DescriptionsView(Descriptions))
admin.add_view(SlogansView(Slogans))

# register blueprints for views

def register_blueprints(app):
	from oilsite.views import oilsite
	app.register_blueprint(oilsite)

register_blueprints(app)
Exemplo n.º 20
0
    column_list = ('id', 'name', 'keywords', 'keywords_values')
    column_sortable_list = ('id', 'name')
    column_filters = ('id', 'name', 'keywords')
    form_columns = ('name', 'keywords')


class KeywordAdmin(sqla.ModelView):
    column_list = ('id', 'keyword')


# Create admin
admin = admin.Admin(app,
                    name='Example: SQLAlchemy Association Proxy',
                    template_mode='bootstrap2')
admin.add_view(UserAdmin(User, db.session))
admin.add_view(KeywordAdmin(Keyword, db.session))

if __name__ == '__main__':

    # Create DB
    db.create_all()

    # Add sample data
    user = User('log')
    for kw in (Keyword('new_from_blammo'), Keyword('its_big')):
        user.keywords.append(kw)

    db.session.add(user)
    db.session.commit()
Exemplo n.º 21
0
    form = RegistrationForm(request.form)
    if request.method == 'POST' and form.validate():
        user = User()

        form.populate_obj(user)
        user.save()

        login.login_user(user)
        return redirect(url_for('index'))

    return render_template('form.html', form=form)


@app.route('/logout/')
def logout_view():
    login.logout_user()
    return redirect(url_for('index'))

if __name__ == '__main__':
    # Initialize flask-login
    init_login()

    # Create admin
    admin = admin.Admin(app, 'Example: Auth-Mongo', index_view=MyAdminIndexView())

    # Add view
    admin.add_view(MyModelView(User))

    # Start app
    app.run(debug=True)
Exemplo n.º 22
0
    form = RegistrationForm(request.form)
    if request.method == 'POST' and form.validate():
        user = User()

        form.populate_obj(user)
        user.save()

        login.login_user(user)
        return redirect(url_for('index'))

    return render_template('form.html', form=form)


@app.route('/logout/')
def logout_view():
    login.logout_user()
    return redirect(url_for('index'))

if __name__ == '__main__':
    # Initialize flask-login
    init_login()

    # Create admin
    admin = admin.Admin(app, 'Example: Auth-Mongo', index_view=MyAdminIndexView())

    # Add view
    admin.add_view(MyModelView(User))

    # Start app
    app.run(debug=True)
Exemplo n.º 23
0
    '''
    form_create_rules = ('name1', rules.HTML('''
    <p class="drawItDesc">Draw your signature</p>
    <ul class="sigNav">
      <li class="drawIt"><a href="#draw-it" >Draw It</a></li>
      <li class="clearButton"><a href="#clear">Clear</a></li>
    </ul>
    <div class="sig sigWrapper">
      <div class="typed"></div>
      <canvas class="pad" width="298" height="55"></canvas>
      <input type="hidden" name="output" class="output">
    </div><br>
    '''), )
    
    create_template = 'create.html'
    edit_template = 'edit.html'
    action_disallowed_list = ('delete')
     
    
# Flask views
@app.route('/')
def index():
    return '<a style="font-size:3em;" , href="/admin/">Click me to get to Admin!</a>'

if __name__ == '__main__':
    # Create admin
    admin = admin.Admin(app, name="signature-pad")
    admin.add_view(PageAdmin(Page, db.session))
    db.create_all()
    app.run(debug=True)
Exemplo n.º 24
0
class PeopleGroupAid(BaseModel):
	people_event = peewee.ForeignKeyField(PeopleGroup, related_name = 'people get help on event')
	aid = peewee.ForeignKeyField(Resource, related_name = 'resource name')
	quantity = peewee.IntegerField()

	def __unicode__(self):
        return self.people_event

#class UserAdmin(ModelView):





class PeopleView(ModelView):

    #Visible columns in the list view
    column_exclude_list = ('middle_name', 'pspt_misc', 'pspt_issued',  'pspt_address', 'pspt_number')

    # List of columns that can be sorted.
    column_sortable_list = ('last_name', 'is_head')

    # Column filters
    column_filters = ('last_name',
                      'is_head',
                      'is_employee'
                      )    
    column_display_pk = 'True'

class ResourceView(ModelView):
    column_filters = ('name', )
    column_display_pk = 'True'

class LocationView(ModelView):
    #column_filters = ( 'name' )
    column_display_pk = 'True'



@app.route('/')
def index():
   return '<a href="/admin/">Click me to get to Admin!</a>'
   #return render_template('index.html')


if __name__ == '__main__':
    import logging
    logging.basicConfig()
    logging.getLogger().setLevel(logging.DEBUG)

    admin = admin.Admin(app, name='Dom gde teplo')
    admin.add_view(PeopleView(People))
    admin.add_view(ModelView(User))
    admin.add_view(ResourceView(Resource))
    admin.add_view(LocationView(Location))
    admin.add_view(ModelView(Project))
    admin.add_view(ModelView(Event))
    admin.add_view(ModelView(PeopleGroup))
    admin.add_view(ModelView(PeopleGroupAid))
    #admin.add_view(UserAdmin(User))
    #admin.add_view(PostAdmin(Post))

    try:
        Project.create_table()
        Event.create_table()
        PeopleGroup.create_table()
        PeopleGroupAid.create_table()
        User.create_table()
        People.create_table()
        Resource.create_table()
        Location.create_table()
        
        
    except:
        pass

    app.run(debug=True)
Exemplo n.º 25
0
    return '<a href="/admin/">Click me to get to Admin!</a>'


# Create admin
admin = admin.Admin(app, name='SoNaR', template_mode='bootstrap3')


# Add views
class BingSearchAdmin(sqla.ModelView):
    def _url_formatter(view, context, model, name):
        return Markup('<a href={0}>{0}</a>'.format(model.url))

    column_formatters = {'url': _url_formatter}
    column_default_sort = ('search_date', True)

admin.add_view(BingSearchAdmin(BingSearch, db.session))
admin.add_view(sqla.ModelView(CodeKeyword, db.session))


class CseSearchAdmin(sqla.ModelView):
    def _html_formatter(view, context, model, name):
        return Markup('<a href={0}>{0}</a>'.format(model.link))

    def _snippet_formatter(view, context, model, name):
        return Markup(model.html_snippet)

    column_formatters = {'link': _html_formatter,
                         'html_snippet': _snippet_formatter}
    column_default_sort = ('search_date', True)

admin.add_view(CseSearchAdmin(CseSearch, db.session))
Exemplo n.º 26
0
    ]
    can_export = True
    export_max_rows = 1000
    export_types = ['csv', 'xls']
    column_searchable_list = [
        Case.tc_id, Case.plan, Case.project, Case.result, Case.version
    ]
    column_editable_list = ['bug', 'result']
    create_modal = True
    edit_modal = True
    can_view_details = True


# Create admin
admin = admin.Admin(app, name='CMII--研发一部', template_mode='bootstrap3')
admin.add_view(CaseAdmin(Case, db.session, category="Lab"))

# Add views


def build_sample_db():
    db.drop_all()
    db.create_all()
    case_list = []
    for i in range(10):
        case = Case()
        case.tc_id = 'test_' + str(i + 1)

        # case_list.append(case)
        db.session.add(case)
Exemplo n.º 27
0
    first_name = db.Column(db.String(255))
    last_name = db.Column(db.String(255))
    email = db.Column(db.String(255), unique=True)
    password = db.Column(db.String(255))
    def __str__(self):
        return self.email

# Flask views
@app.route('/')
def index():
    return '<a href="/admin/">Click me to get to Admin!</a>'

@app.route('/ue_autocomplete', methods=['GET'])
def tag_f1_autocomplete():
    search = request.args.get('q')
    query = db.session.query(User.email).filter(User.email.like('%' + str(search) + '%'))
    results = [mv[0] for mv in query.all()]
    return jsonify(matching_results=results)
     
# Customized admin interface
class ListAdminView(sqla.ModelView):
    create_template = 'edit.html'
    edit_template = 'edit.html'

if __name__ == '__main__':
    # Create admin
    admin = admin.Admin(app, name="jQuery Autocomplete" , template_mode='bootstrap3')
    admin.add_view(ListAdminView(List, db.session))
    db.create_all()
    app.run(debug=True)
Exemplo n.º 28
0
    form_ajax_refs = {
        'user': {
            'fields': (User.username, 'email')
        }
    }


@app.route('/')
def index():
    return '<a href="/admin/">Click me to get to Admin!</a>'


if __name__ == '__main__':
    import logging
    logging.basicConfig()
    logging.getLogger().setLevel(logging.DEBUG)

    admin = admin.Admin(app, name='Example: Peewee')

    admin.add_view(UserAdmin(User))
    admin.add_view(PostAdmin(Post))

    try:
        User.create_table()
        UserInfo.create_table()
        Post.create_table()
    except:
        pass

    app.run(debug=True)
Exemplo n.º 29
0
        return redirect(url_for('.index'))


class Contact(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Text)
    email = db.Column(db.Text)
    message = db.Column(db.Text)
    mailing = db.Column(db.Integer)

    def __unicode__(self):
        return self.username

class Mailing(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Text)
    email = db.Column(db.Text)

    def __unicode__(self):
        return self.username

#Initialise Flask-Login
init_login()

#Create admin instance
admin = admin.Admin(app, name='Phoenix Coffee Admin', index_view=AdminPannel(), template_mode='bootstrap3')

#Add models to views
admin.add_view(ModelView(Contact, db.session, name='Contact Form', endpoint='contact'))
admin.add_view(ModelView(User, db.session, name='Users', endpoint='users'))
admin.add_view(ModelView(Mailing, db.session, name='Mailing', endpoint='Mailing'))
Exemplo n.º 30
0
    tmp = u"""
<p><a href="/admin/?lang=en">Click me to get to Admin! (English)</a></p>
<p><a href="/admin/?lang=cs">Click me to get to Admin! (Czech)</a></p>
<p><a href="/admin/?lang=de">Click me to get to Admin! (German)</a></p>
<p><a href="/admin/?lang=es">Click me to get to Admin! (Spanish)</a></p>
<p><a href="/admin/?lang=fa">Click me to get to Admin! (Farsi)</a></p>
<p><a href="/admin/?lang=fr">Click me to get to Admin! (French)</a></p>
<p><a href="/admin/?lang=pt">Click me to get to Admin! (Portuguese)</a></p>
<p><a href="/admin/?lang=ru">Click me to get to Admin! (Russian)</a></p>
<p><a href="/admin/?lang=zh_CN">Click me to get to Admin! (Chinese - Simplified)</a></p>
<p><a href="/admin/?lang=zh_TW">Click me to get to Admin! (Chinese - Traditional)</a></p>
"""
    return tmp


if __name__ == '__main__':
    # Create admin
    admin = admin.Admin(app, 'Example: Babel')

    #admin.locale_selector(get_locale)

    # Add views
    admin.add_view(sqla.ModelView(User, db.session))
    admin.add_view(sqla.ModelView(Post, db.session))

    # Create DB
    db.create_all()

    # Start app
    app.run(debug=True)
Exemplo n.º 31
0

# Flask views
@app.route('/')
def index():
    return '<a href="/admin/">Click me to get to Admin!</a>'

#~ 
#~ 
# Create admin
admin = admin.Admin(app, name='Example: SQLAlchemy', template_mode='bootstrap3')

# Add views
#admin.add_view(ModelView(Users, db.session))
#admin.add_view(ModelView(Posts, db.session))
admin.add_view(DiseaseAdmin(Disease, db.session))
#~ admin.add_view(sqla.ModelView(Tag, db.session))
#~ admin.add_view(PostAdmin(db.session))
#~ admin.add_view(TreeView(Tree, db.session))
#~ admin.add_view(ImageView(Image, db.session))

admin.add_view(UserAdmin(User, db.session))


if __name__ == '__main__':
	app.run(debug=True)



    # Start app
Exemplo n.º 32
0
    def index(self):

        return self.render('admin/rules.html')


# Initialize flask-login
init_login()

# Create admin
admin = admin.Admin(app,
                    '留言板后台',
                    index_view=MyAdminIndexView(),
                    base_template='my_master.html')

# Add view
admin.add_view(MyModelView(User, db.session, name='用户'))
# Add view
admin.add_view(MyModelView(Category, db.session, name='留言'))
# Add view
admin.add_view(MyModelView(SpiderP9, db.session, name='爬虫'))
admin.add_view(KeywordsView(Keywords, db.session, name=u'关键字'))

admin.add_view(RulesView(url='rules/', name='规则'))

from flask_admin.contrib.fileadmin import FileAdmin

import os.path as op

basedir = os.path.abspath(os.path.dirname(__file__))
file_path = op.join(basedir, 'static')
admin.add_view(FileAdmin(app.config['FILEDIR'], '/upload', name='文件'))
Exemplo n.º 33
0
class users(db.Model):
    __table__ = db.Table("users", db.metadata, autoload=True, autoload_with=db.engine)


# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Flask views
@app.route("/")
def index():
    return '<a href="/admin/">Click me to get to Admin!</a>'


# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# customize views..
class dgview(sqla.ModelView):
    column_display_pk = True


# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Create admin
admin = admin.Admin(app, name="fltg 9datetime picker", template_mode="bootstrap3")

admin.add_view(dgview(users, db.session))

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if __name__ == "__main__":

    # Start app
    app.run(host="0.0.0.0", port=5000, debug=True)

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Exemplo n.º 34
0
        super(PostAdmin, self).__init__(Post, session)


class TreeView(sqla.ModelView):
    form_excluded_columns = [
        'children',
    ]


# Create admin
admin = admin.Admin(app,
                    name='Example: SQLAlchemy',
                    template_mode='bootstrap3')

# Add views
admin.add_view(UserAdmin(User, db.session))
admin.add_view(sqla.ModelView(Tag, db.session))
admin.add_view(PostAdmin(db.session))
admin.add_view(TreeView(Tree, db.session))

admin.add_view(TreeView(Food, db.session))


def build_sample_db():
    """
    Populate a small db with some example entries.
    """

    import random
    import datetime
Exemplo n.º 35
0
from flask import Flask

from redis import Redis

import flask_admin as admin
from flask_admin.contrib import rediscli

# Create flask app
app = Flask(__name__)


# Flask views
@app.route('/')
def index():
    return '<a href="/admin/">Click me to get to Admin!</a>'


if __name__ == '__main__':
    # Create admin interface
    admin = admin.Admin(app, name="Example: Redis")
    admin.add_view(rediscli.RedisCli(Redis()))

    # Start app
    app.run(debug=True)
Exemplo n.º 36
0
class UserAdmin(CustomView):
    column_searchable_list = ('name', )
    column_filters = ('name', 'email')


# Flask views
@app.route('/')
def index():
    return '<a href="/admin/">Click me to get to Admin!</a>'


# Create admin with custom base template
admin = admin.Admin(app, 'Example: Layout', base_template='layout.html')

# Add views
admin.add_view(UserAdmin(User, db.session))
admin.add_view(CustomView(Page, db.session))


def build_sample_db():
    """
    Populate a small db with some example entries.
    """

    db.drop_all()
    db.create_all()

    first_names = [
        'Harry', 'Amelia', 'Oliver', 'Jack', 'Isabella', 'Charlie', 'Sophie',
        'Mia', 'Jacob', 'Thomas', 'Emily', 'Lily', 'Ava', 'Isla', 'Alfie',
        'Olivia', 'Jessica', 'Riley', 'William', 'James', 'Geoffrey', 'Lisa',
Exemplo n.º 37
0
        return self._feed_user_choices(form)

    def edit_form(self, obj):
        form = super(TweetView, self).edit_form(obj)
        return self._feed_user_choices(form)

    # Correct user_id reference before saving
    def on_model_change(self, form, model):
        user_id = model.get('user_id')
        model['user_id'] = ObjectId(user_id)

        return model


# Flask views
@app.route('/')
def index():
    return '<a href="/admin/">Click me to get to Admin!</a>'


if __name__ == '__main__':
    # Create admin
    admin = admin.Admin(app, name='Example: PyMongo')

    # Add views
    admin.add_view(UserView(db.user, 'User'))
    admin.add_view(TweetView(db.tweet, 'Tweets'))

    # Start app
    app.run(debug=True)
Exemplo n.º 38
0
class MultiLineString(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    point = db.Column(Geometry("MULTILINESTRING"))


# Flask views
@app.route('/')
def index():
    return '<a href="/admin/">Click me to get to Admin!</a>'


# Create admin
admin = admin.Admin(app, name='Example: GeoAlchemy', template_mode='adminlte2')

# Add views
admin.add_view(ModelView(Point, db.session, category='Points'))
admin.add_view(ModelView(MultiPoint, db.session, category='Points'))
admin.add_view(ModelView(Polygon, db.session, category='Polygons'))
admin.add_view(ModelView(MultiPolygon, db.session, category='Polygons'))
admin.add_view(ModelView(LineString, db.session, category='Lines'))
admin.add_view(ModelView(MultiLineString, db.session, category='Lines'))

if __name__ == '__main__':

    db.create_all()

    # Start app
    app.run(debug=True)
    
# Flask views
@app.route('/')
def index():
    return '<a href="/admin/">Click me to get to Admin!</a>'


#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   
class vwuser_view(sqla.ModelView):
    column_display_pk = True
    
    
# Create admin
admin = admin.Admin(app, name='flpg6 reflect view', template_mode='bootstrap3')
#admin.add_view(CarAdmin(Car, db.session))
#admin.add_view(TyreAdmin(Tyre, db.session))
admin.add_view(vwuser_view(vw_user1, db.session))

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

if __name__ == '__main__':

    # Create DB
    #db.create_all()

    # Start app
    app.run(host='0.0.0.0', port=5000, debug=True)
    
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Exemplo n.º 40
0
    def _use_filtered_parent(self, form):
        form.pets.query_factory = self._get_parent_list
        return form

    def _get_parent_list(self):
        # only show available pets in the form
        return Pet.query.filter_by(available=True).all()

    def __unicode__(self):
        return self.name


# Create admin
admin = admin.Admin(app, name='Example: SQLAlchemy - Filtered Form Selectable',
                    template_mode='bootstrap3')
admin.add_view(PersonAdmin(Person, db.session))
admin.add_view(sqla.ModelView(Pet, db.session))

if __name__ == '__main__':
    # Recreate DB
    db.drop_all()
    db.create_all()

    person = Person(name='Bill')
    pet1 = Pet(name='Dog', available=True)
    pet2 = Pet(name='Fish', available=True)
    pet3 = Pet(name='Ocelot', available=False)
    db.session.add_all([person, pet1, pet2, pet3])
    db.session.commit()

    # Start app
Exemplo n.º 41
0
sys.setdefaultencoding('utf8')

formatter = logging.Formatter(
    "[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s")
handler = RotatingFileHandler('kuaidi.log', maxBytes=10000000, backupCount=5)
handler.setLevel(logging.ERROR)
handler.setFormatter(formatter)
app.logger.addHandler(handler)

admin = admin.Admin(
                    app,
                    name=u'阳成科技',
                    index_view=MyAdminIndexView(),
                    base_template='my_master.html'
                    )
# admin.locale_selector(get_locale)
admin.add_view(ReceiptView(Receipt, db.session, u'收快递'))
admin.add_view(PostView(Post, db.session, u'发快递'))
# for admin
admin.add_view(CommunityView(Community, db.session, u'小区'))
admin.add_view(UserView(User, db.session, u'管理员'))
admin.add_view(ReceiptReportView(ReceiptReport, db.session, u'收件单报表'))
admin.add_view(PostReportView(PostReport, db.session, u'发件单报表'))
admin.add_view(NotReceiveReportView(NotReceiveReport, db.session, u'未收快递报表'))

if __name__ == '__main__':
    # admin.add_view(MyView(name='Hello'))
    app.run()

    # app.run(host='0.0.0.0',port=8080)
Exemplo n.º 42
0
app.config.from_envvar('DEV_SETTINGS', silent=True)

# limiter to temper with registration abuse
registration_limiter = Limiter(
    app,
    key_func = get_remote_address)

# flask-login
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"
login_manager.login_message = "Vous devez être connectés pour créer ou éditer des pages"

# Setting up flask-admin
admin = admin.Admin(app, name='Wikiloult Admin', index_view=CheckCookieAdminView())
admin.add_view(UserView(UsersConnector().users, 'Users'))
admin.add_view(PageView(WikiPagesConnector().pages, 'Pages'))


@login_manager.user_loader
def load_user(user_cookie):
    return User(user_cookie)


def autologin(function):
    @wraps(function)
    def with_login():
        """Decorator that tries to log in automatically is the cookie is already
        set by a past login, by setting the session"""
        cookie = request.cookies.get("id", None)
        if cookie is not None:
Exemplo n.º 43
0
    id = db.Column(db.Integer, primary_key=True)
    width = db.Column(db.Integer, nullable=False)
    height = db.Column(db.Integer, nullable=False)

    @hybrid_property
    def number_of_pixels(self):
        return self.width * self.height


class ScreenAdmin(sqla.ModelView):
    """ Flask-admin can not automatically find a hybrid_property yet. You will
        need to manually define the column in list_view/filters/sorting/etc."""
    list_columns = ['id', 'width', 'height', 'number_of_pixels']
    column_sortable_list = ['id', 'width', 'height', 'number_of_pixels']

    # Flask-admin can automatically detect the relevant filters for hybrid properties.
    column_filters = ('number_of_pixels', )


# Create admin
admin = admin.Admin(app, name='Example: SQLAlchemy2', template_mode='bootstrap3')
admin.add_view(ScreenAdmin(Screen, db.session))

if __name__ == '__main__':

    # Create DB
    db.create_all()

    # Start app
    app.run(debug=True)
Exemplo n.º 44
0
@app.route('/')
def index():
    return render_template('index.html')


# Initialize flask-login
init_login()

# Create admin
admin = admin.Admin(app,
                    'Example: Auth',
                    index_view=MyAdminIndexView(),
                    base_template='my_master.html')

# Add view
admin.add_view(MyModelView(User, db.session))
path = op.join(op.dirname(__file__), 'static')
admin.add_view(FileView(path, '/static/', name='Static Files'))


def build_sample_db():
    """
    Populate a small db with some example entries.
    """

    # import string
    # import random

    db.drop_all()
    db.create_all()
    # passwords are hashed, to use plaintext passwords instead:
Exemplo n.º 45
0

class MultiLineString(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    point = db.Column(Geometry("MULTILINESTRING"))


# Flask views
@app.route('/')
def index():
    return '<a href="/admin/">Click me to get to Admin!</a>'

# Create admin
admin = admin.Admin(app, name='Example: GeoAlchemy', template_mode='adminlte2')

# Add views
admin.add_view(ModelView(Point, db.session, category='Points'))
admin.add_view(ModelView(MultiPoint, db.session, category='Points'))
admin.add_view(ModelView(Polygon, db.session, category='Polygons'))
admin.add_view(ModelView(MultiPolygon, db.session, category='Polygons'))
admin.add_view(ModelView(LineString, db.session, category='Lines'))
admin.add_view(ModelView(MultiLineString, db.session, category='Lines'))

if __name__ == '__main__':

    db.create_all()

    # Start app
    app.run(debug=True)
Exemplo n.º 46
0
        super(LocationAdmin, self).__init__(Location,
                                            db.session,
                                            name='Locations')


# Simple page to show images
@app.route('/')
def index():
    locations = db.session.query(Location).all()
    return render_template('locations.html', locations=locations)


if __name__ == '__main__':
    # Create upload directory
    try:
        os.mkdir(base_path)
    except OSError:
        pass

    # Create admin
    admin = admin.Admin(app, name='Example: Inline Models')

    # Add views
    admin.add_view(LocationAdmin())

    # Create DB
    db.create_all()

    # Start app
    app.run(debug=True)
Exemplo n.º 47
0
    form_overrides = dict(cartype=SelectField)
    form_args = dict(cartype=dict(choices=[
                ('', 'Please Select'),
                ('Compact', 'Compact'),
                ('Mid-size', 'Mid-size'),
                ('Pickup Truck', 'Pickup Truck')
            ]))

from wtforms import Form, BooleanField, TextField, validators

class carForm(Form):
    desc     = TextField('desc', [validators.Length(min=4, max=25)])
    
def register(request):
    form = carForm(request.POST)
    if request.method == 'POST' and form.validate():
        car = Car()
        car.desc = form.desc.data
        car.save()
        redirect('register')
    return render_response('analytics2.html', form=form)

# Create admin
admin = admin.Admin(app, name='31form', template_mode='bootstrap3')
admin.add_view(AnalyticsView(name='Analytics', endpoint='ana'))
admin.add_view(CarAdmin(Car, db.session))

if __name__ == '__main__':
    db.create_all()
    app.run(debug=True)
Exemplo n.º 48
0
    form_overrides = dict(text1=CKTextAreaField)

    form_create_rules = ('name1','text1', rules.HTML('''
    <p class="drawItDesc">Draw your signature</p>
    <ul class="sigNav">
      <li class="drawIt"><a href="#draw-it" >Draw It</a></li>
      <li class="clearButton"><a href="#clear">Clear</a></li>
    </ul>
    <div class="sig sigWrapper">
      <div class="typed"></div>
      <canvas class="pad" width="198" height="55"></canvas> 
          
    '''), 'output', rules.HTML('</div>'))
    
    create_template = 'create.html'
    edit_template = 'edit.html'

     
    
# Flask views
@app.route('/')
def index():
    return '<a style="font-size:3em;" , href="/admin/">Click me to get to Admin!</a>'

if __name__ == '__main__':
    # Create admin
    admin = admin.Admin(app, name="Example: WYSIWYG")
    admin.add_view(PageAdmin(Page, db.session))
    db.create_all()
    app.run(debug=True)
Exemplo n.º 49
0
        try:
            query = User.query.filter(User.id.in_(ids))

            count = 0
            for user in query.all():
                #import pdb;  pdb.set_trace()
                user.active = 1
                user.confirmed_at = datetime.datetime.fromtimestamp(time.time())
                db.session.commit()
                count += 1

            flash('User was successfully approved.'  )
        
        except Exception as ex:
            if not self.handle_view_exception(ex):
                raise

            flash(gettext('Failed to approve users. %(error)s', error=str(ex)), 'error')        
        

# Flask views
@app.route('/')
def index():
    return '<a href="/admin/">Click me to get to Admin!</a>'

if __name__ == '__main__':
    admin = admin.Admin(app, name="Batch-action" , template_mode='bootstrap3')
    admin.add_view(UserView(User, db.session))
    db.create_all()
    app.run(debug=True)
Exemplo n.º 50
0
    # Force specific template
    #list_template = 'color_list.html'
    create_template = 'dvform.html'
    edit_template = 'dvform.html'

  
    LastName= QuerySelectField(query_factory=lambda: models.User.query.all(),
                           widget=Select2Widget())


#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
# Create admin
admin = admin.Admin(app, name='fltg 28select', template_mode='bootstrap3')

admin.add_view(dgview(users, db.session))
admin.add_view(Personview(Person, db.session))
admin.add_view(dgview(Order, db.session))

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

if __name__ == '__main__':

    # Create DB
    #db.create_all()

    # Start app
    app.run(host='0.0.0.0', port=5000, debug=True)
    
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Exemplo n.º 51
0
        )
    )


from wtforms import Form, BooleanField, TextField, validators


@app.route("/new", methods=["GET", "POST"])
def new():
    if request.method == "POST":
        if not request.form["name"] or not request.form["city"] or not request.form["addr"]:
            flash("Please enter all the fields", "error")
        else:
            student = students(request.form["name"], request.form["city"], request.form["addr"], request.form["pin"])

            db.session.add(student)
            db.session.commit()

            flash("Record was successfully added")
            return redirect(url_for("show_all"))
    return render_template("new.html")


# Create admin
admin = admin.Admin(app, name="31form", template_mode="bootstrap3")
admin.add_view(CarAdmin(Car, db.session))

if __name__ == "__main__":
    db.create_all()
    app.run(debug=True)
Exemplo n.º 52
0
            role = db.session.query(Role).filter(Role.id==2).first()
            user.roles.append(role)
            db.session.add(user)
            db.session.commit()
            flash('The user was created successfully')
        return self.render('open_account.html', form=formAccount)

    def is_visible(self):
        return login.current_user.is_authenticated


init_login()

admin = admin.Admin(app, 'ANYWAY Administration Panel', index_view=AdminIndexView(), base_template='admin_master.html')

admin.add_view(AdminView(User, db.session, name='Users', endpoint='Users', category='Users'))
admin.add_view(AdminView(Role, db.session, name='Roles', endpoint='Roles'))
admin.add_view(OpenNewOrgAccount(name='Open new organization account', endpoint='OpenAccount', category='Users'))
admin.add_view(SendToSubscribersView(name='Send To Subscribers'))
admin.add_view(ViewHighlightedMarkersData(name='View Highlighted Markers Data', endpoint='ViewHighlightedMarkersData', category='View Highlighted Markers'))
admin.add_view(ViewHighlightedMarkersMap(name='View Highlighted Markers Map', endpoint='ViewHighlightedMarkersMap', category='View Highlighted Markers'))

cbs_dictionary = {}

@app.before_first_request
def read_dictionaries():
    global cbs_dictionary
    for directory in sorted(glob.glob("{0}/{1}/*/*".format(app.static_folder, 'data/cbs')),reverse=True):
        main_dict = dict(get_dict_file(directory))
        if len(main_dict) == 0:
            return
app.config['SECRET_KEY'] = '12345679'
engine = create_engine('sqlite:///test.sqlite', convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
metadata = MetaData(bind=engine)

def init_db():
    Base.metadata.create_all(bind=engine)

@app.teardown_appcontext
def shutdown_session(exception=None):
    db_session.remove()

# reflect users table..
class User(Base):
    __table__ = Table('users', metadata, autoload=True)
 
# Flask views
@app.route('/')
def index():
    return '<a href="/admin/">Click me to get to Admin!</a>'

# Create admin
admin = admin.Admin(app, name='db-4-reflect', template_mode='bootstrap3')
admin.add_view(sqla.ModelView(User, db_session))

if __name__ == '__main__':
    init_db()
    app.run(host='0.0.0.0', port=5000, debug=True)
Exemplo n.º 54
0
app.secret_key = '736670cb10a600b695a55839ca3a5aa54a7d7356cdef815d2ad6e19a2031182b'

db.init_app(app)
try:
    with app.app_context():
        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)
import flask_admin as admin1
admin = admin1.Admin(app, 'Elogstation', index_view=MyAdminIndexView())
# Add view
admin.add_view(MyModelView(User, db.session))
app.register_blueprint(account_blueprint)
app.register_blueprint(drivers_blueprint)
app.register_blueprint(dvir_blueprint)
app.register_blueprint(logs_blueprint)
app.register_blueprint(devices_blueprint)
app.register_blueprint(trucks_blueprint)
app.register_blueprint(elogstation_blueprint)
app.register_blueprint(webservices_blueprint)
app.register_blueprint(map_blueprint)
rest_api.add_resource(ELDAPI, '/api/eld')
rest_api.add_resource(EventsAPI, '/api/events')
rest_api.add_resource(StatusAPI, '/api/status')
rest_api.add_resource(AuthApi, '/api/auth')
rest_api.add_resource(PostAPI, '/api/post')
rest_api.add_resource(PostEventsAPI, '/api/post_events')
Exemplo n.º 55
0
    def __repr__(self):
        return '<User %r>' % (self.name)
        
        
    
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


# Flask views
@app.route('/')
def index():
    return '<a href="/admin/">Click me to get to Admin!</a>'

    
'''
class Car(db.Model):
    __tablename__ = 'cars'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    desc = db.Column(db.String(50))

    def __unicode__(self):
        return self.desc

class Tyre(db.Model):
    __tablename__ = 'tyres'
    car_id = db.Column(db.Integer, db.ForeignKey('cars.id'), primary_key=True)
    tyre_id = db.Column(db.Integer, primary_key=True)
    car = db.relationship('Car', backref='tyres')
    desc = db.Column(db.String(50))
Exemplo n.º 56
0
    height = db.Column(db.Integer, nullable=False)

    @hybrid_property
    def number_of_pixels(self):
        return self.width * self.height


class ScreenAdmin(sqla.ModelView):
    """ Flask-admin can not automatically find a hybrid_property yet. You will
        need to manually define the column in list_view/filters/sorting/etc."""
    list_columns = ['id', 'width', 'height', 'number_of_pixels']
    column_sortable_list = ['id', 'width', 'height', 'number_of_pixels']

    # Flask-admin can automatically detect the relevant filters for hybrid properties.
    column_filters = ('number_of_pixels', )


# Create admin
admin = admin.Admin(app,
                    name='Example: SQLAlchemy2',
                    template_mode='bootstrap3')
admin.add_view(ScreenAdmin(Screen, db.session))

if __name__ == '__main__':

    # Create DB
    db.create_all()

    # Start app
    app.run(debug=True)
Exemplo n.º 57
0
    }

    def __init__(self, session):
        # Just call parent class with predefined model.
        super(PostAdmin, self).__init__(Post, session)


class TreeView(sqla.ModelView):
    form_excluded_columns = ['children', ]


# Create admin
admin = admin.Admin(app, name='Example: SQLAlchemy', template_mode='bootstrap3')

# Add views
admin.add_view(UserAdmin(User, db.session))
admin.add_view(sqla.ModelView(Tag, db.session))
admin.add_view(PostAdmin(db.session))
admin.add_view(TreeView(Tree, db.session))


def build_sample_db():
    """
    Populate a small db with some example entries.
    """

    import random
    import datetime

    db.drop_all()
    db.create_all()
Exemplo n.º 58
0
from models.user import user_blueprint
from models.role import role_blueprint
from models.organization import org_blueprint
from models.surveyq_category import surveyq_category_blueprint
from models.survey_questionnaire import surveyq_blueprint
from models.survey_answer import survey_ans_blueprint
from models.client_register import clients_blueprint
from models.client_details import client_details_blueprint
from models.client_response import client_response_blueprint
from models.survey_types import survey_type_blueprint
from models.client_class import client_class_blueprint
from models.client_class_types import client_class_type_blueprint
from models.client_response_summary import client_response_summary_blueprint

admin = admin.Admin(app, name='Hygiene Tracker', template_mode='bootstrap3', base_template='layout.html')
admin.add_view(UserAdmin(User, db.session))
admin.add_view(OrganizationAdmin(Organization, db.session))
admin.add_view(RoleAdmin(Role, db.session))
admin.add_view(OccupationAdmin(Occupation, db.session))
admin.add_view(HouseTypeAdmin(HouseType, db.session))
admin.add_view(SurveyQCategoryAdmin(SurveyQCategory, db.session, category='Survey'))
admin.add_view(SurveyQuestionnaireAdmin(SurveyQuestionnaire, db.session, category='Survey'))
admin.add_view(SurveyAnswerAdmin(SurveyAnswer, db.session, category='Survey'))
admin.add_view(SurveyTypeAdmin(SurveyType, db.session, category='Survey'))
admin.add_view(ClientRegisterAdmin(ClientRegister, db.session, category='Client'))
admin.add_view(ClientDetailsAdmin(ClientDetails, db.session, category='Client'))
admin.add_view(ClientResponseAdmin(ClientResponse, db.session, category='Client'))
admin.add_view(ClientClassTypeAdmin(ClientClassType, db.session, category='Client'))
#admin.add_view(ClientClassAdmin(ClientClass, db.session, category='Client'))
admin.add_view(ClientResponseSummaryAdmin(ClientResponseSummary, db.session, category='Client'))
Exemplo n.º 59
0
class UserAdmin(CustomView):
    column_searchable_list = ('name',)
    column_filters = ('name', 'email')


# Flask views
@app.route('/')
def index():
    return '<a href="/admin/">Click me to get to Admin!</a>'


# Create admin with custom base template
admin = admin.Admin(app, 'Example: Layout-BS3', base_template='layout.html', template_mode='bootstrap3')

# Add views
admin.add_view(UserAdmin(User, db.session))
admin.add_view(CustomView(Page, db.session))


def build_sample_db():
    """
    Populate a small db with some example entries.
    """

    db.drop_all()
    db.create_all()

    first_names = [
        'Harry', 'Amelia', 'Oliver', 'Jack', 'Isabella', 'Charlie','Sophie', 'Mia',
        'Jacob', 'Thomas', 'Emily', 'Lily', 'Ava', 'Isla', 'Alfie', 'Olivia', 'Jessica',
        'Riley', 'William', 'James', 'Geoffrey', 'Lisa', 'Benjamin', 'Stacey', 'Lucy'
Exemplo n.º 60
0
                        'diseases',
                        #'raw_data',
                        #rules.HTML('<hr>')
                    ),
                    'form_widget_args': {
                        'total_score': {
                            'style': 'color: red'
                        }
                    }
                }
            }
        }
    }


# Create admin
admin = admin.Admin(app, 'Healthy Camp Monitoring Tool')

# Add views
admin.add_view(SiteView(Sites))


# Flask views
@app.route('/')
def index():
    return redirect('/admin')


if __name__ == '__main__':
    # Start app
    app.run(debug=True, use_reloader=True)