Esempio n. 1
1
MAIL_SERVER = 'smtp.virgin.net'
MAIL_DEFAULT_SENDER = '*****@*****.**'
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)
Esempio n. 2
0
def init():
    from datetime import datetime
    from flask import Flask
    from flask_bootstrap import Bootstrap
    from flask_nav import Nav, register_renderer
    from pathlib import PurePosixPath
    from .bootstrap import top_nav, CustomBootstrapRenderer
    from .config import PORTAL_NON_ROOT, SECRET_KEY, DEBUG, LAB_NAME, MAX_UPLOAD_SIZE, YANDEX_METRIKA
    from .views import view_bp

    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['MAX_CONTENT_LENGTH'] = MAX_UPLOAD_SIZE

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

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

    app_url = PurePosixPath('/') / (PORTAL_NON_ROOT or '')
    app.register_blueprint(
        view_bp, url_prefix=app_url.as_posix() if PORTAL_NON_ROOT else None)

    return app
Esempio n. 3
0
def init_app():
    from .config import (PORTAL_NON_ROOT, SECRET_KEY, DEBUG, LAB_NAME, RESIZE_URL, IMAGES_PATH, MAX_UPLOAD_SIZE,
                         YANDEX_METRIKA, VK_ENABLE, JOBS_ENABLE, CGRDB_ENABLE, VIEW_ENABLE)
    from .logins import load_user

    app = Flask(__name__)

    app.config['DEBUG'] = DEBUG
    app.config['SECRET_KEY'] = SECRET_KEY
    app.config['ERROR_404_HELP'] = False

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

    app_url = PurePosixPath('/') / (PORTAL_NON_ROOT or '')

    if VIEW_ENABLE:
        from flask_bootstrap import Bootstrap
        from flask_misaka import Misaka
        from flask_nav import Nav, register_renderer
        from flask_resize import Resize
        from misaka import HTML_ESCAPE
        from .views import view_bp
        from .views.bootstrap import top_nav, CustomBootstrapRenderer, CustomMisakaRenderer

        app.config['BOOTSTRAP_SERVE_LOCAL'] = DEBUG
        app.config['RESIZE_URL'] = RESIZE_URL
        app.config['RESIZE_ROOT'] = IMAGES_PATH
        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, autolink=True,
               underline=True, math=True, strikethrough=True, superscript=True, footnotes=True)

        app.register_blueprint(view_bp, url_prefix=app_url.as_posix() if PORTAL_NON_ROOT else None)

    if JOBS_ENABLE:
        from .API import load_jobs
        app.register_blueprint(load_jobs(), url_prefix=(app_url / 'api' / 'jobs').as_posix())
    if CGRDB_ENABLE:
        from .API import load_cgrdb
        app.register_blueprint(load_cgrdb(), url_prefix=(app_url / 'api' / 'db').as_posix())
    if VK_ENABLE:
        from .vk import vk_bp
        app.register_blueprint(vk_bp, url_prefix=(app_url / 'api' / 'vk').as_posix())

    return app
Esempio n. 4
0
def register_nav(app):
    nav = Nav()

    @nav.navigation()
    def dmeetup_navbar():
        items = list()
        items.append(View('Home', 'index'))

        return Navbar('D-Meetup', *items)

    nav.init_app(app)
Esempio n. 5
0
def flask_startup():
    app = Flask(__name__)
    nav = Nav(app)

    @nav.navigation()
    def navigate():
        return navigation_header()

    nav.navigation(navigate())

    app.secret_key = 'super duper secret key'
    app.config.from_object('config.FlaskConfig')

    Bootstrap(app)

    app.register_blueprint(frontend)

    AppConfig(app)

    nav.init_app(app)
    nav.renderer(navigation_header())

    port = os.getenv("VCAP_APP_PORT", default=8000)

    CourseCache.wait_for_access()
    app.run(host="0.0.0.0", port=int(port))
Esempio n. 6
0
    def setUp(self):
        app = Flask(__name__)
        self.app = app
        CSRFProtect(app)
        Bootstrap(app)
        nav = Nav(app)

        app.secret_key = 'DUMMY'

        @app.route('/')
        def index():
            if current_user.is_authenticated:
                return 'OK'
            else:
                return redirect(url_for('commons.login'))

        @nav.navigation()
        def mynavbar():
            """Menu da aplicação."""
            items = [View('Home', 'index')]
            return Navbar('teste', *items)

        app.testing = True
        self.client = app.test_client()
        self.db = MongoClient(host=MONGODB_URI).unit_test
        login.configure(app)
        login.DBUser.dbsession = self.db
        login.DBUser.add('ajna', 'ajna')
Esempio n. 7
0
def register_nav(app):
    nav = Nav()

    @nav.navigation()
    def opalnavbar():
        items = list()
        items.append(View('Home', 'index'))
        if oidc.user_loggedin:
            # items.append(View('Client', 'client.index'))
            if oidc.user_getfield("sub") == "90342.ASDFJWFA":
                items.append(View("Admin", "admin.index"))
            items.append(View('Logout', 'logout'))
        else:
            items.append(View('Login', 'login'))

        return Navbar('OPAL', *items)
    nav.init_app(app)
Esempio n. 8
0
def create_app(env_config):
    app = Flask(__name__)
    app.config.from_object(config[env_config])

    bootstrap = Bootstrap()
    nav = Nav()

    nav.register_element(
        "navbar",
        Navbar(
            "Falsk入门",
            View("首页", "index"),
            View("文章添加", "user_blue_api.add_article"),
            View("文章查看", "article_blue_api.get_article_list"),
            View("读者列表", "user_blue_api.get_user_list"),
            View("用户注册", "user_blue_api.register_user"),
        ))
    from flask_app.api_v1.index.views import init_views

    nav.init_app(app)
    db.init_app(app)
    bootstrap.init_app(app)
    init_views(app)
    register_route(app)
    session.init_app(app)

    return app
Esempio n. 9
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    #register blueprint
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    # nav
    nav = Nav()
    nav.register_element(
        'top',
        Navbar(
            u'flaskDemo',
            View(u'主页', 'main.hello_world'),
            View(u'关于', 'main.hello_world'),
            Subgroup(
                u'项目',
                View(u'项目一', 'main.hello_world'),
                Separator(),
                View(u'项目二', 'main.hello_world2'),
            ),
        ))
    nav.init_app(app)
    # bootstrap init
    bootstrap.init_app(app)

    return app
Esempio n. 10
0
def create_app(config_class=Production):
    """Cria app básica e vincula todos os blueprints e módulos/extensões."""
    app = Flask(__name__)
    app.logger.info('Criando app')
    Bootstrap(app)
    nav = Nav(app)
    csrf = CSRFProtect(app)
    app.secret_key = config_class.SECRET
    app.config['SECRET_KEY'] = config_class.SECRET
    app.config['sql'] = config_class.sql
    db_session = scoped_session(sessionmaker(autocommit=False,
                                             autoflush=False,
                                             bind=config_class.sql))
    app.config['db_session'] = db_session

    app.register_blueprint(k9views)
    app.register_blueprint(k9api)
    csrf.exempt(k9api)
    admin_app(app, db_session)

    app.logger.info('Configurando login...')
    login.configure(app)
    DBUser.alchemy_class = config_class.alchemy_class
    DBUser.dbsession = db_session

    app.logger.info('Configurando / e redirects')

    @nav.navigation()
    def mynavbar():
        """Menu da aplicação."""
        items = [View('Home', 'index'),
                 View('Dog', 'k9views.dog_id'),
                 View('Pesquisa Dog', 'k9views.pesquisa_dog')]
        if current_user.is_authenticated:
            items.append(View('Sair', 'commons.logout'))
        return Navbar('teste', *items)

    @app.route('/')
    def index():  # pragma: no cover
        if current_user.is_authenticated:
            return render_template('index.html')
        else:
            return redirect(url_for('commons.login'))

    @app.teardown_appcontext
    def shutdown_session(exception=None):
        db_session = app.config.get('db_session')
        if db_session:
            db_session.remove()

    return app
Esempio n. 11
0
def add_nav(app):
    """ called by pygameweb.app.add_views_front
    """
    nav = Nav()

    @nav.navigation()
    def mynavbar():
        """ Every time a page is loaded we create the navigation.

        We cache the navbar in the templates.
        """
        return make_nav(current_session)

    nav.init_app(app)
Esempio n. 12
0
def create_app(config_class=Production):
    """Cria app básica e vincula todos os blueprints e módulos/extensões."""
    app = Flask(__name__)
    app.logger.info('Criando app')
    Bootstrap(app)
    nav = Nav(app)
    csrf = CSRFProtect(app)
    # app.config['SERVER_NAME'] = 'ajna.api'
    app.secret_key = config_class.SECRET
    app.config['SECRET_KEY'] = config_class.SECRET
    app.config['mongodb'] = config_class.db
    app.config['sql'] = config_class.sql
    app.register_blueprint(ajna_api)
    csrf.exempt(ajna_api)
    app.register_blueprint(mercanteapi)
    csrf.exempt(mercanteapi)
    app.logger.info('Configurando swagger-ui...')
    swaggerui_blueprint = get_swaggerui_blueprint(SWAGGER_URL, API_URL)
    app.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL)

    @app.route('/docs/openapi.yaml')
    def return_yaml():
        return send_file('openapi.yaml')

    app.logger.info('Configurando api login...')
    api = api_login.configure(app)
    csrf.exempt(api)

    app.logger.info('Configurando login...')
    login.configure(app)
    DBUser.dbsession = config_class.db

    app.logger.info('Configurando / e redirects')

    @nav.navigation()
    def mynavbar():
        """Menu da aplicação."""
        items = [View('Home', 'index')]
        if current_user.is_authenticated:
            items.append(View('Sair', 'commons.logout'))
        return Navbar('teste', *items)

    @app.route('/')
    def index():
        if current_user.is_authenticated:
            return render_template('index.html')
        else:
            return redirect(url_for('commons.login'))

    return app
Esempio n. 13
0
def create_nav(app):
    """
    Register navbar data, for calling in the html templates
    """
    nav = Nav(app)

    @nav.navigation()
    def basic_navbar():
        return Navbar(
            View('Dochap', 'index'),
            View('Upload', 'upload'),
            View('About', 'about'),
        )

    return nav
Esempio n. 14
0
def create_app(config_name='default'):
    app = Flask(__name__)

    # 初始化正则表达式路由规则类,就是在 app 里面添加 url_map
    app.url_map.converters['regex'] = RegexConverter

    # 即时更新网页
    app.debug = True

    # 关于表单提交的 csrf 跨站保护的设置
    app.config.from_pyfile('config.txt')

    # SQLite 数据库配置
    absdir = os.path.abspath(os.path.dirname(__file__))
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(absdir, 'data.sqlite')
    app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    # 测试用的 调用 config.py 文件进行配置
    # app.config.from_object(config[config_name])

    # 引入美化导航栏
    nav = Nav()

    nav.register_element('top', Navbar('FlaskTest',
                                       View('主页', 'main.hello_world'),
                                       View('关于', 'main.about'),
                                       View('登录', 'auth.login'),
                                       View('上传', 'upload'),
                                       ))
    nav.init_app(app)
    db.init_app(app)
    bootstrap.init_app(app)
    login_manager.init_app(app)
    pagedown.init_app(app)
    Gravatar(app, size=64)

    init_views(app)
    from . import auth as auth_blueprint
    from . import main as main_blueprint
    app.register_blueprint(auth_blueprint.auth)
    app.register_blueprint(main_blueprint.main)

    return app
Esempio n. 15
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)),
))
Esempio n. 16
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)
Esempio n. 17
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, 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']
Esempio n. 18
0
#!/usr/bin/python
# -*- coding: utf

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

nav = Nav()

nav.register_element(
    "top_menu",
    Navbar(View(u"Home", ".index"), View(u"Login", ".login"),
           View(u"Add measurement log", ".addMeasurementLog"),
           View(u"Add sample", ".addSample"),
           View(u"Add structure", ".addStructure"),
           View(u"Add project", ".addProject"),
           View(u"Add sample", ".addSample")))
Esempio n. 19
0
def create_app(config_class=Production):
    """Cria app básica e vincula todos os blueprints e módulos/extensões."""
    app = Flask(__name__)
    app.logger.info('Criando app')
    Bootstrap(app)
    nav = Nav(app)
    csrf = CSRFProtect(app)
    # app.config['SERVER_NAME'] = 'ajna.api'
    app.secret_key = config_class.SECRET
    app.config['SECRET_KEY'] = config_class.SECRET
    app.config['mongodb'] = config_class.db
    app.config['mongodb_risco'] = config_class.db_risco
    app.config['sql'] = config_class.sql
    db_session = scoped_session(
        sessionmaker(autocommit=False, autoflush=False, bind=config_class.sql))
    app.config['db_session'] = db_session
    app.register_blueprint(ajna_api)
    csrf.exempt(ajna_api)
    app.register_blueprint(bhadrasanaapi)
    csrf.exempt(bhadrasanaapi)
    app.register_blueprint(virasanaapi)
    csrf.exempt(virasanaapi)
    app.register_blueprint(mercanteapi)
    csrf.exempt(mercanteapi)
    app.register_blueprint(recintosapi)
    csrf.exempt(recintosapi)
    app.register_blueprint(cadastrosapi)
    csrf.exempt(cadastrosapi)
    app.logger.info('Configurando swagger-ui...')
    swaggerui_blueprint = get_swaggerui_blueprint(SWAGGER_URL, API_URL)
    app.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL)

    @app.route('/docs/openapi.yaml')
    def return_yaml():  # pragma: no cover
        return send_file('openapi.yaml')

    app.logger.info('Configurando api login...')
    api = api_login.configure(app)
    csrf.exempt(api)

    app.logger.info('Configurando login...')
    login.configure(app)
    DBUser.dbsession = config_class.db

    app.logger.info('Configurando / e redirects')

    @nav.navigation()
    def mynavbar():
        """Menu da aplicação."""
        items = [View('Home', 'index')]
        if current_user.is_authenticated:
            items.append(View('Sair', 'commons.logout'))
        return Navbar('teste', *items)

    @app.route('/')
    def index():  # pragma: no cover
        if current_user.is_authenticated:
            return render_template('index.html')
        else:
            return redirect(url_for('commons.login'))

    @app.teardown_appcontext
    def shutdown_session(exception=None):
        db_session = app.config.get('db_session')
        if db_session:
            db_session.remove()

    return app
import helper
from helper import *
from flask import Flask, request, Response, render_template, redirect
from flask_nav import Nav
from flask_nav.elements import *
import json
import os.path
import requests
from pprint import pprint
import time
from dotenv import load_dotenv
load_dotenv()

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

nav.register_element(
    'top',
    Navbar('navigation', View('Accueil', 'index'),
           View('Liste des commentaires', 'comments')))


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


@app.route('/comment/new', methods=['POST'])
def add_comment():
    # Get comment from the POST body
    if request.method == "POST":
Esempio n. 21
0
from flask import render_template, request
from flask_nav import Nav
from flask_nav.elements import *

from app import app, db, basic_auth, pages
from app.models import *

import datetime, sys, json


#
#   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
#
Esempio n. 22
0
def get_git_revision_hash():
    return subprocess.check_output(['git', 'rev-parse', 'HEAD'])

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
Esempio n. 23
0
from flask import Blueprint
from flask_nav import Nav
from flask_nav.elements import Navbar, View
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__)
Esempio n. 24
0
from os import path
from flask_bootstrap import Bootstrap
from flask_nav import Nav
from flask_nav.elements import *


class RegexConverter(BaseConverter):
    def __init__(self, url_map, *items):
        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('/')
Esempio n. 25
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"),
        ),
    ),
)
Esempio n. 26
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)
Esempio n. 27
0
File: nav.py Progetto: jleaniz/bdsa
# BDSA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with BDSA.  If not, see <http://www.gnu.org/licenses/>.
#

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

from flask_nav import Nav

nav = Nav()

# 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.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(),
Esempio n. 28
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')
))
Esempio n. 29
0
import sys
import os
from flask import Flask, render_template, redirect, url_for, request
from flask_nav import Nav
from flask_nav.elements import Navbar, Subgroup, View, Link, Text, Separator
import database.database as db
import time
# import serial
#from PIL import Image

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

# picFolder = os.path.join('static', 'db_img')
# app.config['UPLOAD_FOLDER'] = picFolder

nav.register_element(
    'my_navbar',
    Navbar('thenav', View('Home', 'home'), View('Add', 'add'),
           View('Remove', 'remove'), View('Return', 'ret'),
           View('Take', 'take')))
database = []
clothes_option = []

global_clothes_information = []

class_lookup = [
    "Anorak", "Blazer", "Blouse", "Bomber", "Button-Down", "Caftan", "Capris",
    "Cardigan", "Chinos", "Coat, Coverup", "Culottes", "Cutoffs", "Dress",
    "Flannel", "Gauchos", "Halter", "Henley", "Hoodie", "Jacket", "Jeans",
    "Jeggings", "Jersey", "Jodhurs", "Joggers", "Jumpsuit", "Kaftan", "Kimono",
Esempio n. 30
0
from flask_bootstrap import Bootstrap
from flask_nav import Nav
from flask_nav.elements import Navbar, View, Subgroup, Link


SECRET_KEY = 'aula de BCD - string aleatória'


app = Flask(__name__)
app.secret_key = 'SECRET_KEY'

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///urna-python.sqlite'
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




class Pessoa(db.Model):
    __tablename__       = 'Pessoa'
    nomePessoa          = db.Column(db.String(45), nullable=False)
    loginPessoa         = db.Column(db.String(45), primary_key=True, nullable=False)
    senhaPessoa         = db.Column(db.String(45), nullable=False)
    adminPessoa             = db.Column(db.Boolean, nullable=False)
    eleicoes = db.relationship('Eleicao', backref='Pessoa')


    def __init__(self, **kwargs):
Esempio n. 31
0
        "field": "attention",
        "title": "attention",
        "sortable": True,
    },
    {
        "field": "uneven",
        "title": "uneven",
        "sortable": True,
    }
]


app = Flask(__name__)
Bootstrap(app)
Dropzone(app)
nav=Nav()
nav.register_element('top',Navbar(u'ISPM Accelerator',
                                    View(u'Home','index'),
                                    Subgroup(u'Service',
                                             View(u'RRIC Shareholding Rule Recon','shareholding_rule_recon'),

                                             Separator(),
                                             View(u'FCMO Monthly Report Automation', 'index'),
                                    ),
))

nav.init_app(app)


@app.route('/shareholding_rule_recon_uploads', methods=['GET', 'POST'])
def shareholding_rule_recon_uploads():
Esempio n. 32
0
from flask import Flask, render_template, url_for, jsonify, request
from flask_nav import Nav
from flask_nav.elements import *
import translate, sentiment, synthesize

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False

nav = Nav()

nav.register_element(
    'top',
    Navbar(
        View('Home.', 'index'),
        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'),
        View('About', 'about')))

# 3. 初始化 app
nav.init_app(app)


@app.route('/')
def index():
    return render_template('index.html')
Esempio n. 33
0
ALLOWED_EXTENSIONS = set(['txt', 'docx', 'pdf', 'odt'])
topbar = Navbar('',
    Text('Extra Eyes'),
    View('About', 'about'),
    View('Home', 'intro'),
    View('Upload', 'upload_file'),
    View('Usage', 'usage'),
    Link('Style Checks','http://proselint.com/checks/'),
    Subgroup('Resources',
             Link('Lard', 'http://proftgreene.pbworks.com/w/file/fetch/50167777/Richard%20Lanhams%20Paramedic%20Method%20of%20Revision.pdf'),
             Link('Readability', 'http://www.analyzemywriting.com/readability_indices.html'),
             Link('Revision Strategies', 'http://greyfiti.wikidot.com/sdg:gmeth-ref-guidelines-substantive-revision')
             ),
)

nav = Nav()
nav.register_element('top', topbar)
app = Flask(__name__)
Bootstrap(app)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['DEBUG'] = True
nav.init_app(app)






def allowed_file(filename):
    """Make sure filetype has allowed extension."""
    return '.' in filename and \
Esempio n. 34
0
from flask_nav.elements import Navbar, View
from flask_sqlalchemy import SQLAlchemy
from flask_nav import Nav
from flask_login import LoginManager

from config import config
from flask_bootstrap import Bootstrap

login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'main.login'
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
nav = Nav()

topbar = Navbar('',
    View('Home', 'main.index'),
)   

nav.register_element('top', topbar)


def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])#这才真的把config类里的配置写入app
    config[config_name].init_app(app)
    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
Esempio n. 35
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")
Esempio n. 36
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)
Esempio 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)
Esempio n. 38
0
from flask_nav import Nav
from flask_nav.elements import Navbar, View, Subgroup, Link, Text, Separator

from flask_bootstrap import __version__ as FLASK_BOOTSTRAP_VERSION

# 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()

# Menu / navbar
nav.register_element(
    'frontend_top',
    Navbar(
        View('Home', 'frontend.index'),
        Link('GitHub', 'https://github.com'),
        Subgroup(
            'Tropo',
            Link('My Tropo Apps', 'https://www.tropo.com/applications'),
            Link('My Tropo Logs', 'https://www.tropo.com/mylogs'),
            Link('Python Module',
                 'https://github.com/cisco-sre/ciscotropowebapi'),
            Link(
                'SparkLog4Tropo',
                'https://gist.github.com/ObjectIsAdvantag/b73db0cffcedb1152a2d6669cb3d27b0'
            ),
            Link('WebAPI Docs', 'https://www.tropo.com/docs/webapi'),
            Link('Forums',
                 'https://support.tropo.com/hc/en-us/community/topics'),
            Link('IRC Chat', 'https://www.tropo.com/help/irc-chat/'),
Esempio n. 39
0
from flask_nav.elements import *

from flask.ext.sqlalchemy import SQLAlchemy

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
Esempio n. 40
0
    def create_app(self):
        topbar = Navbar(
            'snapcastr',
            View('Home', 'base'),
            View('Clients', 'basep', page='clients'),
            View('Groups', 'basep', page='groups'),
            View('Streams', 'basep', page='streams'),
            View('Zones', 'basep', page='zones'),
        )

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

        # create app
        app = Flask(__name__)
        nav.init_app(app)
        Bootstrap(app)

        @app.route('/')
        def base():
            return redirect('/page/base')

        @app.route('/page/<string:page>', methods=['GET', 'POST'])
        def basep(page):
            snapserver = self.create_snapserver()
            # process POST data
            if (request.method == 'POST'):
                data = request.form.to_dict(flat=False)
                if (page == 'clients'):
                    for hf, slider in zip(data['hf'], data['slider']):
                        gg = snapserver.client(hf).set_volume(int(slider))
                        self.loop.run_until_complete(gg)
                if (page == 'groups'):
                    data = request.form.to_dict(flat=False)
                    for gid, sid in zip(data['hf'], data['select']):
                        grp = snapserver.group(gid)
                        gg = None
                        if sid == '0':
                            gg = grp.set_muted(True)
                        else:
                            if grp.muted:
                                gg = grp.set_muted(False)
                                self.loop.run_until_complete(gg)
                            gg = grp.set_stream(sid)
                        self.loop.run_until_complete(gg)
                if (page == 'zones'):
                    data = request.form.to_dict(flat=False)
                    for cid, gid in zip(data['hf'], data['select']):
                        gg = snapserver.group(gid).add_client(cid)
                        self.loop.run_until_complete(gg)

            # generate content
            if (page == 'clients'):
                forms = []
                for client in snapserver.clients:
                    form = volumeSliderForm(csrf_enabled=False)
                    form.slider.default = client.volume
                    form.process()
                    if client.friendly_name:
                        form.name.data = client.friendly_name
                    else:
                        form.name.data = client.identifier
                    form.hf.data = client.identifier
                    form.connected = client.connected
                    forms.append(form)
                return render_template('clients.html', page=page, forms=forms)
            elif (page == 'groups'):
                forms = []
                clients = {
                    client.identifier: client
                    for client in snapserver.clients
                }
                for group in snapserver.groups:
                    form = streamSelectForm(csrf_enabled=False)
                    form.select.choices = [
                        (stream.identifier,
                         (stream.friendly_name if stream.friendly_name else
                          stream.identifier) + " : " + stream.status)
                        for stream in snapserver.streams
                    ]
                    form.select.choices.append(("0", "Mute"))
                    form.select.default = "0" if group.muted else group.stream
                    form.process()
                    if (group.friendly_name):
                        form.name.data = group.friendly_name
                    else:
                        form.name.data = group.identifier
                    form.clients = [
                        (client.friendly_name if client.friendly_name else
                         client.identifier, client.connected) for client in
                        [clients[gclient] for gclient in group.clients]
                    ]
                    form.hf.data = group.identifier
                    forms.append(form)
                return render_template('groups.html', page=page, forms=forms)
            elif (page == 'streams'):
                return render_template('streams.html',
                                       page=page,
                                       streams=snapserver.streams)
            elif (page == 'zones'):
                forms = []
                for client in snapserver.clients:
                    form = assignForm(csrf_enabled=False)
                    form.select.choices = [
                        (group.identifier, group.friendly_name
                         if group.friendly_name else group.identifier)
                        for group in snapserver.groups
                    ]
                    form.select.default = client.group.identifier
                    form.process()
                    form.hf.data = client.identifier
                    if client.friendly_name:
                        form.name.data = client.friendly_name
                    else:
                        form.name.data = client.identifier
                    form.connected = client.connected
                    forms.append(form)
                return render_template('zones.html', page=page, forms=forms)
            else:
                version = snapserver.version
                num_clients = len(snapserver.clients)
                num_groups = len(snapserver.groups)
                num_streams = len(snapserver.streams)
                return render_template('base.html',
                                       version=version,
                                       num_clients=num_clients,
                                       num_groups=num_groups,
                                       num_streams=num_streams)

        return app
Esempio n. 41
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
Esempio n. 42
0
# Apply styling
Bootstrap(app)

# Login Manager
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"


@login_manager.user_loader
def fair_load_user(user_id):
    return load_user(user_id)


# Connect mail
mail = Mail(app)

# Setup navbar
nav = Nav()
nav.init_app(app)
import fair.nav
import fair.views

app.register_blueprint(fair_blueprint)
# Turn of the default endpoint
app.register_blueprint(projects_blueprint)

# Onetime authentication reset token salt
app.config["ONETIME_TOKEN_SALT"] = os.urandom(24)
Esempio n. 43
0
from flask_wtf import Form, RecaptchaField                                      
from wtforms import TextField, ValidationError, SubmitField, Form, validators              
from wtforms.validators import Required, Email


#form class setup
class SignupForm(Form):
    name = TextField(u'Your name', [validators.required()])
    password = TextField(u'Your favorite password', [validators.required()])
    email = TextField(u'Your email address', [validators.required()])
    submit = SubmitField(u'Signup')


#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(
Esempio n. 44
0
        user = User.query.filter_by(username=form.username.data).first()
        if not user or not user.check_password(form.password.data):
            flash('Username or password is incorrect.', 'danger')
            return render_template('login.html', form=form)
        login_user(user)
        return redirect(url_for('homepage'))
    return render_template('login.html', form=form)


@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('homepage'))


nav = Nav(app)


@nav.navigation('mysite_navbar')
def create_navbar():
    home_view = View('Home', 'homepage')
    login_view = View('Login', 'login')
    logout_view = View('Logout', 'logout')
    posts_view = View('Posts', 'posts')
    register_view = View('Register', 'register')
    about_me_view = View('About Me', 'about_me')
    class_schedule_view = View('Class Schedule', 'class_schedule')
    top_ten_songs_view = View('Top Ten Songs', 'top_ten_songs')
    misc_subgroup = Subgroup('Misc', about_me_view, class_schedule_view,
                             top_ten_songs_view)
    if current_user.is_authenticated:
Esempio n. 45
0
"""
Register the top menu for the frontend.
"""

from flask_nav import Nav
from flask_nav.elements import (Navbar, View, Link)

nav = Nav()
nav.register_element(
    'frontend_top',
    Navbar(
        View('Home', 'frontend_blueprint.index'),
        View('Processors', 'processors_blueprint.processors'),
        View('Workflows', 'workflows_blueprint.workflows'),
        View('Tasks', 'tasks_blueprint.tasks'),
        View('Compare', 'compare_blueprint.compare'),
        Link('API', dest='/api'),
        Link('Queue Backend', dest='/flower/'),
    ))
Esempio n. 46
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='/'),
         )
    )
Esempio n. 47
0
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_frozen import relative_url_for
from flask_nav import Nav
from flask_nav.elements import Navbar, View
from flask_sqlalchemy import SQLAlchemy

from generator.utils import ObjectEncoder

nav = Nav()
bootstrap = Bootstrap()
db = SQLAlchemy()


def create_app(config_dict=None):
    from generator.blueprints import main

    app = Flask("Bobiverse visualisations")
    app.config["FREEZER_DESTINATION"] = "docs"
    app.config["FREEZER_REMOVE_EXTRA_FILES"] = True
    app.config["FREEZER_RELATIVE_URLS"] = True
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///bobiverse.db"
    # app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite://"
    app.config["SQLALCHEMY_ECHO"] = True  # for debugging db problems
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    app.config["JSONIFY_PRETTYPRINT_REGULAR"] = True
    app.json_encoder = ObjectEncoder

    if config_dict is not None:
        app.config.from_mapping(config_dict)
Esempio n. 48
0
# -*- coding: utf-8 -*-

from flask import Flask, render_template
from flask_nav.elements import *
from flask_nav import Nav

import json
import pandas as pd
import pygal

nav = Nav()

nav.register_element('top', Navbar(
    View('Home.', 'index'),
    View('Table', 'table'),
    View('Graph', 'graph'),
    ))


df = pd.read_csv('d:/thinkquant/Data/2016-2016/A.csv', header=0, index_col=0, parse_dates=True)
df['datetime'] = df.index
data = df.iloc[:100].to_dict('records')


app = Flask(__name__)

@app.route('/')
def index():
    """ render svg graph """
    return 'Hello! Go to /table/ or /graph/.'
Esempio n. 49
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 
Esempio n. 50
0
from flask import Flask, render_template, request
# from firebase import Firebase

from flask_wtf import FlaskForm
from wtforms import StringField, SelectField, SubmitField
from wtforms.validators import DataRequired

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

app = Flask(__name__)
nav = Nav(app)
# Config = {
#   apiKey: "AIzaSyBvMBbXcJGyptkPjVu_c6s1obmA97SXEOE",
#   authDomain: "huzzahplay.firebaseapp.com",
#   databaseURL: "https://huzzahplay.firebaseio.com",
#   projectId: "huzzahplay",
#   storageBucket: "huzzahplay.appspot.com",
#   messagingSenderId: "843161759149",
#   appId: "1:843161759149:web:60cdd3bb2df7ababffc524",
#   measurementId: "G-63902Y2BQB"
# };

# firebase = Firebase(config)

nav.register_element(
    'my_navbar',
    Navbar(
        'thenav',
        Text('HazzahPlay'),
        Separator(),
Esempio n. 51
-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