Example #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
Example #2
0
def configure(config):

    from flask import Blueprint, Flask

    from . import routes
    from ..score_processors import ScoreProcessor

    app = Flask(__name__)
    app.config["APPLICATION_ROOT"] = config["ores"]["wsgi"]["application_root"]

    bp = Blueprint("ores", __name__)

    sp_name = config["ores"]["score_processor"]
    score_processor = ScoreProcessor.from_config(config, sp_name)

    bp = routes.configure(config, bp, score_processor)

    app.register_blueprint(bp, url_prefix=config["ores"]["wsgi"]["url_prefix"])

    return app
Example #3
0
def configure(config):

    from flask import Blueprint, Flask

    from . import routes
    from ..score_processors import ScoreProcessor

    directory = os.path.dirname(os.path.realpath(__file__))

    app = Flask(__name__, static_url_path="/BASE_STATIC", template_folder=os.path.join(directory, "templates"))

    app.config["APPLICATION_ROOT"] = config["ores"]["wsgi"]["application_root"]

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

    sp_name = config["ores"]["score_processor"]
    score_processor = ScoreProcessor.from_config(config, sp_name)

    bp = routes.configure(config, bp, score_processor)

    app.register_blueprint(bp, url_prefix=config["ores"]["wsgi"]["url_prefix"])

    return app
Example #4
0
                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
	- set fedora_handle to False, knowing it will get built in fedora_handle
Example #5
0
from flask import Flask, request, jsonify
from flask.ext.restful import Api

from ncr.services.auth import AuthService
from ncr.util import strings
from ncr.views.auth import AuthenticationResource
from ncr.views.user import UserResource

AUTHENTICATION_ROUTE = "/authenticate"
TOKEN_HEADER_KEY = "Auth-Token"

# Create new application
app = Flask(__name__)
# Set application root
app.config["APPLICATION_ROOT"] = "/ncr/api"
# Debugging is on for now
app.debug = True
# Create the REST API
api = Api(app)


@app.before_request
def before_request():
    """Before the request we're doing some authentication.

    """
    # if the client is sending data to the server, verify it is valid json
    if request.method in ["POST", "PUT"]:
        # check for the json content-type
        content_type = request.headers.get("Content-Type")
import pkg_resources
import os
import logging
from logging.handlers import WatchedFileHandler
from flask import Flask, redirect
from flask_mail import Mail

app = Flask(__name__)
app.config.from_object("npactflask.settings")
mail = Mail(app)

app.config["APPLICATION_ROOT"] = "/npact"
app.config["VERSION"] = pkg_resources.require("npactflask")[0].version


logger = logging.getLogger("")
logger.setLevel(logging.DEBUG)
fmt = "%(asctime)s %(levelname)-7s %(name)-20s| %(message)s"
logdir = app.config["LOGDIR"].makedirs_p()
fh = WatchedFileHandler(logdir / "main.log")
fh.setFormatter(logging.Formatter(fmt))
logger.addHandler(fh)

if app.config["DEBUG"]:
    sh = logging.StreamHandler()
    sh.setFormatter(logging.Formatter(fmt, datefmt="%H:%M:%S"))
    logger.addHandler(sh)
    app.logger.handlers = []  # we've superceded flask's handler, get rid of it


# all of the following register stuff in the environment
Example #7
0
import os
import settings
import inspect
from flask import Flask
from flask_restful import Api
from flask.ext.babel import Babel

app = Flask(import_name=__name__, static_folder=None, template_folder="themes")

app.config["SECRET_KEY"] = settings.app_secret
app.config["dir_base"] = os.path.dirname(os.path.abspath(__file__))
app.config["dir_root"] = "/".join(app.config["dir_base"].split("/")[:-1])
app.config["APPLICATION_ROOT"] = settings.bind_route
app.config["TEMPLATES_AUTO_RELOAD"] = settings.app_debug

SECRET_KEY = settings.app_secret

appapi = Api(app)
babel = Babel(app)
# user_timeout
locales = {"en": "English", "nl": "Nederlands"}

from bin.config import Config

settings = Config()

if not settings.local:
    raise Exception("Local settings (%s/settings.py) not found" % app.config["dir_root"])

import findex_gui.controllers.routes.static
import findex_gui.controllers.routes.errors
Example #8
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",
Example #9
0
from flask import Flask, session, redirect, url_for, request
import urllib2
import urllib
import simplejson
import redis

app = Flask(__name__)
app.debug = True
app.config["APPLICATION_ROOT"] = "/go"


@app.route("/set_position", methods=["GET", "POST"])
def set_position():
    user = check_auth(request.form.get("access_token", request.args.get("access_token")))
    if not user:
        return simplejson.dumps({"error": "access_token invalid", "code": 401})

    stream_id = request.form.get("stream_id", request.args.get("stream_id"))
    key = "".join(["appricot_position_", user["user"]["id"], "_", stream_id])
    r = redis.StrictRedis()
    r.set(key, request.form.get("position", request.args.get("position")))

    return simplejson.dumps({"status": "success"})


@app.route("/get_position", methods=["GET", "POST"])
def get_position():
    user = check_auth(request.form.get("access_token", request.args.get("access_token")))
    if not user:
        return simplejson.dumps({"error": "access_token invalid", "code": 401})
Example #10
0
from flask import Flask, render_template, request, redirect, url_for, abort
from functools import wraps
from flask_wtf import Form
from wtforms import StringField
import models
from google.appengine.api import users

app = Flask(__name__)
app.secret_key = "dj0-ifh983 dfj0 f;;j2u s3k4 "
app.config["APPLICATION_ROOT"] = "/admin"


def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        user = users.get_current_user()
        if not user.email().endswith("@ave81.com"):
            abort(401)
        # if g.user is None:
        #     return redirect(url_for('login', next=request.url))
        return f(*args, **kwargs)

    return decorated_function


@app.route("/admin/")
@login_required
def index():
    items, cursor, more = models.Project.query().fetch_page(20)
    print items
    return render_template("listing.html", items=items)
import logging

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("[%(asctime)s %(levelname)s] %(message)s")

# fh = logging.FileHandler('main.log')
# fh.setLevel(logging.DEBUG)
# fh.setFormatter(formatter)

# sh = logging.StreamHandler()
# sh.setLevel(logging.DEBUG)
# sh.setFormatter(formatter)

app = Flask("app", template_folder=os.path.join(os.path.dirname(__file__), "templates"))
app.config["APPLICATION_ROOT"] = "/digitaltmuseum"
# app.debug = True  # reload on each code change

# app.logger.addHandler(fh)
# app.logger.addHandler(sh)

# app.logger.info('Flask server started in %s', settings.APP_ROOT)

config_file = os.path.join(app.root_path, "config.yml")
config = yaml.load(open(config_file, "r"))

app.logger.info("Root path: %s", app.root_path)
app.logger.info("Instance path: %s", app.instance_path)


def error_404():
Example #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
Example #13
0
    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
Example #14
0
app = Flask(__name__)


# Schema for hosts
host_attrs = ["outside_ip", "local_ip", "user", "uptime", "free", "dfh", "ifconfig", "route"]

extra_attrs = ["port", "restart", "update_configs", "last_report", "nickname"]


# Authentication
app.config["BASIC_AUTH_FORCE"] = require_login
app.config["BASIC_AUTH_USERNAME"] = username
app.config["BASIC_AUTH_PASSWORD"] = password
basic_auth = BasicAuth(app)

app.config["APPLICATION_ROOT"] = base_uri

# Initialize Database
con = lite.connect("db.sqlite3")
try:
    con.cursor().execute("select * from Clients")
except lite.OperationalError:
    print "No DB found, creating..."
    con.cursor().execute(
        "create table Clients(hostname UNIQUE, " + ", ".join(host_attrs) + "," + ", ".join(extra_attrs) + ");"
    )


# Helper Methods
def get_args(request, key):
    try:
from flask import Flask
import logging

app = Flask(__name__, static_url_path="")
app.config.from_object("config")
app.config["APPLICATION_ROOT"] = "/api/v1"


logging.basicConfig(filename="myapp.log", level=logging.DEBUG)

logging.info("Started")
logging.info(app.config)


from app.routes import indexMysql
Example #16
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
Example #17
0
from os import environ
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
Example #18
0

# Demonstrate.
root = PartylineFlask(__name__)
one = PartylineFlask(__name__)
two = PartylineFlask(__name__)
three = Flask(__name__)  # Add a non-partyline application.

root.debug = True
one.debug = True
two.debug = True
three.debug = True

one.config["APPLICATION_ROOT"] = "/one"
two.config["APPLICATION_ROOT"] = "/two"
three.config["APPLICATION_ROOT"] = "/three"

template = """
<html>
<head>
  <title>Demo: Cross-application URL building in Flask.</title>
</head>
<body>
  <p>You are in the root application.</p>
  <ul>
    <li><a href="%s">Go to application one</a></li>
    <li><a href="%s">Go to application two</a></li>
  </ul>
  <p>Source code is <a href="http://github.com/rduplain/wsgi_party">here</a>.</p>
</body>
</html>