Ejemplo n.º 1
1
#setup navigation
nav = Nav()
nav.register_element('frontend_top', Navbar(
    View('Stocker', '.index'),
    Subgroup(
        'Rankings',
        View('Magic Formula Trailing', 'rank', strategy = 'magic_formula_trailing'),
        View('Magic Formula Future', 'rank', strategy = 'magic_formula_future'),
        View('EBITDA', 'rank', strategy = 'ebitda'),
        View('PE ratio trailing', 'rank', strategy = 'pe_ratio_ttm'),
        View('PE ratio future', 'rank', strategy = 'pe_ratio_ftm'),
        View('GARP ratio', 'rank', strategy = 'garp_ratio'),
        View('Return on Assets', 'rank', strategy = 'return_on_assets'),
        View('Return on Equity', 'rank', strategy = 'return_on_equity'),
        View('Dividend Yield', 'rank', strategy = 'DividendYield'),
        ),
    Subgroup(
        'Development',
        Link('Flask-Bootstrap', 'http://pythonhosted.org/Flask-Bootstrap'),
        Link('Flask-AppConfig', 'https://github.com/mbr/flask-appconfig'),
        Link('Flask-Debug', 'https://github.com/mbr/flask-debug'),
        Separator(),
        Text('Bootstrap'),
        Link('Getting started', 'http://getbootstrap.com/getting-started/'),
        Link('CSS', 'http://getbootstrap.com/css/'),
        Link('Components', 'http://getbootstrap.com/components/'),
        Link('Javascript', 'http://getbootstrap.com/javascript/'),
        Link('Customize', 'http://getbootstrap.com/customize/'),
    ),
))

Ejemplo n.º 2
0
# for production use: app.config.from_pyfile('config.py')
# make sure you do not commit secret key to public repo
app.config['SECRET_KEY'] = 'enter_secret_key_here'

# navigation bar
from flask_nav import Nav
from flask_nav.elements import Navbar, View, Link, Subgroup, Separator
nav = Nav()
nav.register_element(
    'top',
    Navbar(
        View('Iris Machine Learning App', 'index'),
        View('Plots', 'plots'),
        View('Dataframe', 'dataframe'),
        View('About', 'about'),
        View('Contact', 'contact'),
        Subgroup(
            'External Links',
            Link('University of Notre Dame', 'https://www.nd.edu'),
            Link('Northwestern University', 'https://www.northwestern.edu'),
            Separator(),
            Link('Google', 'https://www.google.com'),
        ),
    ))
nav.init_app(app)

# bootstrap css
from flask_bootstrap import Bootstrap
Bootstrap(app)

# wtforms
from forms import MyForm
Ejemplo n.º 3
0
def min_max_dates():
    dates = list(
        map(dir_date_to_datetime, get_dirs(app.config['SCANS_DATA_DIR'])))
    return min(dates), max(dates)


nav.register_element(
    'top',
    Navbar(
        View('Identity and Access Management',
             'service',
             service='Identity and Access Management'),
        View('Security Center', 'service', service='Security Center'),
        View('Storage Accounts', 'service', service='Storage Accounts'),
        View('SQL Servers', 'service', service='SQL Servers'),
        View('Logging and Monitoring',
             'service',
             service='Logging and Monitoring'),
        View('Networking', 'service', service='Networking'),
        View('Virtual Machines', 'service', service='Virtual Machines'),
        View('Other Security Considerations',
             'service',
             service='Other Security Considerations'),
    ))


def main(parser=None):
    """
    parser is a parsed argparse parser passed in from controller
    """
    if not parser:
Ejemplo n.º 4
0
# from models import Education, Experience

from dotenv import load_dotenv
load_dotenv()

app = Flask(__name__)
app.config.from_object(os.environ['APP_SETTINGS'])
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

nav = Nav(app)

nav.register_element(
    'my_navbar',
    Navbar('thenav', View('Resume', 'index'), View('Gallery', 'gallery'),
           View('Blog', 'blog'), View('Contact', 'contact')))


@app.route('/')
def index():
    title = 'resume'
    body = 'resume'
    return render_template('base.html', title=title, body=body)


@app.route('/gallery')
def gallery():
    title = 'gallery'
    body = 'gallery'
    return render_template('base.html', title=title, body=body)
Ejemplo n.º 5
0
def configure_nav(app):
    nav = Nav()
    nav.register_element('base', basebar)
    nav.register_element('ctx', ctxbar)
    nav.init_app(app)
Ejemplo n.º 6
0
EMAIL_REGEX = re.compile(r'[\w]+@[.\w]+')

# Create app
app = Flask(__name__)
app.config.from_object(__name__)

# Flask Mail
mail = Mail(app)

# Flask Bootstrap
bootstrap = Bootstrap(app)

# Naviagtion bar
nav = Nav(app)
nav.register_element('navigation',
                     Navbar(View('Home', 'front'),
                            View('Contact', 'contact'),
                            View('CV', 'cv')))


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


@app.route('/contact')
def contact(error=None):
    return render_template('contact.html', error=error)


@app.route('/cv')
def cv():
Ejemplo n.º 7
0
class zhuanhuanqi(BaseConverter):
    def __init__(self,url_map,*items):
        super(zhuanhuanqi,self).__init__(url_map)
        self.regex=items[0]

app = Flask(__name__)
app.url_map.converters['urlzhengze']=zhuanhuanqi
app.config.from_object('config')
db=SQLAlchemy(app)

Bootstrap(app)
nav = Nav()

nav.register_element('top',Navbar('Flask',
                                  View('主页','index'),
                                  View('用户','user'),
                                  View('服务','service')
                                  ))

nav.init_app(app)



@app.route('/index')
def index():
    user_agent=request.headers.get('User-Agent')
    return '<h5 style=color:yellowgreen>%s</h5>'% user_agent ,206


@app.route('/service')
def service():
Ejemplo n.º 8
0
from flask_login import current_user

nav = Nav()


def frontend_nav():
    navbar = Navbar('',
                    View("Instabattle", 'main.index'),
                    View("Gallery", 'gallery.show'), )
    navbar.items = list(navbar.items)  # FIXME should be fixed in nav 0.6

    if current_user.is_authenticated:
        navbar.items.append(View("Profile",
                                 'main.user',
                                 username=current_user.username))
        navbar.items.append(View("Log Out", 'auth.logout'))
        navbar.items.append(View("Upload", 'main.upload'))
        navbar.items.append(View("Challenges", 'battle.challenges'))
    else:
        navbar.items.append(View("Log In", 'auth.login'))
        navbar.items.append(View("Register", 'auth.register'))

    navbar.items.append(View("Battles", 'battle.battles'))

    return navbar


frontend = Blueprint('frontend', __name__)

nav.register_element('frontend_top', frontend_nav)
Ejemplo n.º 9
0
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_nav import Nav
from flask_nav.elements import Navbar, View, Link, Subgroup, Separator, Text

import config as _config
from requests_code.database import db
from requests_code.views import generate, run, code


nav = Nav()

nav.register_element('top', Navbar(
    View('Home', 'code.home'),
    View('Generate Code', 'generate.index'),
    View('OJ', 'run.run'),
    View('List', 'code.list'),
    Link('使用说明', 'http://www.baidu.com/', target='_blank'),
))


def create_app(config=None):
    app = Flask(__name__)
    if config is not None:
        app.config.from_pyfile(config)
    else:
        app.config.from_object(_config)
    app.base_dir = app.config['BASE_DIR']

    app.jinja_env.autoescape = False
Ejemplo n.º 10
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
Ejemplo n.º 11
0
from flask import Flask, render_template
from flask_bootstrap import Bootstrap
from flask_nav import Nav
from flask_nav.elements import Navbar, View, Subgroup, Link

from dgcastle import dgcastle

app = Flask(__name__)
Bootstrap(app)

nav = Nav()
nav.register_element(
    'top',
    Navbar(View('DGCastle', '.home'),
           Subgroup('Import', View('Challonge', '.challonge'))))
nav.init_app(app)

DGCastle = dgcastle.DGCastle()


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


@app.route("/challonge")
@app.route("/challonge/<tournament>")
def challonge(tournament=None):
    if tournament:
        # Need to make a call to DGCastle to import this tournament information
        info = DGCastle.challonge_import(tournament)
Ejemplo n.º 12
0
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

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

# To keep things clean, we keep our Flask-Nav instance in here. We will define
# frontend-specific navbars in the respective frontend, but it is also possible
# to put share navigational items in here.

nav = Nav()

nav.register_element(
    "frontend_top",
    Navbar(
        View("Search By Name", ".find_by_name"),
        Subgroup(
            "Docs",
            Link("PIGS WIKI", "https://github.com/virtdevninja/steel_pigs/wiki"),
            Link("Making PIGS Plugins", "https://github.com/virtdevninja/steel_pigs/wiki"),
        ),
    ),
)
Ejemplo n.º 13
0
from flask_bootstrap import __version__ as FLASK_BOOTSTRAP_VERSION
from flask_nav import Nav
from flask_nav.elements import Link, Navbar, Separator, Subgroup, Text, View

nav = Nav()

nav.register_element('frontend_top', Navbar(
    View('Flask-Bootstrap', '.index'),
    View('Home', '.index'),
    View('Forms Example', '.example_form'),
    View('Debug-Info', 'debug.debug_root'),
    Subgroup(
        'Docs',
        Link('Flask-Bootstrap', 'http://pythonhosted.org/Flask-Bootstrap'),
        Link('Flask-AppConfig', 'https://github.com/mbr/flask-appconfig'),
        Link('Flask-Debug', 'https://github.com/mbr/flask-debug'),
        Separator(),
        Text('Bootstrap'),
        Link('Getting started', 'http://getbootstrap.com/getting-started/'),
        Link('CSS', 'http://getbootstrap.com/css/'),
        Link('Components', 'http://getbootstrap.com/components/'),
        Link('Javascript', 'http://getbootstrap.com/javascript/'),
        Link('Customize', 'http://getbootstrap.com/customize/'),
    ),
    Text('Using Flask-Bootstrap {}'.format(FLASK_BOOTSTRAP_VERSION)),
))
Ejemplo n.º 14
0
from flask_nav import Nav
from flask_nav.elements import Navbar, View, Subgroup, Link, Text, Separator

nav = Nav()

nav.register_element('top', Navbar(
    'JBToDo',
    View('Task list', 'index'),
    View('New task', 'new')
))
Ejemplo n.º 15
0
from flask import Flask, request, render_template
from flask_bootstrap import Bootstrap
from flask_nav import Nav
from flask_nav.elements import *

import random

app = Flask(__name__)
Bootstrap(app)

nav = Nav(app)

# registers the "top" menubar
nav.register_element(
    'top', Navbar(View('Plus', 'my_form'), View('Minus', 'my_form_minus')))


@app.route('/')
def my_form():
    a = random.randrange(0, 9)
    b = random.randrange(0, 49)
    return render_template('plus.html', a=a, b=b)


@app.route('/', methods=['POST'])
def my_form_post():
    svar = request.form['svar']
    svar_int = int(svar)
    a = request.form.get('a')
    b = request.form.get('b')
    summa = int(a) + int(b)
Ejemplo n.º 16
0
from flask import Flask, render_template, jsonify, request, redirect
from flask_nav import Nav
from flask_nav.elements import Navbar, View
from pymongo import MongoClient

app = Flask(__name__)
nav = Nav(app)
app.config['DEBUG'] = True

client = MongoClient()
db = client.python_flask_pymongo
collection = db.operators

nav.register_element(
    'my_navbar',
    Navbar('the_nav', View('Home Page', 'home_page'),
           View('Loops Page', 'loops_page'),
           View('Operators Page', 'operators_page')))


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


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


@app.route('/operators', methods=['GET', 'POST'])
Ejemplo n.º 17
0
        self.regex = items[0]


basedir = path.abspath(path.dirname(__file__))

# manager = Manager(app)
babel = Babel()
bootstrap = Bootstrap()
nav = Nav()
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'

nav.register_element(
    'top',
    Navbar('微信管理', View(u'首页', 'main.index'), View(u'关于', 'main.about'),
           View(u'服务', 'main.services'), View(u'项目', 'main.projects')))


def create_app(config_name='default'):
    app = Flask(__name__)
    app.url_map.converters['regex'] = RegexConverter
    app.config.from_object(config[config_name])
    #app.config.from_pyfile('babel.cfg')
    #app.secret_key = 'hard to guess string'
    # app.config['BABEL_DEFAULT_LOCALE']='zh'
    # app.config['SQLALCHEMY_DATABASE_URI'] = \
    #     'sqlite:///' + path.join(basedir, 'data.sqlite')
    # app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True

    #nav.init_app(app)
Ejemplo n.º 18
0
        super(RegexConverter, self).__init__(url_map)
        self.regex = items[0]


app = Flask(__name__)
app.url_map.converters['regex'] = RegexConverter
Bootstrap(app)
nav = Nav()

app.config.from_pyfile('config')

manager = Manager(app)

nav.register_element('top', Navbar(u'Flask入门',
                                   View(u'主页', 'index'),
                                   View(u'关于', 'about'),
                                   View(u'服务', 'services'),
                                   View(u'项目', 'projects'),
                                   ))
nav.init_app(app)


@app.route('/')
def index():
    return render_template('index.html',
                           title='Welcome')


@app.route('/services')
def services():
    return 'Service'
Ejemplo n.º 19
0
from flask_nav.elements import *

from load_data import loadcsv
import trypy
from neo4j_main import maintest
app = Flask(__name__)

nav = Nav()
nav.register_element(
    'top',
    Navbar(
        u'Flask入门',
        View(u'查询', 'index'),
        Subgroup(
            u'结果',
            View(u'犯罪人员基本信息统计', 'result1'),
            # Separator(),
            View(u'毒资支付方式统计', 'result2'),
            View(u'毒品交易方式统计', 'result3'),
            View(u'贩毒联系方式统计', 'result4'),
            View(u'新数据导入', 'add1'),
            # View(u'结果','success'),
            # ),
        )))
nav.init_app(app)


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

Ejemplo n.º 20
0
from flask import Blueprint, render_template, send_from_directory
from flask_nav import Nav
from flask_nav.elements import Navbar, View

web = Blueprint('web', __name__, template_folder="templates",
                static_folder="static")


nav = Nav()
nav.register_element("web_top", Navbar(
    View("martinke.mp", ".index"),
    View("CV", ".static", filename="mk_resume-2016-03-09.pdf")
))


@web.route("/", methods=["GET"])
def index():
    return render_template('index.j2',
                           title="Martin Kemp - DevOps Specialist")
Ejemplo n.º 21
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
Ejemplo n.º 22
0
from flask import Flask, render_template
from flask_nav import Nav
from flask_nav.elements import *

nav = Nav()

# registers the "top" menubar
nav.register_element(
    'top',
    Navbar(
        View('Widgits, Inc.', 'index'),
        View('Our Mission', 'about'),
        Subgroup('Products',
                 View('Wg240-Series',
                      'products',
                      product='wg240'),
                 View('Wg250-Series',
                      'products',
                      product='wg250'),
                 Separator(),
                 Text('Discontinued Products'),
                 View('Wg10X',
                      'products',
                      product='wg10x'), ),
        Link('Tech Support', 'http://techsupport.invalid/widgits_inc'), ))


def create_app(configfile=None):
    app = Flask(__name__)
    nav.init_app(app)

    # not good style, but like to keep our examples short
Ejemplo n.º 23
0
from flask import Flask
from flask_nav import Nav
from flask_nav.elements import Navbar, View, Link
from flask_bootstrap import Bootstrap
topbar = Navbar(
    View("Home", "home"),
    Link("Source Code", r"http://www.github.com/d4d3vd4v3/tweet-analysis"))
nav = Nav()
nav.register_element("topbar", topbar)


def create_app():
    app = Flask(__name__)
    from .blueprints import bp
    app.register_blueprint(bp)
    Bootstrap(app)
    nav.init_app(app)
    return app
Ejemplo n.º 24
0
def get_git_revision_short_hash():
    return subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'])

app = Flask(__name__)
app.config.from_pyfile('settings.py')
app.config.update(dict(
    DATABASE=os.path.join(app.root_path, app.config['DATABASE_NAME']),
))

# We're adding a navbar as well through flask-navbar. In our example, the
# navbar has an usual amount of Link-Elements, more commonly you will have a
# lot more View instances.
nav = Nav()
nav.register_element('frontend_top', Navbar(
    View('Music on Blocks', 'index'),
    View('Tags', 'tags'),
    View('Settings', 'settings'),
    View('Debug', 'debug'),
    Text('Current GIT Hash: {}'.format(get_git_revision_short_hash())), ))

# webapp endpoint
Bootstrap(app)
nav.init_app(app)

# Because we're security-conscious developers, we also hard-code disabling
# the CDN support (this might become a default in later versions):
app.config['BOOTSTRAP_SERVE_LOCAL'] = True


raspberryPi = None
mySonosController = None
lastTag = None
Ejemplo n.º 25
0
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_nav import Nav
import logging

from navbar import navbar

app = Flask("SPE-IoT-Energy", template_folder="templates")
app.config.from_pyfile('config.cfg')
logging.basicConfig(level=logging.DEBUG)
Bootstrap(app)

nav = Nav(app)

nav.register_element('navbar', navbar)

from views import *

def main():
    app.run(host=app.config['HOSTNAME'], port=int(app.config['PORT']))
        
if __name__ == "__main__":
    main()
Ejemplo n.º 26
0
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_nav import Nav
from flask_nav.elements import *
from config import config

FC = None
DP = None

nav = Nav()
nav.register_element('top', Navbar(u'文本分类',
                                   View(u'分类', 'app.index'),
                                   View(u'关于', 'app.info'),
                                   )
                     )
bootstrap = Bootstrap()


def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name]) # 可以直接把对象里面的配置数据转换到app.config里面
    config[config_name].init_app(app)

    bootstrap.init_app(app)
    nav.init_app(app)
    #mail.init_app(app)
    #moment.init_app(app)
    #db.init_app(app)
    # 路由和其他处理程序定义
    from www import view
    app.register_blueprint(view.bp)
Ejemplo n.º 27
0
from flask_nav import Nav
from flask_nav.elements import Navbar, View
from flask_paginate import Pagination, get_page_parameter
from flask_bootstrap import Bootstrap
import config
import re

app = Flask(__name__)
app.config.from_object(config)
db = SQLAlchemy(app)
Bootstrap(app)
nav = Nav()
nav.register_element(
    'top',
    Navbar(u'题库', View(u"搜索", "index"), View(u"所有", "all"),
           View(u"常识判断", "types", mtype=u"a"),
           View(u"言语理解与表达", "types", mtype=u"b"),
           View(u"数量关系", "types", mtype=u"c"),
           View(u"判断推理", "types", mtype=u"d"),
           View(u"资料分析", "types", mtype=u"e")))

nav.init_app(app)


class Questions(db.Model):
    __tablename__ = 'sQuestions'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    Means = db.Column(db.Text)
    Title = db.Column(db.String(2500))
    Answers = db.Column(db.String(2500))
    CAnswers = db.Column(db.String(2500))
    Statistics = db.Column(db.String(2500))
    def visit_SuperGroup(self, node):
        li = tags.li(_id=sanitise_for_css(node.title.text), _class="parent")
        if node.title.active:
            li['class'] = 'parent active'
        a = li.add(tags.a(node.title.text, href=node.title.get_url()))
        ul = tags.ul(*[self.visit(item) for item in node.items])
        ul2 = li.add(ul)
        return li

    def visit_Separator(self, node):
        return tags.li('---')

    def visit_Subgroup(self, node):
        li = tags.li(node.title, _class="nested")
        ul2 = tags.ul(*[self.visit(item) for item in node.items])
        lis2 = li.add(ul2)
        return li

    def visit_RawTag(self, node):
        return raw(node.content)


nav.register_element('mob_in', mobile_first_in)
nav.register_element('mob_out', mobile_first_out)


def initialise_nav(app):
    register_renderer(app, 'just_li', JustLiRenderer)
    nav.init_app(app)
Ejemplo n.º 29
0
def init():
    from CGRdb import Loader
    from datetime import datetime
    from flask import Flask
    from flask_bootstrap import Bootstrap
    from flask_login import LoginManager
    from flask_misaka import Misaka
    from flask_nav import Nav, register_renderer
    from flask_resize import Resize
    from misaka import HTML_ESCAPE
    from os.path import join
    from pony.orm import sql_debug
    from .API import api_bp
    from .bootstrap import top_nav, CustomBootstrapRenderer, CustomMisakaRenderer
    from .config import (PORTAL_NON_ROOT, SECRET_KEY, DEBUG, LAB_NAME,
                         RESIZE_URL, UPLOAD_PATH, IMAGES_ROOT, MAX_UPLOAD_SIZE,
                         YANDEX_METRIKA)
    from .logins import load_user
    from .models import db, User
    from .views import view_bp

    if DEBUG:
        sql_debug(True)
        db.bind('sqlite', 'database.sqlite')
        db.generate_mapping(create_tables=True)
    else:
        from .config import DB_PASS, DB_HOST, DB_USER, DB_NAME
        db.bind('postgres',
                user=DB_USER,
                password=DB_PASS,
                host=DB_HOST,
                database=DB_NAME)
        db.generate_mapping()

    Loader.load_schemas(user_entity=User)

    app = Flask(__name__)

    app.config['DEBUG'] = DEBUG
    app.config['SECRET_KEY'] = SECRET_KEY
    app.config['BOOTSTRAP_SERVE_LOCAL'] = DEBUG
    app.config['ERROR_404_HELP'] = False
    app.config['RESIZE_URL'] = RESIZE_URL
    app.config['RESIZE_ROOT'] = IMAGES_ROOT
    app.config['MAX_CONTENT_LENGTH'] = MAX_UPLOAD_SIZE

    app.jinja_env.globals.update(year=datetime.utcnow,
                                 laboratory=LAB_NAME,
                                 yandex=YANDEX_METRIKA)

    Resize(app)

    register_renderer(app, 'myrenderer', CustomBootstrapRenderer)
    nav = Nav(app)
    nav.register_element('top_nav', top_nav)
    Bootstrap(app)

    Misaka(app,
           renderer=CustomMisakaRenderer(flags=0 | HTML_ESCAPE),
           tables=True,
           underline=True,
           math=True,
           strikethrough=True,
           superscript=True,
           footnotes=True,
           smartypants=False)

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

    app.register_blueprint(api_bp,
                           url_prefix=join('/', PORTAL_NON_ROOT, 'api'))
    app.register_blueprint(
        view_bp,
        url_prefix=join('/', PORTAL_NON_ROOT) if PORTAL_NON_ROOT else None)

    return app
Ejemplo n.º 30
0
from flask import Flask, jsonify, render_template, flash, redirect, url_for
from flask_bootstrap import Bootstrap
from flask_nav import Nav
from flask_nav.elements import *
from flask_socketio import SocketIO, emit

nav = Nav()

topbar = Navbar(
    '',
    View('Home', 'index'),
    View('Your Account', 'index'),
)

nav.register_element('top', topbar)

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

nav.init_app(app)
Bootstrap(app)

server = "localhost:9999"
mpd_folder = "/srv/public/Nutzer/"
playlist_folder = "David_Bauer/temp_playlist/"


def cmd_run(cmd):
    p = Popen(cmd, shell=True, stdout=PIPE)
Ejemplo n.º 31
0
from .forms import LoginForm, RegisterForm, AccountForm
from .models import User, Product, Order

from flask_nav import Nav
from .nav import init_custom_nav_renderer, anon, auth, admin

from .shop import view_products, get_product_dict, check_exist_product, update_amount_product, get_cost_cart, get_money_by_username, check_order, update_cost_cart, remove_product_cart, delete_all_products, fill_all_products

from .account import get_user_info

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

nav = Nav(app)
nav.register_element('navbarAnon', anon)
nav.register_element('navbarAuth', auth)
nav.register_element('navbarAdmin', admin)
init_custom_nav_renderer(app)


class AdminViewModels(ModelView):
    def is_accessible(self):
        if current_user.is_authenticated:
            if current_user.username == 'jayse' or \
                current_user.username == 'admin':
                return True
        else:
            return False

    def inaccessible_callback(self, name, **kwargs):
Ejemplo n.º 32
0
from flask import Flask, render_template
from flask_nav import Nav
from flask_nav.elements import Navbar, Subgroup, View, Link, Text, Separator

app = Flask(__name__)
nav = Nav(app)

nav.register_element('wine_navbar', Navbar('thenav',
                                           View('Home Page', 'index')))


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


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

app = Flask(__name__)

nav.init_app(app)
Ejemplo n.º 33
0
@app.route('/inspiring')
def joinus():
    return render_template('helping.html')


def events():
    return render_template('helping.html')


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


nav = Nav()
nav.register_element(
    'top',
    Navbar(
        View("Pyladies Antananarivo", 'home'),
        View("About", 'home'),
        View("Pourquoi?", 'joinus'),
        View("Activités", 'joinus'),
        View("Partenaires", 'joinus'),
    ))

nav.init_app(app)
if __name__ == '__main__':
    #app.run(debug=False, host='192.168.1.3', port=7000)
    app.run(debug=False)
Ejemplo n.º 34
0
    if not logged_in and request.path != '/login':
        entries.append(View('Login', 'login'))
    if app.config['CALL_OPEN'] and logged_in and request.path != '/submit':
        entries.append(View('Submit a Proposal', 'submit'))
    if logged_in and request.path != '/registration_update':
        entries.append(View('Registration Update', 'registration_update'))
    if app.config[
            'CALL_OPEN'] and logged_in and request.path != '/my_proposals':
        entries.append(View('My Proposals', 'my_proposals'))
    if app.config[
            'REVIEWING_ALLOWED'] and logged_in and request.path != '/review_list':
        user = User.query.filter_by(email=session['email']).first()
        if user and user.role == Role.reviewer:
            entries.append(View('Review Proposals', 'review_list'))
    if logged_in:
        entries.append(View('Logout', 'logout'))
    return Navbar('', *entries)


nav = Nav()
nav.register_element('top_nav', top_nav)
nav.init_app(app)

# Only now bring in the views since they likely rely on some of the setup above.
# Ignore the violations of PEP-8.
import accuconf_cfp.views.index
import accuconf_cfp.views.register
import accuconf_cfp.views.login
import accuconf_cfp.views.submit
import accuconf_cfp.views.review
Ejemplo n.º 35
0
##需要全局设置一个csrf
app.config['SECRET_KEY'] = 'hard to guess string'

bootstrap = Bootstrap(app)

manager = Manager(app)

nav = Nav()

nav.register_element(
    'top',
    Navbar(
        u'flask入门',
        View(u'你好', 'test_templates'),
        View(u'栏目测试', 'test_base'),
        View(u'测试表单 ', 'test_form'),
        View(u'点击注册测试 ', 'register_form'),
        View(u'查看用户 ', 'user'),
        View(u'真正的注册用户 ', 'register'),
    ))

##初始化一个nav
nav.init_app(app)

##编辑一下链接数据库的信息
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(
    basedir, 'data.sqlite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)
Ejemplo n.º 36
0
# frontend-specific navbars in the respective frontend, but it is also possible
# to put share navigational items in here.

nav = Nav()
#icono = img(src='static/img/Escudo1.png')
nombre_app = "Gobierno y calidad de datos"

# Barra de navegación
nav.register_element(
    'frontend_top',
    Navbar(
        # icono,
        nombre_app,
        View('Inicio', 'frontend.index'),
        View('Proyectos', 'frontend.proyectos_form'),
        Subgroup(
            'Documentos',
            Link('Flask-Bootstrap', 'http://pythonhosted.org/Flask-Bootstrap'),
            Link('Flask-AppConfig', 'https://github.com/mbr/flask-appconfig'),
            Link('Flask-Debug', 'https://github.com/mbr/flask-debug'),
            Separator(),
            Text('Bootstrap'),
            Link('Getting started',
                 'http://getbootstrap.com/getting-started/'),
            Link('CSS', 'http://getbootstrap.com/css/'),
            Link('Components', 'http://getbootstrap.com/components/'),
            Link('Javascript', 'http://getbootstrap.com/javascript/'),
            Link('Customize', 'http://getbootstrap.com/customize/'),
        ),
        Text('Using Flask-Bootstrap {}'.format(FLASK_BOOTSTRAP_VERSION)),
    ))
Ejemplo n.º 37
0
# -*- coding: utf-8 -*-
from __future__ import absolute_import

from flask import Flask
from flask_bootstrap import Bootstrap
from flask_nav import Nav
from flask_nav.elements import Navbar, View, Link

from requests_code import config as _config
from requests_code.views import bp


nav = Nav()

nav.register_element('top', Navbar(
    View('Home', 'home.index'),
    Link('使用说明', 'http://www.baidu.com/'),
))


def create_app(config=None):
    app = Flask(__name__)
    if config is not None:
        app.config.from_pyfile(config)
    else:
        app.config.from_object(_config)

    app.jinja_env.autoescape = False

    Bootstrap(app)
    nav.init_app(app)
    app.register_blueprint(bp)
Ejemplo n.º 38
0
nav.init_app(app)

#je déclare une barre de navigation contenant les routes
mynavbar = Navbar(
        'mysite',
        View('Home', 'index'),
        View('1er Exemple', 'hello'),
        View('template Exemple', 'hello2'),
        View('BootStrap Exemple', 'hello3'),
        View('BootStrap et Nav Exemple', 'hello4'),
        
    )


#je donne au plug-in ma barre de navigation
nav.register_element('top', mynavbar)


#crée la route web de la racine du site 
#et la lie à la fonction index
@app.route("/")
def index():
    return render_template('index.html')

#on crée la nouvelle route et on la lie à fonction Hello
@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
    #if name == None : 
        #Si le nom n'est pas dans l'url, je tente de l'extraire depuis la requête 
    #    name = request.args.get('name',None)
Ejemplo n.º 39
0
try:
    from accuconf_config import Config
except ImportError:
    from models.configuration import Config

year = 2018

app = Flask(__name__)
app.config.from_object(Config)
app.secret_key = app.config['SECRET_KEY']
app.logger.info(app.url_map)

db = SQLAlchemy(app)

nav = Nav()
nav.register_element('top_nav', Navbar(''))
nav.init_app(app)

# The shared packages use accuconf as the name of the application package.
# must set this up. Don't use a proper DI for now, just use this (possibly
# fragile) hack.
#
# NB Some of these imports rely on accuconf.app and accuconf.db so they must
# be included after the definition of those symbols.
sys.modules['accuconf'] = sys.modules['accuconf_api']
# Not apparently used but has to be loaded, and here is good.
from models.user import User
from models.proposal import Presenter, Proposal


@app.route('/')
Ejemplo n.º 40
0
app.config.from_object('config')

# Register Flask-BCrypt.
bcrypt = Bcrypt(app)

# Register Flask-Bootstrap.
Bootstrap(app)

# Register Flask-CLI
FlaskCLI(app)

# Register Flask-HTMLmin
HTMLMIN(app)

# Register Flask-Nav
nav = Nav(app)
from app.navigation import navbar
nav.register_element('navbar', navbar)
# nav.init_app(app)

# NOTE: Moved to app.models
# Register Flask-SQLAlchemy
# db = SQLAlchemy(app)

# Extend app.jinja_env
from app.jinja_ext import extend_app
extend_app(app)

# Import views.
from app import views
Ejemplo n.º 41
0
from flask import Flask, render_template
from flask_nav import Nav
from flask_nav.elements import *

nav = Nav()

# registers the "top" menubar
nav.register_element(
    'top',
    Navbar(
        View('Widgits, Inc.', 'index'),
        View('Our Mission', 'about'),
        Subgroup(
            'Products',
            View('Wg240-Series', 'products', product='wg240'),
            View('Wg250-Series', 'products', product='wg250'),
            Separator(),
            Text('Discontinued Products'),
            View('Wg10X', 'products', product='wg10x'),
        ),
        Link('Tech Support', 'http://techsupport.invalid/widgits_inc'),
    ))


def create_app(configfile=None):
    app = Flask(__name__)
    nav.init_app(app)

    # not good style, but like to keep our examples short
    @app.route('/')
    def index():
Ejemplo n.º 42
0
    # /opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/matplotlib/mpl-data/fonts/ttf/Vera.ttf
    # Deleting fix and ax seems to have no effect ...
    # del fig, ax

    return send_file(img, mimetype='image/png')


topbar = Navbar('',
    View('About', 'view_about'),
    View('Data', 'view_data'),
    View('Events', 'view_events'),
    View('IRFs', 'view_irfs'),
)


nav = Nav()
nav.register_element('top', topbar)
nav.init_app(app)

# def run_data_browser(data_dir):
#     """Run a data browser web app.
#     """
#
#     log.info('data_dir = {}'.format(data_dir))
#     # http://flask.pocoo.org/docs/0.10/api/#flask.Flask.add_url_rule
#     app.add_url_rule('/', view_func=view_about, methods=['GET', 'POST'])
#     app.add_url_rule('/obs', view_func=view_obs, methods=['GET', 'POST'])
#     app.add_url_rule('/events', view_func=view_events, methods=['GET', 'POST'])
#     app.add_url_rule('/irfs', view_func=view_irfs, methods=['GET', 'POST'])
#     app.add_url_rule('/image/<int:obs_id>', view_func=view_image)
Ejemplo n.º 43
0
def get_nav():
    nav = Nav()
    nav.register_element('mynavbar', mynavbar)
    nav.register_element('secnavbar', secnavbar)
    return nav
Ejemplo n.º 44
0
app.logger.info("loading model CND ...")
cnd = load_model('VGG16_cats_and_dogs.h5')
cnd._make_predict_function()
app.logger.info("... model loaded")

# # Load LSTM IMDB sentiment classification model
# global imdb
# app.logger.info("loading model IMDB ...")
# imdb = load_model('imdb.h5')
# imdb._make_predict_function()
# app.logger.info("... model loaded")

# navigation bar (navbar) registration
nav.register_element(
    'navbar',
    Navbar('Demos:', View('Home', 'index'), View('CNN', 'cnn'),
           View('Sentiment', 'sentiment'), View('Summarize', 'summarize'),
           View('Similarity', 'similarity'), View('ChatBot', 'chatbot')))

APP_ROOT = os.path.dirname(os.path.abspath(__file__))


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


def preprocess_image(image, target_size):
    app.logger.info("CNN API: preprocessing image")
    if image.mode != "RGB":
        app.logger.info("CNN API: converting image to RGB")
Ejemplo n.º 45
0
from flask_uploads import configure_uploads
from .consts import MENU, receipts, uploaded_files
from .renderer import (ePrihlaskaNavRenderer, ExtendedNavbar, UserGreeting,
                       LogInLogOut)
import locale

import logging
from logging.handlers import SMTPHandler
from logging import Formatter

nav = Nav()
items = [View(*x) for x in MENU]
right_items = [UserGreeting(), LogInLogOut()]
nav.register_element(
    'top',
    ExtendedNavbar(title=items[0], items=items[1:], right_items=right_items))

csrf = CSRFProtect()
app = Flask(__name__)
app.config.from_object('config')
Bootstrap(app)
nav.init_app(app)
register_renderer(app, 'eprihlaska_nav_renderer', ePrihlaskaNavRenderer)

csrf.init_app(app)
babel = Babel(app)
app.config['BABEL_DEFAULT_LOCALE'] = 'sk_SK'
locale.setlocale(locale.LC_ALL, 'sk_SK.utf8')

configure_uploads(app, receipts)
Ejemplo n.º 46
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 
Ejemplo n.º 47
0
Archivo: nav.py Proyecto: jleaniz/bdsa
nav.register_element('frontend_top', Navbar(
    View('BDSA', 'main.index'),
    Subgroup(
        'Dashboards',
        Link('Firewall stats', '/dashboard/fw'),
        Link('Patch Mgmt.', '/dashboard/pm')
    ),
    Subgroup(
        'Analytics',
        Text('VPN'),
        Separator(),
        Link('Remote IPs per user', '/vpn/user'),
        Link('Unusual activity', '/vpn/activity'),
        Link('Remote IP GeoMap', '/vpn/geomap'),
        Separator(),
        Text('Proxy'),
        Separator(),
        Link('Endpoint malware search', '/proxy/endpoint'),
        Link('Outdated browsers', '/proxy/endpoint/outdated'),
        Link('High data transfers', '/proxy/top/transfers'),
        Link('Most visited domains', '/proxy/top/visited'),
        Link('Most visited malware domains', '/proxy/top/malware'),
        Link('Most visited malware domains (OTX/C2)', '/proxy/top/malware/feeds'),
        Link('Uncommon User-Agents', '/proxy/uncommon/useragent'),
        Separator(),
        Text('Firewall'),
        Separator(),
        Link('Most denied Dst Ports', '/firewall/port/stats'),
        Link('Most denied IP stats', '/firewall/ip/stats'),
        Link('Malicious connections (OTX/C2)', '/firewall/malware/conns'),
        Link('Top 50 denied flows', '/firewall/top/talkers'),
        Separator(),
        Text('Bash'),
        Separator(),
        Link('Keyword search', '/bash/keyword'),
        Link('User activity', '/bash/user'),
    ),
    Link('Search', '/search'),
    Subgroup(
        'Spark',
        Link('Clear cache', '/spark/clearcache'),
        Link('Cancel jobs', '/spark/canceljobs'),
    ),
    View('Logout', 'login.logout'),
))
Ejemplo n.º 48
0
'''
Sets up navigation in the dashboard 
'''

from flask_nav import Nav
from flask_nav.elements import *

# To keep things clean, we keep our Flask-Nav instance in here. We will define
# frontend-specific navbars in the respective frontend, but it is also possible
# to put share navigational items in here.


nav = Nav()

nav.register_element('top', Navbar(
         Link('Home', dest='/'),
         )
    )
Ejemplo n.º 49
-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