Esempio n. 1
0
 def _deb():
     deb = flask.Blueprint("deb", __name__)
     AutoIndex(deb, browse_root=path.join(self.app_repo_config.artifacts_directory, 'deb'))
     self.register_blueprint(deb, url_prefix="/deb")
Esempio n. 2
0
 def _ova_updates():
     ova = flask.Blueprint("ova", __name__)
     AutoIndex(ova, browse_root=path.join(self.app_repo_config.artifacts_directory, 'ova', 'updates'))
     self.register_blueprint(ova, url_prefix="/ova")
Esempio n. 3
0
                                             spec, request.json)

    return jsonify({'jobguid': processing_id})


@app.route('/results/<workflow_id>')
@app.route('/results/<workflow_id>/<path:path>')
@cern_oauth.login_required
def results(workflow_id, path="."):
    basepath = wflowapi.resultdir(workflow_id)
    basepath = basepath.split(os.environ['YADAGE_RESULTBASE'],
                              1)[-1].strip('/')
    return redirect(url_for('autoindex', path=os.path.join(basepath, path)))


idx = AutoIndex(app, os.environ['YADAGE_RESULTBASE'], add_url_rules=False)


@app.route('/resultfiles')
@app.route('/resultfiles/<path:path>')
@cern_oauth.login_required
def autoindex(path='.'):
    return idx.render_autoindex(path)


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


@app.route('/examples')
Esempio n. 4
0
def create_app(debug=True,
               enable_profiler=False,
               profiler_quiet=False,
               enable_timepro=False):
    """
    :param debug: whether to configure app for debug
    :param enable_profiler: enable flask profiler, causes function to return ProfilerMiddleware rather than Flask object which can be started by run_simple
    :param profiler_quiet: when profiler enabled sets whether profiler output echoed to stdout
    """
    app = Flask("iiab")
    app.url_map.strict_slashes = False
    app.use_x_sendfile = config().getboolean('WEBAPP', 'use_x_sendfile')
    app.secret_key = '1785132b4fd244a2a1ce6ae3f1d978ac'

    # Configuration items
    if debug:
        app.debug = True
        app.config['DEBUG'] = True
        app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0

    base_prefix = config().get('WEBAPP', 'base_prefix')

    blueprints = [
        (top_views.blueprint, base_prefix),
        (search_views.blueprint, base_prefix),
        (gutenberg.gutenberg, base_prefix + "books"),
        (map_views.blueprint, base_prefix + "maps"),
        (video_views.blueprint, base_prefix + "video"),
        (wikipedia_views.blueprint, base_prefix + "wikipedia"),
        (zim_views.blueprint, base_prefix + "zim"),
        (gutenberg_content_views.blueprint, base_prefix + "books"),
        (settings_views.blueprint, base_prefix + "settings"),
    ]
    for blueprint, prefix in blueprints:
        app.register_blueprint(blueprint, url_prefix=prefix)

    gutenberg.set_flask_app(app)
    gutenberg.init_db()

    configure_babel(app)

    # Auto Index the software repository
    autoindex = AutoIndex(app, add_url_rules=False)
    # FIXME: this should be done more elegantly -bcg'13

    @app.route(base_prefix + 'software/<path:path>')
    @app.route(base_prefix + 'software')
    def software_view(path='.'):
        software_dir = config().get_path('SOFTWARE', 'software_dir')
        return autoindex.render_autoindex(path,
                                          browse_root=software_dir,
                                          endpoint='software_view')

    #print "URL MAP: ", app.url_map

    # Static handling from http://flask.pocoo.org/mailinglist/archive/2011/8/25/static-files-subdomains/#9237e5b3c217b2875c59daaac4c23487
    app.config['STATIC_ROOT'] = config().get_default('WEBAPP',
                                                     'static_url_path', None)

    def static(path):
        root = app.config.get('STATIC_ROOT', None)
        if root is None:  # fallback on the normal way
            return url_for('static', filename=path)
        return urlparse.urljoin(root, path)

    @app.context_processor
    def inject_static():
        return dict(static=static)

    if enable_profiler:
        from werkzeug.contrib.profiler import ProfilerMiddleware, MergeStream
        f = open('profiler.log', 'w')
        if profiler_quiet:
            profile_app = ProfilerMiddleware(app, f, profile_dir="/tmp")
        else:
            stream = MergeStream(sys.stdout, f)
            profile_app = ProfilerMiddleware(app, stream, profile_dir="/tmp")
        return profile_app

    if enable_timepro:
        from timepro_flask import TimeProMiddleware, MergeStream
        f = open('timepro.log', 'w')
        if profiler_quiet:
            profile_app = TimeProMiddleware(app, f, profile_dir="/tmp")
        else:
            stream = MergeStream(sys.stdout, f)
            profile_app = TimeProMiddleware(app, stream, profile_dir="/tmp")
        return profile_app

    return app
Esempio n. 5
0
from functools import wraps
import os, json
from flask import Flask, render_template, request, g, session, flash, \
     redirect, url_for, abort, send_from_directory, request, Response

from flask.ext.openid import OpenID
from flask.ext.autoindex import AutoIndex

app = Flask(__name__)
app.secret_key = '\xa5\x10\xbfN3\x1f\t\xd0ec\xa1\xe8\xe7B\x1dU4!\xa1N@\xcf\xfe\xa2'

idx = AutoIndex(app, add_url_rules=False, browse_root="templates")
#idx=AutoIndex(app, add_url_rules=False, browse_root="../..")

oid = OpenID(app)


@app.before_request
def before_request():
    g.user = None
    if 'openid' in session:
        pass


def check_auth():
    if 'DOMAIN' in os.environ:
        if 'openid' in session:
            return True
        return False
    else:
        return True
Esempio n. 6
0
def create_app(path_to_notebook, *args, **kwds):
    """
    This is the main method to create a running notebook. This is
    called from the process spawned in run_notebook.py
    """
    global notebook
    startup_token = kwds.pop('startup_token', None)

    #############
    # OLD STUFF #
    #############
    import sagenb.notebook.notebook as notebook
    notebook.MATHJAX = True
    notebook = notebook.load_notebook(path_to_notebook, *args, **kwds)
    init_updates()

    ##############
    # Create app #
    ##############
    app = SageNBFlask('flask_version', startup_token=startup_token)
    app.secret_key = os.urandom(24)
    oid.init_app(app)
    app.debug = True

    @app.before_request
    def set_notebook_object():
        g.notebook = notebook

    ####################################
    # create Babel translation manager #
    ####################################
    babel = Babel(app, default_locale=notebook.conf()['default_language'],
                  default_timezone='UTC',
                  date_formats=None, configure_jinja=True)

    ########################
    # Register the modules #
    ########################
    app.register_blueprint(base)

    from worksheet_listing import worksheet_listing
    app.register_blueprint(worksheet_listing)

    from admin import admin
    app.register_blueprint(admin)

    from authentication import authentication
    app.register_blueprint(authentication)

    from doc import doc
    app.register_blueprint(doc)

    from worksheet import ws as worksheet
    app.register_blueprint(worksheet)

    from settings import settings
    app.register_blueprint(settings)

    #autoindex v0.3 doesnt seem to work with modules
    #routing with app directly does the trick
    #TODO: Check to see if autoindex 0.4 works with modules
    idx = AutoIndex(app, browse_root=SRC, add_url_rules=False)
    @app.route('/src/')
    @app.route('/src/<path:path>')
    @guest_or_login_required
    def autoindex(path='.'):
        filename = os.path.join(SRC, path)
        if os.path.isfile(filename):
            from cgi import escape
            src = escape(open(filename).read().decode('utf-8','ignore'))
            if (os.path.splitext(filename)[1] in
                ['.py','.c','.cc','.h','.hh','.pyx','.pxd']):
                return render_template(os.path.join('html', 'source_code.html'),
                                       src_filename=path,
                                       src=src, username = g.username)
            return src
        return idx.render_autoindex(path)

    return app
Esempio n. 7
0
                         })
    except ConnectionError:
        print "Failed to set brightness"
        return
    return "Set brightness"


def get_ip_type_from_devid(devid):
    conn = sqlite3.connect(dbname)
    print devid
    retval = conn.execute(
        "SELECT ipaddr, endpoint FROM devices WHERE devid==?",
        (devid, )).fetchone()
    conn.close()
    return retval


ai = AutoIndex(app,
               browse_root='/home/ryanqputz/vigilance/python/' + content_path,
               add_url_rules=True)


@app.route("/archive/")
def get_archive():
    print "archive"
    return ai.render_autoindex('.')


if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True)
Esempio n. 8
0
@app.route('/sent')
def sent():
    r = py_010_webhook_lib.send()
    return render_template('sent.html', title='Sent - Webhook--Python', data=r)


@app.route('/webhook', methods=['POST'])
def webhook():
    r = py_010_webhook_lib.webhook_listener()
    return render_template('webhook.html')


# Custom indexing of /files
files_index = AutoIndex(app,
                        os.path.curdir + '/app/files/',
                        add_url_rules=False)


# The request must provide the directory name one down from /files
@app.route('/files/<path:path>')
def autoindex(path):
    return files_index.render_autoindex(path)


################################################################################
################################################################################


@app.errorhandler(404)
def not_found_error(error):
Esempio n. 9
0
import os.path
from flask import Flask
from flask.ext.autoindex import AutoIndex

app = Flask(__name__)
AutoIndex(app)

if __name__ == '__main__':
    app.run()
Esempio n. 10
0
import os.path
from flask import Flask
from flask.ext.autoindex import AutoIndex

HOST = "0.0.0.0"  # host ip adress do not change
PORT = 8080  # only for debug and test environment. will change to 80 if product is released
DebugMode = True  # set to false if server is deployed
server = Flask(__name__)  # main server variable

AutoIndex(server, browse_root=os.path.curdir)

server.run(debug=DebugMode, host=HOST, port=PORT)
Esempio n. 11
0
def run():
    app = Flask(__name__)
    AutoIndex(app, browse_root=os.path.curdir)
    app.run()
Esempio n. 12
0

def workdirpath(wflowid):
    return '{}/{}'.format(
        os.environ.get('WORKDIRBASE', '{}/workdirs'.format(os.getcwd())),
        wflowid)


def statefile(wflowid, mode='r'):
    return open('{}/_yadage/yadage_instance.json'.format(workdirpath(wflowid)),
                mode)


index = Blueprint('index', 'index')
from flask.ext.autoindex import AutoIndex
AutoIndex(index, browse_root=workdirpath(''), add_url_rules=True)
app.register_blueprint(index, url_prefix='/index')

import celery
import os
import uuid
import wflowui
import json
from wflowui import backend as wflowbackend
import yadage.visualize


@app.route('/')
def index():
    existing_flows = os.listdir(workdirpath(''))
    return render_template('home.html', existing_flows=existing_flows)
Esempio n. 13
0
import datetime
import re

import flask
from flask.ext.autoindex import AutoIndex

import bson.json_util
from bson.objectid import ObjectId
import pymongo
import csv

import pysolar

from flask import Flask, render_template, request, jsonify, send_from_directory

AutoIndex(app, browse_root=os.path.curdir)

mongoClient = pymongo.MongoClient('localhost', 27017)
db = mongoClient.KC31
macAddressChecker = re.compile("^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$")


class JSONEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, ObjectId):
            return str(o)
        return json.JSONEncoder.default(self, o)


@app.route('/html/<path:path>')
def serveStaticPage(path):
Esempio n. 14
0
 def _python():
     rpm = flask.Blueprint("python", __name__)
     AutoIndex(rpm, browse_root=path.join(self.app_repo_config.artifacts_directory, 'python'))
     self.register_blueprint(rpm, url_prefix="/python")
Esempio n. 15
0
'''
Creates a file server for the recorded videos
'''

#!/usr/bin/python

import os.path
from flask import Flask
from flask.ext.autoindex import AutoIndex

app = Flask(__name__)
AutoIndex(app, browse_root=os.path.curdir + "/saved")

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5002)

Esempio n. 16
0
 def _archives():
     rpm = flask.Blueprint("archives", __name__)
     AutoIndex(rpm, browse_root=path.join(self.app_repo_config.artifacts_directory, 'archives'))
     self.register_blueprint(rpm, url_prefix="/archives")
Esempio n. 17
0
from flask import Flask, render_template, redirect, Markup
from banner import generate, format_data
from flask.ext.autoindex import AutoIndex
from subprocess import Popen
from glob import glob
import zipfile
import pandas
import numpy
import os

app = Flask(__name__)
index = AutoIndex(app, browse_root='/var/www/results', add_url_rules=False)

# MyConnectome Directory
myconn = os.environ['MYCONNECTOME_DIR']


# Zip files up into package
def zip_files(files, output_name):
    with zipfile.ZipFile(output_name, 'w') as myzip:
        for f in files:
            myzip.write(f)


# Global Data browser functions
def get_lookup():
    return {
        "metab": "metabolomics clustering",
        "fullmetab": "single metabolites",
        "wgcna": "weighted gene coexpression network clusters",
        "behav": "behavioral variables",
Esempio n. 18
0
  user.id = username

  user.is_authenticated = request.form['pw'] == users[username]['pw']

  return user




@app.route('/')
@flask_login.login_required
def home():
    return render_template("index.html", reference=ROUTINE, words = getWords())


idx = AutoIndex(app, './static/media', add_url_rules=False)

@app.route('/reports')
@app.route('/reports/<path:path>')
def autoindex(path='.'):
    return idx.render_autoindex(path)



@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        if request.form.get('password') == users[username]['pw']:
            user = User()
            user.id = username
Esempio n. 19
0
from flask import Flask
from flask import request
from flask.ext.autoindex import AutoIndex
import codecs
import time
app = Flask(__name__)
idx = AutoIndex(app, '/data', add_url_rules=False)

#if app.debug is not True:
if not app.debug:
    import logging
    from logging.handlers import RotatingFileHandler
    error_file_handler = RotatingFileHandler('error.log',
                                             maxBytes=1024 * 1024 * 100,
                                             backupCount=20)
    error_file_handler.setLevel(logging.WARNING)
    formatter = logging.Formatter(
        "%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    error_file_handler.setFormatter(formatter)
    app.logger.addHandler(error_file_handler)

    access_file_handler = RotatingFileHandler('access.log',
                                              maxBytes=1024 * 1024 * 100,
                                              backupCount=20)
    logger = logging.getLogger('werkzeug')
    logger.addHandler(access_file_handler)

# comma separated list of URLs where http get is sent after successful ingest
# you may want to use following variables:
# ${pid}, ${sysno}, ${name}
# NOTE: it is also possible to use substring extraction:
Esempio n. 20
0
"""
import flask
from flask.ext.autoindex import AutoIndex
from flask.ext.silk import Silk

from logga.log import log
import baip_munger
import baip_munger.exception

app = flask.Flask(__name__)
silk = Silk(app)
app.config.from_object('config')

# Load the Munger config.
try:
    conf_file = app.config['MUNGER_CONF_FILE']
    conf = baip_munger.XpathGen(conf_file=conf_file)
    app.config['MUNGER_ACTIONS'] = conf.parse_configuration()
except baip_munger.exception.MungerConfigError as e:
    log.error(str(e))

staging_index = AutoIndex(app,
                          browse_root=app.config['STAGING_DIR'],
                          add_url_rules=False)

ready_index = AutoIndex(app,
                        browse_root=app.config['READY_DIR'],
                        add_url_rules=False)

from baip_munger_ui import views
Esempio n. 21
0
from flask import Flask, render_template, request, url_for, redirect
from flask.ext.autoindex import AutoIndex

thermometer = Flask('flaskapp')

do_pretty = AutoIndex(thermometer, '/your/path/here/podserv/web', add_url_rules=False)

    
@thermometer.route('/submit', methods=('GET', 'POST'))
def submit():
    form = MyForm()
    if form.validate_on_submit():
        return redirect('/')
    return render_template('main.html', form=form)


@thermometer.route('/creds', methods=["GET","POST"])
def credentials():

    error = ''
    try:
        if request.method == "POST":
		
            attempted_username = request.form['username']
            attempted_password = request.form['password']

            flash(attempted_username)
            flash(attempted_password)

            if attempted_username == "admin" and attempted_password == "password":
                return render_template("main.html")
Esempio n. 22
0
import os.path
from master import config
from flask import Flask
from flask.ext.autoindex import AutoIndex

app = Flask(__name__)
AutoIndex(app, 'builds', add_url_rules=True)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=config.BUILDSLIST_PORT)
Esempio n. 23
0
 def _directory_index():
     packages = flask.Blueprint("packages", __name__)
     AutoIndex(packages, browse_root=self.app_repo_config.packages_directory)
     self.register_blueprint(packages, url_prefix="/packages")
Esempio n. 24
0
def create_app(path_to_notebook, *args, **kwds):
    """
    This is the main method to create a running notebook. This is
    called from the process spawned in run_notebook.py
    """
    global notebook
    startup_token = kwds.pop('startup_token', None)

    #############
    # OLD STUFF #
    #############
    import sagenb.notebook.notebook as notebook
    notebook.MATHJAX = True
    notebook = notebook.load_notebook(path_to_notebook, *args, **kwds)
    init_updates()

    ##############
    # Create app #
    ##############
    app = SageNBFlask('flask_version',
                      startup_token=startup_token,
                      template_folder=TEMPLATE_PATH)
    app.secret_key = os.urandom(24)
    oid.init_app(app)
    app.debug = True

    @app.before_request
    def set_notebook_object():
        g.notebook = notebook

    ####################################
    # create Babel translation manager #
    ####################################
    babel = Babel(app, default_locale='en_US')

    #Check if saved default language exists. If not fallback to default
    @app.before_first_request
    def check_default_lang():
        def_lang = notebook.conf()['default_language']
        trans_ids = [str(trans) for trans in babel.list_translations()]
        if def_lang not in trans_ids:
            notebook.conf()['default_language'] = None

    #register callback function for locale selection
    #this function must be modified to add per user language support
    @babel.localeselector
    def get_locale():
        return g.notebook.conf()['default_language']

    ########################
    # Register the modules #
    ########################
    app.register_blueprint(base)

    from .worksheet_listing import worksheet_listing
    app.register_blueprint(worksheet_listing)

    from .admin import admin
    app.register_blueprint(admin)

    from .authentication import authentication
    app.register_blueprint(authentication)

    from .doc import doc
    app.register_blueprint(doc)

    from .worksheet import ws as worksheet
    app.register_blueprint(worksheet)

    from .settings import settings
    app.register_blueprint(settings)

    # Handles all uncaught exceptions by sending an e-mail to the
    # administrator(s) and displaying an error page.
    @app.errorhandler(Exception)
    def log_exception(error):
        from sagenb.notebook.notification import logger
        logger.exception(error)
        return app.message(gettext('''500: Internal server error.'''),
                           username=getattr(g, 'username', 'guest')), 500

    #autoindex v0.3 doesnt seem to work with modules
    #routing with app directly does the trick
    #TODO: Check to see if autoindex 0.4 works with modules
    idx = AutoIndex(app, browse_root=SRC, add_url_rules=False)

    @app.route('/src/')
    @app.route('/src/<path:path>')
    @guest_or_login_required
    def autoindex(path='.'):
        filename = os.path.join(SRC, path)
        if os.path.isfile(filename):
            from cgi import escape
            src = escape(open(filename).read().decode('utf-8', 'ignore'))
            if (os.path.splitext(filename)[1]
                    in ['.py', '.c', '.cc', '.h', '.hh', '.pyx', '.pxd']):
                return render_template(os.path.join('html',
                                                    'source_code.html'),
                                       src_filename=path,
                                       src=src,
                                       username=g.username)
            return src
        return idx.render_autoindex(path)

    return app
Esempio n. 25
0
    return jsonify(name="invalid file", size=0)


@app.route('/uploads/<filename>')
def uploaded_file(filename):
    """
    function for serving uploaded files
    """
    if not session.get('logged_in'):
        abort(401)
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)


# make /uploads visible using AutoIndex
idx = AutoIndex(app, app.config['UPLOAD_FOLDER'], add_url_rules=True)
idx.add_icon_rule('page_white_acrobat.png', ext=['pdf', 'PDF'])


@app.route('/uploads')
def uploaded_files():
    """
    function for serving uploaded files
    """
    return idx.render_autoindex('/', show_hidden=None, sort_by='name')


if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    app.run(host='178.62.125.116')