Exemplo n.º 1
0
def configure_nav(app):
    nav = Nav()
    nav.register_element('my_nav_bar', my_nav_bar)
    nav.register_element('sec_nav_bar', sec_nav_bar)
    nav.register_element('unauthenticated_nav', unauthenticated_nav)
    nav.init_app(app)
Exemplo n.º 2
0
        # finally for non ROLE_SUPER_ADMIN
        else:
            navbar.items.append(View('My Account', 'security.change_password'))

    else:
        navbar.items.append(View('Home', 'frontend.home', interest=g.interest))
        if g.interest:
            usermemberssviews = Subgroup('Membership')
            navbar.items.append(usermemberssviews)
            usermemberssviews.items.append(
                View('Registered Members',
                     'frontend.members',
                     interest=g.interest))
            usermemberssviews.items.append(
                View('Membership Stats',
                     'frontend.membershipstats',
                     interest=g.interest))

    # common items
    if g.interest:
        pass
    navbar.items.append(View('About', 'admin.sysinfo'))
    if request.path in contexthelp:
        navbar.items.append(Link('Help', contexthelp[request.path]))

    return navbar


thisnav.init_app(current_app)
Exemplo n.º 3
0
from flask_bootstrap import Bootstrap
from flask_nav import Nav
from flask_nav.elements import Navbar, View

application = Flask(__name__)
Bootstrap( application )
nav = Nav()

application.config.from_object( Config )

db = SQLAlchemy( application )
migrate = Migrate( application, db )

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

from app import routes, models

# Defining navigation bars
@nav.navigation()
def main_navbar():
    return Navbar(
        'Recommendation App', 
        View('Home', 'home'), 
        View('Register', 'register'),
        View('Logout', 'logout'),
    )

nav.init_app( application )
Exemplo n.º 4
0
def create_app():
    app = Flask(__name__)

    # Extensions
    nav = Nav()
    nav.init_app(app)

    bs = Bootstrap()
    bs.init_app(app)

    @nav.navigation()
    def mynavbar():
        return Navbar(
            "Flasked Altair Demo",
            View("Home", "index"),
            View("Cars charts", "show_cars"),
            View("Electricity charts", "show_electricity"),
            Subgroup(
                "References",
                Link("Altair", "https://altair-viz.github.io/index.html"),
                Link("Vega-Lite", "https://vega.github.io/vega-lite/"),
                Link("D3", "http://d3js.org/"),
                Link("Flask", "http://flask.pocoo.org/"),
            ),
        )

    ##########################
    # Flask routes
    ##########################
    # render index.html home page
    @app.route("/")
    def index():
        return render_template("index.html")

    # render cars.html page
    @app.route("/cars")
    def show_cars():
        return render_template("cars.html")

    # render iowa electricity.html
    @app.route("/electricity")
    def show_electricity():
        return render_template("electricity.html")

    #########################
    # Altair Data Routes
    #########################

    WIDTH = 800
    HEIGHT = 300

    @app.route("/data/waterfall")
    def data_waterfall():
        chart = (Chart(
            data=sample_data.df_water,
            width=WIDTH,
        ).mark_bar(color="gray").encode(
            X("Name", axis=Axis(title="Sample")),
            Y("Value", axis=Axis(title="Value")),
        ).interactive())
        return chart.to_json()

    @app.route("/data/line")
    def data_line():
        chart = (Chart(data=sample_data.df_list, height=HEIGHT,
                       width=WIDTH).mark_line(color="green").encode(
                           X("name", axis=Axis(title="Sample")),
                           Y("data", axis=Axis(title="Value")),
                       ).interactive())
        return chart.to_json()

    @app.route("/data/multiline")
    def data_multiline():
        chart = (Chart(data=sample_data.df_stocks, height=HEIGHT,
                       width=WIDTH).mark_line().encode(
                           color="symbol:N",
                           x="date:T",
                           y="price:Q",
                       ).interactive())
        return chart.to_json()

    @app.route("/data/stocks")
    def stocks():
        chart = (Chart(data=sample_data.df_stocks, height=HEIGHT,
                       width=WIDTH).mark_bar().encode(
                           color="symbol:N",
                           x="date:T",
                           y="price:Q",
                       ).interactive())
        return chart.to_json()

    @app.route("/data/scatter")
    def scatter():
        chart = (Chart(sample_data.df_0, height=HEIGHT,
                       width=WIDTH).mark_circle().encode(
                           x="name:N", y="y2:Q").interactive())
        return chart.to_json()

    @app.route("/data/bar")
    def data_bar():
        chart = (Chart(data=sample_data.df_list, height=HEIGHT,
                       width=WIDTH).mark_bar(color="yellow").encode(
                           X("name", axis=Axis(title="Sample")),
                           Y("data", axis=Axis(title="Value")),
                       ).interactive())
        return chart.to_json()

    # Creates graph for cars
    @app.route("/data/cars")
    def cars_demo():

        chart = (Chart(data=cars, height=700, width=700).mark_point().encode(
            x="Horsepower",
            y="Miles_per_Gallon",
            color="Origin",
        ).interactive())
        return chart.to_json()

    # Creates graph for IOWA electricity consumption
    @app.route("/data/electricity")
    def electricity_demo():

        chart = (Chart(
            data=electricity, height=700,
            width=700).mark_area().encode(x="year:T",
                                          y="net_generation:Q",
                                          color="source:N").interactive())
        return chart.to_json()

    # Creates graph for IOWA electricity consumption
    @app.route("/data/barley_yield")
    def barley_yield_demo():

        chart = (Chart(data=barley_yield, height=400,
                       width=150).mark_bar().encode(
                           x="year:O",
                           y="sum(yield):Q",
                           color="year:N",
                           column="site:N").interactive())
        return chart.to_json()

    return app
Exemplo n.º 5
0
from sqlalchemy.testing import db
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import *

SECRET_KEY = 'projeto2'

app = Flask(__name__)
app.secret_key = SECRET_KEY

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///lab02.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

boostrap = Bootstrap(app)  # isso habilita o template bootstrap/base.html
nav = Nav()
nav.init_app(
    app)  # isso habilita a criação de menus de navegação do pacote Flask-Nav


@nav.navigation()
def meunavbar():
    menu = Navbar('Urna 3000')
    menu.items = [View('Resultados', 'listarEleicaoResultados')]
    menu.items.append(View('Login', 'autenticar'))
    if ('logged_in' in session) and session['logged_in'] and (session['tipo']
                                                              == 1):
        menu.items.append(
            Subgroup('Manipular Pessoa', View('Adicionar Pessoa',
                                              'criarPessoa'),
                     View('Alterar tipo Pessoa',
                          'listarPessoaParaTrocarTipo')))
        menu.items.append(View('Criar Eleicao', 'criarEleicao'))
Exemplo n.º 6
0
def configure_nav(app):
    nav = Nav()
    nav.register_element('mynavbar', mynavbar)
    nav.register_element('secnavbar', secnavbar)
    nav.init_app(app)
Exemplo n.º 7
0
def create_app():
    app = Flask(__name__)
    Bootstrap(app)
    nav = Nav()

    nav.register_element(
        'top',
        Navbar(
            View('Overview', 'overview'),
            Subgroup('Groups', View('List Groups', 'list_group'),
                     View('Add Group', 'add_group')),
            Subgroup('Servers', View('List Servers', 'list_server'),
                     View('Add Server', 'add_server')),
            View('Ban', 'index'),
            View('Users', 'index'),
        ))

    nav.init_app(app)

    # init varnish
    varnish = Varnish()

    # remove this please
    core = Core('192.168.99.100', 'varnishmon', 'root', '123.')

    # function for make response to charts
    def makeResponse(r):
        response = make_response(r)
        response.content_type = 'application/json'
        return response

    # index content
    @app.route('/')
    def index():
        return "ok"

    @app.route('/overview', methods=['GET', 'POST'])
    def overview():
        if request.method == 'GET':
            response = core.listGroup()
            servers = core.listServer(1)
            return render_template('overview.html',
                                   groups=response,
                                   servers=servers,
                                   group_id=1)
        else:
            response = core.listGroup()
            return redirect('/overview/' + request.form['group_id'])

    @app.route('/overview/<group_id>', methods=['GET'])
    def overview_select(group_id):
        group_list = core.listGroup()
        servers = core.listServer(group_id)
        return render_template('overview.html',
                               groups=group_list,
                               servers=servers,
                               group_id=int(group_id))

    @app.route('/add_group', methods=['GET', 'POST'])
    def add_group():
        if request.method == 'GET':
            return render_template('addGroup.html')
        else:
            response = core.addGroup(request.form['name'])
            return response

    @app.route('/list_group')
    def list_group():
        response = core.listGroup()
        return render_template('listGroup.html', groups=response)

    @app.route('/add_server', methods=['GET', 'POST'])
    def add_server():
        if request.method == 'GET':
            response = core.listGroup()
            return render_template('addServer.html', groups=response)
        else:
            response = core.addServer(request.form['name'], request.form['ip'],
                                      request.form['port'],
                                      request.form['password'],
                                      request.form['group'])
            return response

    @app.route('/list_server')
    def list_server():
        response = core.listServer()
        return render_template('listServer.html', servers=response)

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

    #
    # response for charts data
    #
    @app.route('/live/hit/<group_id>')
    def hit(group_id):
        response = core.listServer(group_id)
        v = varnish.only_hit_or_miss('hit', servers=response)

        return makeResponse(v)

    @app.route('/live/miss/<group_id>')
    def miss(group_id):
        response = core.listServer(group_id)
        v = varnish.only_hit_or_miss('miss', servers=response)
        return makeResponse(v)

    @app.route('/live/client_req/<group_id>')
    def client_req(group_id):
        response = core.listServer(group_id)
        v = varnish.client_req(servers=response)
        return makeResponse(v)

    @app.route('/live/health/<group_id>')
    def health(group_id):
        response = core.listServer(group_id)
        v = varnish.health(servers=response)
        return makeResponse(v)

    return app
Exemplo n.º 8
0
#
#   Navbar
#

nav = Nav()

@nav.navigation()
def mynavbar():
    return Navbar(
        'Celebrity Death Clock',
        View('Home', 'index'),
        View('About', 'page', path="about")
    )

nav.init_app(app)


#
#   App Routes
#

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

    def safe_get(headlines, index):
        record = headlines[index] if index < len(headlines) else None
        try:
            return record.person, record.created_at.date(), record.url
        except:
Exemplo n.º 9
0
def configure_nav(app):
    nav = Nav()
    nav.register_element('base', basebar)
    nav.register_element('ctx', ctxbar)
    nav.init_app(app)
Exemplo n.º 10
0
      filename = file.filename
      print os.path.join('uploads/',filename)
      file.save(os.path.join('static/uploads/',filename))
      
      image_url = os.path.join('uploads/',filename)
      image_name=filename
      image = MyImage(image_url=image_url,image_name=image_name)
      session.add(image)
      session.commit()
      print 'image uploaded'
      
      print filename
      return redirect('/')    
    return redirect('/')
      
nav.init_app(app)  #nav bar    

class NameForm(Form):
  name = StringField('What is your name?')
  submit = SubmitField('Submit')

class RegistrationForm(Form):
    username = StringField('Username', [validators.Length(min=4, max=25)])
    email = StringField('Email Address', [validators.Length(min=6, max=35)])
    password = PasswordField('New Password', [
        validators.DataRequired(),
        validators.EqualTo('confirm', message='Passwords must match')
    ])
    confirm = PasswordField('Repeat Password')
    accept_tos = BooleanField('I accept the TOS', [validators.DataRequired()])    
    
Exemplo n.º 11
0
from db_connector.db_connector import connect_to_database, execute_query
from flask_bootstrap import Bootstrap
from flask_nav import Nav
from flask_nav.elements import Navbar, View
from flask_wtf import FlaskForm
from wtforms import Form, TextField, IntegerField, StringField, DecimalField, validators
from wtforms.validators import DataRequired, Regexp, AnyOf

nav = Nav()

#create the web application
webapp = Flask(__name__)
webapp.secret_key = 'cs340_2019'

Bootstrap(webapp)
nav.init_app(webapp)

### NAVIGATION

@nav.navigation()
def nav_login():
    return Navbar(
        'Food Delivery Inc.'
    )

@nav.navigation()
def nav_customer():
    return Navbar(
        'Food Delivery Inc.',
        View('Home', 'home_customer'),
        View('Search', 'search'),
Exemplo n.º 12
0
def create_app():
    app = Flask(__name__)

    # load config
    configure_app(app)
    db.init_app(app)

    # create task executor
    executor = ThreadPoolExecutor(app.config['TASK_POOL_SIZE'])

    # Bootstrap flask-bootstrap
    Bootstrap(app)

    # Navbar flask-nav
    topbar = Navbar(
        '',
        View('Task', 'task'),
        View('Host', 'host'),
    )
    nav = Nav()
    nav.register_element('top', topbar)
    nav.init_app(app)

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

    # host operation
    @app.route('/host')
    def host():
        hosts = Host.query.filter(
            Host.status != Status.query.filter_by(title=Status.SOURCE).first())

        return render_template('host.html', hosts=hosts)

    @app.route('/host/form/')
    @app.route('/host/form/<host_id>')
    def host_form(host_id=None):
        host = None
        if host_id != None:
            host = Host.query.filter_by(id=host_id).first()
        status = Status.query.all()

        return render_template('host_form.html', host=host, status=status)

    @app.route('/host/delete/<host_id>')
    def host_delete(host_id):
        delete_host = Host.query.filter_by(id=host_id).first()
        delete_host.delete()

        flash('Host #%s %s deleted.' % (delete_host.id, delete_host.name()))

        return redirect(url_for('host'))

    @app.route('/host/update/<host_id>', methods=['POST'])
    def host_update(host_id):
        update_host = Host.query.filter_by(id=host_id).first()

        id = host_id
        ip = request.form['host_ip']
        port = request.form['host_port']
        domain = request.form['host_domain']
        pwd = request.form['host_pwd']
        db_pwd = request.form['host_db_pwd']
        memo = request.form['host_memo']
        status = request.form['host_status']

        update_host.update(ip, port, domain, pwd, db_pwd, memo, status)

        flash('Host #%s "%s" updated.' % (update_host.id, update_host.name()))

        return redirect(url_for('host'))

    @app.route('/host/add', methods=['POST'])
    def host_add():
        ip = request.form['host_ip']
        port = request.form['host_port']
        domain = request.form['host_domain']
        pwd = request.form['host_pwd']
        db_pwd = request.form['host_db_pwd']
        memo = request.form['host_memo']
        status = request.form['host_status']

        new_host = Host(ip, port, domain, pwd, db_pwd, memo, status)
        new_host = new_host.create()

        flash('Host #%s "%s" added.' % (new_host.id, new_host.name()))

        return redirect(url_for('host'))

    # Tasks

    # task
    @app.route('/task')
    def task():
        tasklogs = TaskLog.query.order_by(desc(TaskLog.id)).all()
        return render_template('task.html', tasklogs=tasklogs)

    # clone site task
    @app.route('/task/clone_site/form')
    def task_clone_site_form():
        source_hosts = Host.query.filter_by(status=Status.query.filter_by(
            title=Status.SOURCE).first())
        target_hosts = Host.query.filter(
            Host.status != Status.query.filter_by(title=Status.SOURCE).first())
        order_start_id = SettingOrderStartNumber().get()

        return render_template('task_clone_site_form.html',
                               source_hosts=source_hosts,
                               target_hosts=target_hosts,
                               order_start_id=order_start_id)

    # clone site task
    @app.route('/task/clone_site', methods=['POST'])
    def task_clone_site():
        site_type = request.form['site_type']
        source_host_id = request.form['source_host_id']
        target_host_id = request.form['target_host_id']
        table_prefix = request.form['table_prefix']
        order_start_id = SettingOrderStartNumber().inc_interval()
        smtp_host = request.form['smtp_host']
        smtp_username = request.form['smtp_username']
        smtp_password = request.form['smtp_password']
        app.logger.debug('site_type: %s' % (site_type))
        app.logger.debug('source_host_id: %s' % (source_host_id))
        app.logger.debug('target_host_id: %s' % (target_host_id))
        app.logger.debug('table_prefix: %s' % (table_prefix))
        app.logger.debug('order_start_id: %s' % (order_start_id))
        app.logger.debug('smtp_host: %s' % (smtp_host))
        app.logger.debug('smtp_username: %s' % (smtp_username))
        app.logger.debug('smtp_password: %s' % (smtp_password))

        app.logger.debug('Query host info')
        source_host = Host.query.filter_by(id=source_host_id).first()
        target_host = Host.query.filter_by(id=target_host_id).first()

        app.logger.debug('Checking source host id')
        if not isinstance(source_host, Host):
            flash("Source Host Not Found!")
            return redirect(url_for('/task/clone_site/form'))
        app.logger.debug('Checking target host id')
        if not isinstance(target_host, Host):
            flash("Target Host Not Found!")
            return redirect(url_for('/task/clone_site/form'))

        app.logger.debug('Lanuching task.')
        params = {
            'logger': app.logger,
            'source_domain': source_host.domain,
            'source_ip': source_host.ip,
            'source_port': source_host.port,
            'source_password': source_host.pwd,
            'target_domain': target_host.domain,
            'target_ip': target_host.ip,
            'target_port': target_host.port,
            'target_password': target_host.pwd,
            'target_database_root_password': target_host.db_pwd,
            'order_start_id': order_start_id,
        }
        tasklog_params = {
            'web_type': site_type,
            'template': params['source_domain'],
            'target_host': params['target_ip'],
            'target_domain': params['target_domain'],
        }
        TaskLog(task_name='clone site', custom_data=tasklog_params).create()
        #cscart_workflow(**params)
        if site_type == 'cscart':
            params['table_prefix'] = 'cscart_'
            executor.submit(cscart_workflow, **params)
        elif site_type == 'magento':
            executor.submit(magento_workflow, **params)
        elif site_type == 'opencart':
            params['table_prefix'] = 'oc'
            executor.submit(opencart_workflow, **params)
        #executor.submit(task_clone_site_exec, source_host, target_host,
        #site_type, table_prefix, order_start_id, smtp_host,
        #smtp_username, smtp_password)

        flash("Clone Task Is Running In Background. Please Wait...")

        return redirect(url_for('task'))

    #def task_clone_site_exec(source_host: Host, target_host: Host, site_type,
    #table_prefix, order_start_id, smtp_host,
    #smtp_username, smtp_password):
    #from dress.tasks.tasks import CloneSiteTask
    #task = CloneSiteTask(source_host, target_host, site_type, table_prefix,
    #order_start_id, smtp_host, smtp_username,
    #smtp_password)
    #task.run()

    @app.route('/task/lnmpa_install/form')
    def task_lnmpa_install_form():
        target_hosts = Host.query.filter(
            Host.status != Status.query.filter_by(title=Status.SOURCE).first())

        return render_template('task_lnmpa_install_form.html',
                               target_hosts=target_hosts)

    @app.route('/task/lnmpa_install', methods=['POST'])
    def task_lnmpa_install():
        target_host_id = form.request('target_host_id')
        db_root_password = form.request('db_root_password')

        target_host = Host.query.filter_by(id=target_host_id).first()
        if not isinstance(target_host, Host):
            flash("Target Host Not Found!")
            return redirect(url_for('/task/clone_site/form'))

        params = {
            'db_root_password': db_root_password,
            'domain': target_host.domain,
        }
        tasklog_params = {
            'domain': params['domain'],
        }
        TaskLog(task_name='install lnmpa', custom_data=tasklog_params).create()

        lnmpa_workflow(params)
        #executor.submit(lnmpa_workflow, **params)

        flash("Lnmpa Installation Is Running In Background. Please Wait...")

        return redirect(url_for('task'))

    # test
    @app.route('/test/change_host_status')
    def test_change_host_status():
        h = Host.query.all()[0]
        print(h.status.title)
        h.updateStatus(Status.BUSINESS)
        print(h.status.title)
        return h.status.title

    @app.route('/test_flash')
    def test_flash():
        flash('This is flash message')
        return redirect(url_for('index'))

    @app.route('/test')
    def test_task():
        executor.submit(some_long_task1)
        executor.submit(some_long_task2, 'hello', 123)
        return 'launched!'

    def some_long_task1():
        from time import sleep
        print("Task #1 started!")
        sleep(10)
        print("Task #1 is done!")

    def some_long_task2(arg1, arg2):
        from time import sleep
        print("Task #2 started with args %s %s!" % (arg1, arg2))
        sleep(5)
        print("Task #2 is done!")

    return app
Exemplo n.º 13
0
def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    csrf = CSRFProtect()
    app.config.update(dict(SECRET_KEY=os.urandom(24) or 'riverrun'))

    csrf.init_app(app)
    '''
    app.config.from_mapping(
        SECRET_KEY='dev',
        DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
    )
    '''
    Bootstrap(app)
    nav = Nav()
    '''
    def get_db():
        db = getattr(g, '_database', None)
        if db is None:
            db = g._database = sqlite3.connect(DATABASE)
        return db

    @app.teardown_appcontext
    def close_connection(exception):
        db = getattr(g, '_database', None)
        if db is not None:
            db.close()
    '''

    # registers the "top" menubar

    nav.register_element(
        'top',
        Navbar(
            'Parking',
            View('Home', 'home'),
            View('Application', 'application'),
            Subgroup(
                'Admin',
                View('All Applications', 'view_applications'),
                View('Settings and Configuration', 'settings'),
                #Separator(),
                #Label('Discontinued Products'),
                #View('Wg10X', 'products', product='wg10x'),
            ),
        ))
    '''
    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass
    '''
    @app.route('/')
    def home():
        #cur = get_db().cursor()
        lot = Lot()
        return render_template('index.html', object=lot)

    @app.route('/application', methods=['GET', 'POST'])
    def application():
        complete = {}
        if request.method == 'POST':
            result = request.form

            for key, value in result.items():
                if key != 'csrf_token':
                    if key != 'submit':
                        complete[key] = value
            now = unicode(datetime.datetime.now())
            complete['timestamp'] = now

            #print application

            app_obj = Application(complete['full_name'])
            process_form_results(complete, app_obj)
            app_obj.id = complete['full_name']
            app_obj.grade = complete['grade']
            app_obj.multiply(app_obj.qualifier)
            app_obj.expo_bloom(app_obj.qualifier, app_obj.raw_score)
            #print application

            application = json.dumps(app_obj.__dict__)
            with open("data/output.json", "a") as record:
                record.write('\n\n' + application)

            return render_template('ack.html', result=complete, object=app_obj)
        else:
            form = ApplicationForm()
            return render_template('application_form.html',
                                   title="Application",
                                   form=form,
                                   wtf=wtf)

    @app.route('/receipt')
    def acknowledge():
        return render_template('ack.html')

    nav.init_app(app)

    @app.route('/admin/applications')
    def view_applications():
        with open('data/output.json') as data:
            records = data.read()
            records = records.split('\n\n')
            for record in records:
                record = record.strip()
                record = json.loads(record)

        return render_template('applications.html', records=records)

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

    return app
Exemplo n.º 14
0
from flask_nav import Nav
from flask_nav.elements import Navbar, View

from raven.contrib.flask import Sentry

# Local stuff
from app.config import Config
from app.parsers_manager import ParsersManager
from app.utils.utils import (setup_logging, files_in_dir, get_lock_status,
                             printable_time)

# init application
app = Flask(__name__)
Bootstrap(app)
NAV = Nav()
NAV.init_app(app)
CONFIG = Config()
setup_logging(CONFIG)
sentry = Sentry(app,
                logging=True,
                level=logging.WARNING,
                dsn=CONFIG.sentry_dns)


def check_auth(username, password, config):
    """This function is called to check if a username /
    password combination is valid.
    :param config:
    """
    return username == config.username and password == config.password
Exemplo n.º 15
0
def create_app():

    # instantiate the app
    app = Flask(__name__,
                template_folder='../client/templates',
                static_folder='../client/static')

    from cabotage.server.models.auth import User, Role
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)

    from cabotage.server.user.forms import (
        ExtendedConfirmRegisterForm,
        ExtendedLoginForm,
        ExtendedRegisterForm,
    )

    from flask_nav import Nav
    from flask_nav.elements import Navbar, View, Separator, Subgroup

    nav = Nav()

    anonymous_nav = Navbar(
        'Cabotage',
        View('Register', 'security.register'),
        View('Log In', 'security.login'),
    )
    logged_in_nav = Navbar(
        'Cabotage',
        Subgroup(
            'Orgs',
            View('All My Orgs', 'user.organizations'),
        ),
        Subgroup(
            'Projects',
            View('All My Projects', 'user.projects'),
        ),
        Subgroup(
            'Account',
            Separator(),
            View('Change Password', 'security.change_password'),
            View('Log Out', 'security.logout'),
        ),
    )
    nav.register_element('anonymous', anonymous_nav)
    nav.register_element('logged_in', logged_in_nav)

    # set config
    app_settings = os.getenv('APP_SETTINGS', 'cabotage.server.config.Config')
    app.config.from_object(app_settings)

    # set up extensions
    bcrypt.init_app(app)
    toolbar.init_app(app)
    bootstrap.init_app(app)
    security.init_app(
        app,
        user_datastore,
        confirm_register_form=ExtendedConfirmRegisterForm,
        register_form=ExtendedRegisterForm,
        login_form=ExtendedLoginForm,
    )
    vault_db_creds.init_app(app)
    db.init_app(app)
    mail.init_app(app)
    migrate.init_app(app, db)
    nav.init_app(app)
    humanize.init_app(app)
    consul.init_app(app)
    vault.init_app(app)
    kubernetes.init_app(app)
    config_writer.init_app(app, consul, vault)
    minio.init_app(app)
    celery.init_app(app)
    github_app.init_app(app)

    # register blueprints
    from cabotage.server.user.views import user_blueprint
    from cabotage.server.main.views import main_blueprint
    app.register_blueprint(user_blueprint)
    app.register_blueprint(main_blueprint)

    # error handlers
    @app.errorhandler(401)
    def unauthorized_page(error):
        return render_template('errors/401.html'), 401

    @app.errorhandler(403)
    def forbidden_page(error):
        return render_template('errors/403.html'), 403

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

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

    return app
Exemplo n.º 16
0
__author__ = """Mikael Fridh"""
__email__ = "*****@*****.**"
__version__ = "0.1.0"

from flask import Flask, render_template
from flask_bootstrap import Bootstrap

from flask_nav import Nav
from flask_nav.elements import Navbar, View

nav = Nav()

app = Flask(__name__)
from slack_status.errors import blueprint as errors
from slack_status.emojis import blueprint as emojis

app.register_blueprint(errors)
app.register_blueprint(emojis)

nav.init_app(app)
Bootstrap(app)


@nav.navigation()
def mynavbar():
    return Navbar("Fulhack Industries")


from slack_status import routes
Exemplo n.º 17
0
    def __init__(self, app):
        nav = Nav()

        # noinspection PyUnusedLocal,PyAbstractClass,PyMethodMayBeStatic,PyPep8Naming
        @nav.renderer('custom')
        class CustomRenderer(BootstrapRenderer):

            # External links now open in new tab
            def visit_LinkTab(self, node):
                item = tags.li()
                item.add(tags.a(node.text, href=node.get_url(), target="_blank"))

                return item

            def visit_LogIn(self, node):
                item = tags.li()
                inner = item.add(tags.a(href=node.get_url(), _class="nav-image"))
                inner.add(tags.img(src=url_for("static", filename="sso_login.png")))
                if node.active:
                    item['class'] = 'active'
                return item

            def visit_SeparatorAlign(self, node):
                return NotImplementedError

            def visit_Navbar(self, node):
                # create a navbar id that is somewhat fixed, but do not leak any
                # information about memory contents to the outside
                node_id = self.id or sha1(str(id(node)).encode()).hexdigest()

                root = tags.nav() if self.html5 else tags.div(role='navigation')
                root['class'] = 'navbar navbar-default'

                cont = root.add(tags.div(_class='container-fluid'))

                # collapse button
                header = cont.add(tags.div(_class='navbar-header'))
                btn = header.add(tags.button())
                btn['type'] = 'button'
                btn['class'] = 'navbar-toggle collapsed'
                btn['data-toggle'] = 'collapse'
                btn['data-target'] = '#' + node_id
                btn['aria-expanded'] = 'false'
                btn['aria-controls'] = 'navbar'

                btn.add(tags.span('Toggle navigation', _class='sr-only'))
                btn.add(tags.span(_class='icon-bar'))
                btn.add(tags.span(_class='icon-bar'))
                btn.add(tags.span(_class='icon-bar'))

                # title may also have a 'get_url()' method, in which case we render
                # a brand-link
                if node.title is not None:
                    if hasattr(node.title, 'get_url'):
                        header.add(tags.a(node.title.text, _class='navbar-brand',
                                          href=node.title.get_url()))
                    else:
                        header.add(tags.span(node.title, _class='navbar-brand'))

                bar = cont.add(tags.div(
                    _class='navbar-collapse collapse',
                    id=node_id,
                ))
                bar_list = bar.add(tags.ul(_class='nav navbar-nav'))
                bar_list_right = bar.add(tags.ul(_class='nav navbar-nav navbar-right'))

                to_right = False
                for item in node.items:
                    if isinstance(item, SeparatorAlign):
                        to_right = True
                        continue
                    if not to_right:
                        bar_list.add(self.visit(item))
                    else:
                        bar_list_right.add(self.visit(item))

                return root

        @nav.navigation('anon')
        def nav_anon():
            return Navbar('TiT', View('Home', 'home'),
                          View('Buyback Service', 'buyback.home'), View('JF Service', "jf.home"),
                          View('Recruitment', 'recruitment.home'),
                          SeparatorAlign(), View("Change Theme", "settings"), LogIn('Log In', 'auth.sso_redirect'))

        @nav.navigation('neut')
        def nav_neut():
            return Navbar('TiT', View('Home', 'home'), View('Account', "account.home"),
                          View('Buyback Service', 'buyback.home'), View('JF Service', "jf.home"),
                          View('Recruitment', 'recruitment.home'),
                          SeparatorAlign(), View("Change Theme", "settings"), View('Log Out', 'auth.log_out'))

        @nav.navigation('corporation')
        def nav_corp():
            items = Navigation.corp + Navigation.settings
            return Navbar(*items)

        @nav.navigation('alliance')
        def nav_alliance():
            items = Navigation.alliance + Navigation.settings
            return Navbar(*items)

        @nav.navigation('admin')
        def nav_admin():
            admin_elements = []
            role_elements = []
            market_service = False
            security = False
            for role in session.get("UI_Roles"):
                if role == "jf_admin":
                    admin_elements += [View('JF Routes', "jf.admin"), View('JF Stats', "jf.stats")]
                elif role == "user_admin":
                    admin_elements.append(View('User Roles', "admin.roles"))
                elif role == "jf_pilot":
                    role_elements.append(View('JF Service', "jf.pilot"))
                elif role == "buyback_admin":
                    admin_elements.append(View('Buyback Service', 'buyback.admin'))
                elif role in ["ordering_marketeer", "ordering_admin"] and not market_service:
                    role_elements.append(View('Market Service', 'ordering.admin'))
                    market_service = True
                elif role in ["security_officer", "recruiter"] and not security:
                    role_elements.append(View('Recruitment Apps', 'recruitment.applications'))
                    if role == "security_officer":
                        role_elements.append(View('Security Info', 'security.home'))
                        admin_elements.append(View('Recruitment Settings', 'recruitment.admin'))
                    security = True
                elif role == "recruiter" and not security:
                    role_elements.append(View('Recruitment Apps', 'recruitment.applications'))
            subs = []
            if role_elements:
                subs.append(Subgroup('Role Pages', *role_elements))
            if admin_elements:
                subs.append(Subgroup('Admin Pages', *admin_elements))
            if session["UI_Corporation"]:
                items = Navigation.corp + subs + Navigation.settings
            elif session["UI_Alliance"]:
                items = Navigation.alliance + subs + Navigation.settings
            else:
                return nav_neut()

            return Navbar(*items)

        nav.init_app(app)
Exemplo n.º 18
0
def create_app():
  app = Flask(__name__)
  Bootstrap(app)
  nav = Nav()
  
  nav.register_element('top', Navbar(
    View('Overview', 'overview'),
    Subgroup(
      'Groups',
        View('List Groups','list_group'),
        View('Add Group','add_group')
    ),
    Subgroup(
      'Servers',
        View('List Servers','list_server'),
        View('Add Server','add_server')
    ),
    View('Ban', 'index'),
    View('Users', 'index'),
  ))

  nav.init_app(app)

  # init varnish
  varnish = Varnish()

  # remove this please
  core = Core('192.168.99.100', 'varnishmon', 'root', '123.')

  # function for make response to charts
  def makeResponse(r):
    response = make_response(r)
    response.content_type = 'application/json'
    return response

  # index content
  @app.route('/')
  def index():
    return "ok"

  @app.route('/overview', methods=['GET', 'POST'])
  def overview():
    if request.method == 'GET':
      response = core.listGroup()
      servers = core.listServer(1)
      return render_template('overview.html', groups=response, servers=servers, group_id=1)
    else:
      response = core.listGroup()
      return redirect('/overview/' + request.form['group_id'])

   
  @app.route('/overview/<group_id>', methods=['GET'])
  def overview_select(group_id):
    group_list = core.listGroup()
    servers = core.listServer(group_id)
    return render_template('overview.html', groups=group_list, servers=servers, group_id=int(group_id))

  @app.route('/add_group', methods=['GET', 'POST'])
  def add_group():
    if request.method == 'GET':
      return render_template('addGroup.html')
    else:
      response = core.addGroup(request.form['name'])
      return response

  @app.route('/list_group')
  def list_group():
    response = core.listGroup()
    return render_template('listGroup.html', groups=response)

  @app.route('/add_server', methods=['GET', 'POST'])
  def add_server():
    if request.method == 'GET':
      response = core.listGroup()
      return render_template('addServer.html', groups=response)
    else:
      response = core.addServer(request.form['name'], request.form['ip'], request.form['port'], request.form['password'], request.form['group'])
      return response

  @app.route('/list_server')
  def list_server():
    response = core.listServer()
    return render_template('listServer.html', servers=response)


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

  #
  # response for charts data
  #
  @app.route('/live/hit/<group_id>')
  def hit(group_id):
    response = core.listServer(group_id)
    v =  varnish.only_hit_or_miss('hit', servers=response)

    return makeResponse(v)

  @app.route('/live/miss/<group_id>')
  def miss(group_id):
    response = core.listServer(group_id)
    v = varnish.only_hit_or_miss('miss', servers=response)
    return makeResponse(v)

  @app.route('/live/client_req/<group_id>')
  def client_req(group_id):
    response = core.listServer(group_id)
    v = varnish.client_req(servers=response)
    return makeResponse(v)
  
  @app.route('/live/health/<group_id>')
  def health(group_id):
    response = core.listServer(group_id)
    v = varnish.health(servers=response)
    return makeResponse(v)

  return app 
Exemplo n.º 19
0
def init_app_navbar(app):
    nav = Nav()
    nav.register_element('top', topbar)
    nav.init_app(app)
Exemplo n.º 20
-2
def create_app():
    fapp = Flask(__name__)
    fapp.config['SECRET_KEY'] = SECRET_KEY
    fapp.config['BOOTSTRAP_SERVE_LOCAL'] = BOOTSTRAP_SERVE_LOCAL

    lm = LoginManager()
    lm.init_app(fapp)
    lm.login_view = 'login'

    nav = Nav()
    nav.init_app(fapp)

    Bootstrap(fapp)
    register_renderer(fapp, 'myrenderer', Customrenderer)
    nav.register_element('top_nav', top_nav)
    return fapp, lm, nav