Beispiel #1
0
def configure(config):
    directory = os.path.dirname(os.path.realpath(__file__))

    app = Flask(
        "wikilabels",
        static_url_path="/BASE_STATIC",  # No conflict with blueprint
        template_folder=os.path.join(directory, "templates"),
    )
    app.config["APPLICATION_ROOT"] = config["wsgi"]["application_root"]

    bp = Blueprint("wikilabels", __name__, static_folder=os.path.join(directory, "static"))

    db = DB.from_config(config)
    form_directory = config["wikilabels"]["form_directory"]
    form_filenames = (os.path.join(form_directory, fn) for fn in os.listdir(form_directory))
    form_map = {d["name"]: d for d in (yaml.load(open(fn)) for fn in form_filenames)}

    app = sessions.configure(app)

    oauth_config = yaml.load(open(config["oauth"]["creds"]))

    consumer_token = mwoauth.ConsumerToken(oauth_config["key"], oauth_config["secret"])

    oauth = mwoauth.Handshaker(config["oauth"]["mw_uri"], consumer_token)

    bp = routes.configure(config, bp, db, oauth, form_map)
    app.register_blueprint(bp, url_prefix=config["wsgi"]["url_prefix"])

    return app
Beispiel #2
0
def configure(config):
    directory = os.path.dirname(os.path.realpath(__file__))

    app = Flask("wikilabels",
                static_url_path="/BASE_STATIC",  # No conflict with blueprint
                template_folder=os.path.join(directory, 'templates'))
    app.config["APPLICATION_ROOT"] = config['wsgi']['application_root']
    bp = Blueprint('wikilabels', __name__,
                   static_folder=os.path.join(directory, 'static'))

    db = DB.from_config(config)

    form_directory = config['wikilabels']['form_directory']
    form_filenames = (os.path.join(form_directory, fn)
                      for fn in os.listdir(form_directory))
    form_map = {d['name']: d for d in
                (yaml.load(open(fn)) for fn in form_filenames)}

    app = sessions.configure(app)

    oauth_config = yaml.load(open(config['oauth']['creds']))

    consumer_token = mwoauth.ConsumerToken(oauth_config['key'],
                                           oauth_config['secret'])

    oauth = mwoauth.Handshaker(config['oauth']['mw_uri'], consumer_token)

    bp = routes.configure(config, bp, db, oauth, form_map)
    app.register_blueprint(bp, url_prefix=config['wsgi']['url_prefix'])

    return app
Beispiel #3
0
def configure(config):
    directory = os.path.dirname(os.path.realpath(__file__))

    app = Flask("wikilabels",
                static_url_path="/BASE_STATIC",  # No conflict with blueprint
                template_folder=os.path.join(directory, 'templates'))
    app.config["APPLICATION_ROOT"] = config['wsgi']['application_root']
    bp = Blueprint('wikilabels', __name__,
                   static_folder=os.path.join(directory, 'static'))

    db = DB.from_config(config)

    form_directory = config['wikilabels']['form_directory']
    form_i18n_directory = config['wikilabels']['form_i18n_directory']
    form_filenames = (os.path.join(form_directory, fn)
                      for fn in os.listdir(form_directory))
    form_map = {}
    for fn in form_filenames:
        form_name = os.path.splitext(os.path.basename(fn))[0]
        form_map[form_name] = yaml.load(open(fn))
    for form_name in form_map:
        i18n_dir = os.path.join(form_i18n_directory, form_name)
        form_map[form_name]['i18n'] = (
            {lang[:-5]: json.load(open(os.path.join(i18n_dir, lang)))
                for lang in os.listdir(i18n_dir)}
        )
    app = sessions.configure(app)

    consumer_token = mwoauth.ConsumerToken(config['oauth']['key'],
                                           config['oauth']['secret'])

    oauth = mwoauth.Handshaker(config['oauth']['mw_uri'], consumer_token)

    bp = routes.configure(config, bp, db, oauth, form_map)
    CORS(bp, origins=config['wsgi'].get('cors_allowed', '*'),
         supports_credentials=True)
    app.register_blueprint(bp, url_prefix=config['wsgi']['url_prefix'])

    return app
Beispiel #4
0
from indexworker import indexpage
from indexworker import dobookmarks
import time
from flask import render_template
from config import admin_url

import requests
import json
import os
from werkzeug.utils import secure_filename
from elasticsearch import Elasticsearch

app = Flask(__name__)


app.config["APPLICATION_ROOT"] = "/breadcrumbs"


def crossdomain(origin=None, methods=None, headers=None, max_age=21600, attach_to_all=True, automatic_options=True):
    if methods is not None:
        methods = ", ".join(sorted(x.upper() for x in methods))
    if headers is not None and not isinstance(headers, basestring):
        headers = ", ".join(x.upper() for x in headers)
    if not isinstance(origin, basestring):
        origin = ", ".join(origin)
    if isinstance(max_age, timedelta):
        max_age = max_age.total_seconds()

    def get_methods():
        if methods is not None:
            return methods
Beispiel #5
0
#!/usr/bin/python

from flask import Flask

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///AA.db'
app.config["APPLICATION_ROOT"] = '/patacsdb'

import PATACSDB.views

if __name__ == "__main__":
    app.run()
Beispiel #6
0
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), ".."))

from lib.cuckoo.common.constants import CUCKOO_VERSION, CUCKOO_ROOT
from lib.cuckoo.common.utils import store_temp_file, delete_folder
from lib.cuckoo.core.database import Database, TASK_RUNNING, Task
from lib.cuckoo.core.database import TASK_REPORTED, TASK_COMPLETED
from lib.cuckoo.core.startup import drop_privileges
from lib.cuckoo.core.rooter import rooter

# Global Database object.
db = Database()

# Initialize Flask app.
app = Flask(__name__)
app.config["APPLICATION_ROOT"] = "/api"

def json_error(status_code, message):
    """Return a JSON object with a HTTP error code."""
    r = jsonify(message=message)
    r.status_code = status_code
    return r

@app.after_request
def custom_headers(response):
    """Set some custom headers across all HTTP responses."""
    response.headers["Server"] = "Machete Server"
    response.headers["X-Content-Type-Options"] = "nosniff"
    response.headers["X-Frame-Options"] = "DENY"
    response.headers["X-XSS-Protection"] = "1; mode=block"
    response.headers["Pragma"] = "no-cache"
Beispiel #7
0
from launchpad import FlaskPad
from flask.ext.paginate import Pagination
from collections import defaultdict
import codecs

###############################
# from tornado.wsgi import WSGIContainer
# from tornado.httpserver import HTTPServer
# from tornado.ioloop import IOLoop
# from . import app

# http_server = HTTPServer(WSGIContainer(app))
# http_server.listen(5000)
# IOLoop.instance().start()
app = Flask(__name__)
app.config["APPLICATION_ROOT"] = "/workflows"
app.config["PROPAGATE_EXCEPTIONS"] = True
app.use_reloader = True
CMO_CONFIG_LOC = "/opt/common/CentOS_6-dev/cmo"
hello = __name__
lp = FlaskPad.from_file(CMO_CONFIG_LOC + "/cmo_launchpad.yaml")
PER_PAGE = 20
STATES = Firework.STATE_RANKS.keys()
client = MongoClient(host="pitchfork.mskcc.org", port=27017)
dbnames = client.database_names()

state_to_class = {
    "RUNNING": "warning",
    "WAITING": "primary",
    "FIZZLED": "danger",
    "READY": "info",
Beispiel #8
0
from os.path import isfile
from platform import node
from flask import Flask
from werkzeug.wsgi import DispatcherMiddleware
from werkzeug.exceptions import NotFound

# check hostname to determine if it is a production deployment
deployed_in_production = node() == "anchor"

DEBUG = not deployed_in_production
# deployed behind ngix
URL_ROOT = "/finance" if deployed_in_production else None

env_db = environ.get('FINANCE_DB')
DATABASE = r"C:\work\finance.db" if env_db is None else env_db
if not isfile(DATABASE):
    DATABASE = None  # FakeDao will be used

app = Flask(__name__)
# load all uppercase variables ad configuration
app.config.from_object(__name__)
app.debug = DEBUG

if URL_ROOT is not None:
    app.config["APPLICATION_ROOT"] = URL_ROOT
    application = DispatcherMiddleware(NotFound, {URL_ROOT: app})
else:
    application = app

import views
Beispiel #9
0
from jinja2 import Environment, FileSystemLoader

from flask import Flask
from flask import render_template
from flask import request
from flask import Response
from flask import session
from flask import redirect
from flask import url_for

from utils import read_dict_file, write_dict_file, current_dir, read_settings


app = Flask(__name__)
app.secret_key = 'SALKAS DFLkdaDSF&*5462SDAsd@E#'
app.config["APPLICATION_ROOT"] = "/secret-santa"

env = Environment(loader=FileSystemLoader(
    os.path.join(current_dir,'templates'))
)


def read_passwords():
    return dict((email.lower(), password) for (email, password) in read_dict_file("passwords.txt").iteritems())


def read_names():
    return dict((email.lower(), name) for (name, email) in read_dict_file("names.txt").iteritems())


def read_groups():
Beispiel #10
0
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import UniqueConstraint
import keys
time_format='%Y-%m-%dT%H:%M:%S'

try:
    root_dir=os.path.dirname(__file__)
    app = Flask(__name__)
except NameError: # during dev:
    root_dir="."
    app = Flask("weather_app2")

volatile=os.path.join(root_dir,'volatile')
    
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(root_dir,'volatile','sensors.db')
app.config["APPLICATION_ROOT"] = "/weather2"
db = SQLAlchemy(app)


# post-process a dataframe result to a desired resolution in time
def downsample(raw,period_secs):
    """
    raw: pandas DataFrame, with a datetime64 time column
    """
    timestamp=utils.to_unix(raw.time.values)
    periods=timestamp//period_secs
    
    #agg=raw.groupby(periods).agg( [np.min,np.mean,np.max] )
    agg=raw.groupby(periods).agg( [np.mean] )

    # drop multiindex by compounding the names
Beispiel #11
0
			if path_info.startswith(script_name):
				environ['PATH_INFO'] = path_info[len(script_name):]

		scheme = environ.get('HTTP_X_SCHEME', '')
		if scheme:
			environ['wsgi.url_scheme'] = scheme
		return self.app(environ, start_response)

# create app
app = Flask(__name__)

# if using app prefix, wrap Flask app in ReverseProxied class from above
if localConfig.APP_PREFIX_USE:
	print "wrapping WSUDOR_Manager for reverse proxy"
	app.wsgi_app = ReverseProxied(app.wsgi_app)
	app.config["APPLICATION_ROOT"] = "/%s" % localConfig.APP_PREFIX



##########################################################################################
# instantiate fedora_handle
##########################################################################################
'''
Needs Improvement.

If no args passed, assume 'python runserver.py', and thus, not celery worker.
	- fire generic fedora_handle with username / password from localConfig
	- handles API-M calls and some tasks (e.g. solrIndexer)
	- but again, would be ideal if these all worked from generic, localhost fedora_handle

If celery worker -- with multiple args -- fire fedora_handle based on username
Beispiel #12
0
# -*- coding=utf-8 -*-
from flask import Flask, render_template
from flask.ext.sqlalchemy import SQLAlchemy
# from .views import lib
import os,sys
from flask.ext.login import LoginManager
from flask.ext.openid import OpenID
from config import basedir

app = Flask(__name__)
print(__name__)
app.config.from_object('config')
app.config["APPLICATION_ROOT"] = 'apps'
db = SQLAlchemy(app)

lm = LoginManager()
lm.init_app(app)
lm.login_view = 'login'
oid = OpenID(app, os.path.join(basedir, 'tmp'))


from apps import views, models, baseview
from apps.models import *
reload(sys)
sys.setdefaultencoding('utf8')
text_factory = str

@lm.user_loader
def load_user(id):
    return user.query.get(int(id))
Beispiel #13
0
from functools import update_wrapper
from gen import generate_from_text, generate_cache



dir_path = os.path.dirname(os.path.realpath(__file__))
UPLOAD_FOLDER = dir_path + "/teksty"
ALLOWED_EXTENSIONS = set(['txt'])

sdir = os.path.join(os.path.abspath(
    os.path.dirname(__file__)), 'static')

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['JSON_AS_ASCII'] = False
app.config["APPLICATION_ROOT"] = "/epygone"

handler = RotatingFileHandler('foo.log', maxBytes=10000, backupCount=1)
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)


def get_files():
    return [name for name in os.listdir(UPLOAD_FOLDER) if not name.startswith('.')]

TEXT_CACHE = generate_cache(UPLOAD_FOLDER, get_files())
# cors = CORS(app, resources={r"/rand": {"origins": "*"}})
# print(TEXT_CACHE)

def parse_tadeoa(rand=True, **kwargs):
    files = get_files()
Beispiel #14
0
    import binascii
    key = os.urandom(24)
    hexkey = binascii.hexlify(os.urandom(32)).decode()
    common.writesettings("APPKEY", hexkey)
    app.secret_key = hexkey
else:
    app.secret_key = common.readsettings("APPKEY")

if settings.SSL:
    app.config["SSL"] = True

if settings.running_with_iis == True:
    from werkzeug.wsgi import DispatcherMiddleware
    app.wsgi_app = DispatcherMiddleware(
        app.wsgi_app, {settings.iis_virtual_path: app.wsgi_app})
    app.config["APPLICATION_ROOT"] = settings.iis_virtual_path

####### error #######


@app.errorhandler(400)
def bad_request(error):
    app.logger.error(error)
    return render_template('error/400.html'), 400


@app.errorhandler(401)
def authorization_required(error):
    app.logger.error(error)
    return render_template('error/401.html'), 401