Example #1
1
def create_app(config=None):
    """Create an instance of the tentd flask application"""
    app = Flask("tentd")
    app.add_url_rule("/", "home", description)
    app.request_class = Request

    # Load the default configuration values
    import tentd.defaults as defaults

    app.config.from_object(defaults)

    # Load the user configuration values
    if isinstance(config, basestring):
        config = make_config(config)

    if not isinstance(config, dict):
        raise TypeError("Config argument must be a dict or string.")

    if config is not None:
        app.config.update(config)

    # Initialise the db for this app
    db.init_app(app)

    # Register the entity blueprints
    for blueprint in (entity, followers, posts):
        app.register_blueprint(blueprint, url_prefix=blueprint.prefix(app))

    return app
Example #2
1
 def load_app(self, config):
     """
     Called from the parent class, so we can provide the appropriate flask
     app for this test case.
     """
     app = Flask("test.localhost")
     app.request_class = Request
     app.config.update(config)
     app.register_blueprint(test_views)
     app.central_userdb = UserDB(app.config["MONGO_URI"], "eduid_am")
     app.session_interface = SessionFactory(app.config)
     return app
Example #3
0
def create_app():
    from flask import Flask, Request, got_request_exception
    import rollbar.contrib.flask

    app = Flask(__name__)

    @app.route("/")
    def index():
        return "Index page"

    @app.route("/cause_error", methods=["GET", "POST"])
    def cause_error():
        raise Exception("Uh oh")

    @app.before_first_request
    def init_rollbar():
        rollbar.init(
            TOKEN, "flasktest", root=os.path.dirname(os.path.realpath(__file__)), allow_logging_basic_config=True
        )
        got_request_exception.connect(rollbar.contrib.flask.report_exception, app)

    class CustomRequest(Request):
        @property
        def rollbar_person(self):
            return {"id": "123", "username": "testuser", "email": "test@example.com"}

    app.request_class = CustomRequest

    return app
Example #4
0
def create(
    static_url_path="", configuration=None, settings=settings, environment_variable="CRAIC_SETTINGS", blueprints=[]
):
    """Create the Craic application.

    :param static_url_path: Default ``''``. Specify the URL path for static
        files.
    :param configuration: Default `None`. Python configuration file name.
    :param settings: Default :mod:`settings`. Default configuration settings -
        used only if `configuration` is not provided.
    :param environment_variable: Default ``'CRAIC_SETTINGS'``. The name of the
        environment variable that points to a configuration file - overrides
        any existing configuration setting.
    :param blueprints: Default `[]`. A list of application blueprints.
    """
    ret_val = Flask(__name__, static_url_path=static_url_path)
    ret_val.request_class = Request

    if configuration:
        ret_val.config.from_pyfile(configuration)
    else:
        ret_val.config.from_object(settings)

    ret_val.config.from_envvar(environment_variable, silent=True)
    init_extensions(ret_val)
    init_blueprints(ret_val, *blueprints)
    init_middleware(ret_val)

    @ret_val.before_request
    def before_request():
        g.is_local = is_local(request.environ)
        g.user_agent = UserAgent(request.environ)

    @ret_val.context_processor
    def context_processor():
        if hasattr(g, "title"):
            title = gettext("Craic / %(title)s", title=g.title)
        else:
            title = gettext("Craic.")

        return dict(title=title)

    return ret_val
Example #5
0
def create_app(configfilename=None):
    """Loads the configfilename in the app.config object as requested"""
    setup_logging()
    log.debug("creating application")
    app = Flask(__name__)
    setup_config(app, configfilename)
    setup_modules(app)
    setup_aux(app)
    # If we run behind nginx, fix the request vars
    if app.config["PROXYPASS"]:
        log.debug("Loading proxy fix")
        app.wsgi_app = ProxyFix(app.wsgi_app)
    else:
        log.debug("Running without proxy fix")
    # bittorrent clients live in the stone age
    app.request_class = Latin1Request
    log.debug("setup request class")
    # Register the redis connect before every request
    app.before_request(redis_connect)
    log.debug("assigned before_request")
    return app
Example #6
0
        target = url_for(endpoint, **values)
    return redirect(target)


class JSONRequest(Request):
    # from http://flask.pocoo.org/snippets/45/
    def wants_json(self):
        mimes = json_mimetypes
        mimes.append("text/html")
        best = self.accept_mimetypes.best_match(mimes)
        return best in json_mimetypes and self.accept_mimetypes[best] > self.accept_mimetypes["text/html"]


app = Flask(__name__)
app.config.from_object(config)
app.request_class = JSONRequest
app.jinja_env.filters["datetime"] = format_datetime
app.jinja_env.filters["isodatetime"] = lambda d: d.isoformat() + "Z"
app.jinja_env.filters["format_currency"] = format_currency
app.static_folder = "static"

redis_conn = redis.from_url(app.config["REDIS_URL"])
app.session_interface = session.RedisSessionInterface(redis_conn)

csrf = SeaSurf(app)
db = SQLAlchemy(app)
migrate = Migrate(app, db)

login_manager = LoginManager()
login_manager.login_view = "auth.login"
login_manager.init_app(app)
Example #7
0
def create_app(config=None, **kwargs):
    """Create the WSGI application that is this app.

    In addition to the arguments documented below, this function accepts as a
    keyword agument all agruments to :py:class:`flask.Flask` except
    `import_name`, which is set to 'evesrp'. Additionally, the value of
    `instance_relative_config` has a default value of `True`.

    If the `config` argument isn't specified, the app will attempt to use the
    file 'config.py' in the instance folder if it exists, and will then fall
    back to using the value of the EVESRP_SETTINGS environment variable as a
    path to a config file.

    :param config: The app configuration file. Can be a Python
        :py:class:`dict`, a path to a configuration file, or an importable
        module name containing the configuration.
    :type config: str, dict
    """
    # Default instance_relative_config to True to let the config fallback work
    kwargs.setdefault("instance_relative_config", True)
    app = Flask("evesrp", **kwargs)
    app.request_class = AcceptRequest
    app.config.from_object("evesrp.default_config")
    # Push the instance folder path onto sys.path to allow importing from there
    sys.path.insert(0, app.instance_path)
    # Check in config is a dict, python config file, or importable object name,
    # in that order. Finally, check the EVESRP_SETTINGS environment variable
    # as a last resort.
    if isinstance(config, dict):
        app.config.update(config)
    elif isinstance(config, six.string_types):
        if config.endswith((".txt", ".py", ".cfg")):
            app.config.from_pyfile(config)
        else:
            app.config.from_object(config)
    elif config is None:
        try:
            app.config.from_pyfile("config.py")
        except OSError:
            app.config.from_envvar("EVESRP_SETTINGS")

    # Register SQLAlchemy monitoring before the DB is connected
    app.before_request(sqlalchemy_before)

    db.init_app(app)

    from .views.login import login_manager

    login_manager.init_app(app)

    before_csrf = list(app.before_request_funcs[None])
    csrf.init_app(app)
    # Remove the context processor that checks CSRF values. All it is used for
    # is the template function.
    app.before_request_funcs[None] = before_csrf

    # Hook up OAuth
    oauth.init_app(app)

    # Connect views
    from .views import index, error_page, update_navbar, divisions, login, requests, api

    app.add_url_rule(rule=u"/", view_func=index)
    for error_code in (400, 403, 404, 500):
        app.register_error_handler(error_code, error_page)
    app.after_request(update_navbar)
    app.register_blueprint(divisions.blueprint, url_prefix="/division")
    app.register_blueprint(login.blueprint)
    app.register_blueprint(requests.blueprint, url_prefix="/request")
    app.register_blueprint(api.api, url_prefix="/api")
    app.register_blueprint(api.filters, url_prefix="/api/filter")

    from .views import request_count

    app.add_template_global(request_count)

    from .json import SRPEncoder

    app.json_encoder = SRPEncoder

    # Configure the Jinja context
    # Inject variables into the context
    from .auth import PermissionType

    @app.context_processor
    def inject_enums():
        return {
            "ActionType": models.ActionType,
            "PermissionType": PermissionType,
            "app_version": __version__,
            "site_name": app.config["SRP_SITE_NAME"],
            "url_for_page": requests.url_for_page,
        }

    # Auto-trim whitespace
    app.jinja_env.trim_blocks = True
    app.jinja_env.lstrip_blocks = True

    init_app(app)

    return app
Example #8
0
from data_models import Quote, Tag, Vote
from jsonify import jsonify
import flask_override
from db import db
from sql import db_session  # yuck, we shouldnt dep on this
from basic_auth import FlaskRealmDigestDB
from news import News
from rest import build_link, add_loc_hdr, add_link_hdr

# app config
SECRET_KEY = "\xfb\x12\xdf\xa1@i\xd6>V\xc0\xbb\x8fp\x16#Z\x0b\x81\xeb\x16"
DEBUG = True
CACHE_TYPE = "simple"

app = Flask(__name__)
app.request_class = flask_override.Request
app.config.from_object(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)

cache = Cache(app)

navs = [
    build_link("/top", "pyqdb/quotes", Quote.list_json_mimetype, title="Top"),
    build_link("/quotes", "pyqdb/quotes", Quote.list_json_mimetype, title="Browse"),
    build_link("/random", "pyqdb/quotes", Quote.list_json_mimetype, title="Random"),
    build_link("/tags", "pyqdb/tags", Tag.list_json_mimetype, title="Tags"),
    build_link("/search", "", "application/json", title="Search"),
    build_link("/quotes/new", "pyqdb/quote/new", Quote.json_mimetype, title="Submit"),
]

authDB = FlaskRealmDigestDB("MyAuthRealm")
Example #9
0
File: store.py Project: dlobue/clio
app.config.from_object("clio.settings")
try:
    app.config.from_envvar("CLIO_SETTINGS")
except RuntimeError:
    if os.path.exists("/etc/clio/app.conf"):
        app.logger.debug("couldn't load settings from file in envvar. trying /etc/clio/app.conf")
        try:
            app.config.from_pyfile("/etc/clio/app.conf")
        except RuntimeError:
            app.logger.debug("unable to find any settings files. using defaults in local settings module.")
    else:
        app.logger.debug("unable to find any settings files. using defaults in local settings module.")

from utils import ExtRequest

app.request_class = ExtRequest

mongo_conn = None


def get_mongo_conn():
    global mongo_conn
    if mongo_conn is None:
        mongo_conn = pymongo.Connection(app.config["MONGO_HOSTS"], app.config["MONGO_PORT"]).clio
    return mongo_conn


def validify_data(data):
    if not isinstance(data, dict):
        return data
Example #10
0

DIRNAME = os.path.dirname(__file__)
if not DIRNAME:
    DIRNAME = "/home/ki/my_projects/dartz_spb_ru__shop/dartz_shop/src"
DB_NAME = "%s/items.csv" % DIRNAME
LOCKFILE = "%s/items.lock" % DIRNAME


class CyrillicRequest(Request):
    url_charset = "cp1251"


app = Flask(__name__)
if not DEBUG_MODE:
    app.request_class = CyrillicRequest

# Turn of on production
app.debug = DEBUG_MODE


# =============================
#           UTILS
# =============================
def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
    # csv.py doesn't do Unicode; encode temporarily as UTF-8:
    csv_reader = csv.reader(unicode_csv_data, dialect=dialect, **kwargs)
    for row in csv_reader:
        # decode UTF-8 back to Unicode, cell by cell:
        yield [unicode(cell, "utf-8") for cell in row]
Example #11
0
def create_app(config_filename=None):
    app = Flask(__name__)
    app.request_class = Request
    app.url_map.converters["re"] = RegexConverter

    if config_filename is None:
        HerokuConfig(app)
    else:
        AppConfig(app, config_filename)

    from_envvars(app.config, prefix="")
    app.debug = app.config.get("DEBUG")

    # TODO: these variables probably aren't unjsonnable anymore

    # push all variables into the environment
    unjsonnable = (datetime, timedelta)
    data = {k: json.dumps(v) for k, v in app.config.items() if not isinstance(v, unjsonnable)}
    os.environ.update(data)

    # app.logger.info('App is running on port %s', os.environ.get('PORT'))

    if app.config["DEBUG"] is not True:
        log_level = app.config.get("LOG_LEVEL", "DEBUG")
        app.logger.setLevel(getattr(logging, log_level.upper()))

    import bauble.db as db

    if "LOG_SQL" in os.environ:
        logging.getLogger("sqlalchemy.engine").setLevel(logging.INFO)

    db.init_app(app)

    # register flask extensionsa
    SSLify(app, permanent=True)
    app.login_manager = LoginManager(app)
    app.login_manager.login_view = "auth.login"
    app.mail = Mail(app)
    app.babel = Babel(app)

    from .assets import init_app

    init_app(app)

    # TODO: just import everything controllers

    for controller in ["auth", "index", "batch"]:
        module = import_module("bauble.controllers.{}".format(controller))
        app.register_blueprint(module.blueprint)

    from bauble.resource import Resource

    controllers = ["search", "family", "genus", "taxon", "accession", "plant", "location", "vernacular_name"]
    for controller in controllers:
        module = import_module("bauble.controllers.{}".format(controller))
        for attr_name in dir(module):
            attr = getattr(module, attr_name)
            # find all the blueprints in the files
            if isinstance(attr, Blueprint):
                app.register_blueprint(attr)
            # if isclass(attr) and issubclass(attr, Blueprint) and attr != Resource:
            #     app.register_blueprint(attr())

    from bauble.error import init_errorhandlers

    init_errorhandlers(app)

    app.json_encoder = JSONEncoder

    return app
Example #12
0
        cfg["rollbar"]["environment"],
        root=os.path.dirname(os.path.realpath(__file__)),
        allow_logging_basic_config=False,
    )
    got_request_exception.connect(rollbar.contrib.flask.report_exception, app)


class CustomRequest(Request):
    @property
    def rollbar_person(self):
        from flask import session

        return {"id": session["user_id"], "username": session["user_name"], "email": session["email"]}


app.request_class = CustomRequest

if __name__ == "__main__":
    # Create Views
    __builtin__.flock_app = app
    from flock import views

    # Run with Tornado
    from tornado.wsgi import WSGIContainer
    from tornado.httpserver import HTTPServer
    from tornado.ioloop import IOLoop

    http_server = HTTPServer(WSGIContainer(app))

    http_server.listen(cfg["web_server"]["port"], address=cfg["web_server"]["host"])
    IOLoop.instance().start()
import os
from flask import Flask, Request, jsonify, request
from netaddr import *
import random


class MyRequest(Request):
    def __init__(self, environ, populate_request=True, shallow=False):
        if not environ.get("CONTENT_TYPE", ""):
            environ["CONTENT_TYPE"] = "application/json"
        super(self.__class__, self).__init__(environ, populate_request, shallow)


app = Flask(__name__)
app.request_class = MyRequest


@app.route("/Plugin.Activate", methods=["POST"])
def plugin_activate():
    resp = {"Implements": ["NetworkDriver"]}
    return jsonify(resp)


_networks = {}


@app.route("/NetworkDriver.CreateNetwork", methods=["POST"])
def create_network():
    network = request.json
    network["cidr"] = IPNetwork("192.168.0.0/24")
    network["gateway"] = str(network["cidr"].iter_hosts().next())
Example #14
0
# -*- coding: utf-8 -*-

import unittest

from werkzeug import MultiDict
from flask import Flask, request

from flaskoauth import OAuthRequest

app = Flask(__name__)
app.request_class = OAuthRequest


class TestOAuthRequest(unittest.TestCase):
    def test_oauth_normalized_request_parameters(self):
        with app.test_request_context("/photos?size=original&file=vacation.jpg"):
            request.form = MultiDict()
            request.headers = {
                "Authorization": 'OAuth oauth_consumer_key="dpf43f3p2l4k3l03", oauth_token="", oauth_nonce="kllo9940pd9333jh", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1191242096", oauth_version="1.0", oauth_signature="4J55AIIGX6DlGs7mUZYHwtz%2FfCg%3D"'
            }
            oauth_request = request.oauth
            self.assertTrue(oauth_request.verify_signature("kd94hf93k423kf44"))

    def test_oauth_non_english_parameters(self):
        with app.test_request_context("/photos?type=אוטובוס&scenario=תאונה"):
            request.form = MultiDict()
            request.headers = {
                "Authorization": 'OAuth oauth_consumer_key="dpf43f3++p+#2l4k3l03", oauth_token="nnch734d(0)0sl2jdk", oauth_nonce="kllo~9940~pd9333jh", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1191242096", oauth_version="1.0", oauth_signature="KdNbhMazVmaCPUZA9%2BtZBTZ8%2FkE%3D"'
            }

            oauth_request = request.oauth
from flask.ext import gae_tests
from flask.ext import gae_blobstore
from google.appengine.api import files
from google.appengine.ext import ndb


# test application..


class TestModel(ndb.Model):
    blob_key = ndb.BlobKeyProperty()


app = Flask(__name__)
app.debug = True
app.request_class = gae_tests.FileUploadRequest


@app.route("/test_upload", methods=["POST", "OPTIONS", "HEAD", "PUT"])
@gae_blobstore.upload_blobs()
def test_upload(uploads):
    entities = []
    try:
        for upload in uploads:
            entity = TestModel(blob_key=upload.blob_key)
            entities.append(entity)
            blob_info = upload.blob_info
            logging.info("upload.blob_info: %s", blob_info)
        ndb.put_multi(entities)
    except:
        # rollback the operation and delete the blobs,
Example #16
0
        return self.readline()


class FileShareRequest(Request):
    def __init__(self, environ, populate_request=True, shallow=False):
        environ = copy(environ)

        stream = ProgressWsgiInputWrapper(environ["wsgi.input"], get_content_length(environ))
        environ["wsgi.input"] = stream

        super(FileShareRequest, self).__init__(environ, populate_request, shallow)

        progress_streams[self.path] = stream


app.request_class = FileShareRequest


@app.route("/")
def index():
    global upload_id

    upload_id += 1

    return render_template("index.html", upload_id=upload_id)


@app.route("/upload/<upload_id>", methods=["POST"])
def upload(upload_id):
    print request.files
Example #17
0
    def __init__(self, environ, populate_request=True, shallow=False):
        super(Request, self).__init__(environ, populate_request, shallow)

        if self.headers.get("X-Forwarded-Proto") == "https":
            environ["wsgi.url_scheme"] = "https"


# app setup + static files
app = Flask(__name__, static_url_path="", static_folder="static")
socketio = SocketIO(app)

# csrf_token protect
csrf = SeaSurf(app)

# apply SSL termination handling
app.request_class = ProxiedRequest

# configuration file
if os.path.isfile("./DEV"):
    app.config.from_object("config.DebugConfiguration")
else:
    app.config.from_object("config.BaseConfiguration")

# other app'ish things
login_manager = LoginManager(app)  # login manager
manager = Manager(app)  # shell actions manager
db = SQLAlchemy(app)  # database connection
bcrypt = Bcrypt(app)  # hashing function

# users module blueprint
from webapp.handlers.userhandlers import mod as usersModule
# -*- coding: UTF-8 -*-
# vim: set ts=4 sw=4 expandtab :

from flask import Flask, Response, jsonify, request, abort

import complexform

app = Flask(__name__)
app.request_class = complexform.ComplexFormRequest


@app.route("/", methods=["GET", "POST", "PATCH", "DELETE"])
def index():
    print "REQUEST"

    import pdb

    pdb.set_trace()

    return "OK"


if __name__ == "__main__":
    app.run()
Example #19
0
from raven import Client
from raven.middleware import Sentry

from yoi.account.user import bp as account
from yoi.config import (secret,
                        database_url,
                        in_production,
                        canonical_domain,
                        always_secure)
from yoi import dweeb
from yoi.flask_genshi import Genshi, render_response
from yoi import middleware
from yoi.resources import static_url

app = Flask(__name__)
app.request_class = dweeb.Request

app.genshi = Genshi(app)
app.db = SQLAlchemy(app)

app.register_blueprint(account)

# FIXME - Use app.config.from_object
app.config['DEBUG'] = True
app.config['PROPAGATE_EXCEPTIONS'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = database_url
app.config['SECRET_KEY'] = secret

if canonical_domain:
    app.config['SESSION_COOKIE_DOMAIN'] = canonical_domain
app.config['SESSION_COOKIE_HTTPONLY'] = True
Example #20
0
# this enable us to use gevent for launching background task
from gevent import monkey

monkey.patch_all()

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import logging.config
import sys
from chaos.utils import Request
from chaos.publisher import Publisher

app = Flask(__name__)
app.config.from_object("chaos.default_settings")
app.config.from_envvar("CHAOS_CONFIG_FILE")
app.request_class = Request


if "LOGGER" in app.config:
    logging.config.dictConfig(app.config["LOGGER"])
else:  # Default is std out
    handler = logging.StreamHandler(stream=sys.stdout)
    app.logger.addHandler(handler)
    app.logger.setLevel("INFO")


db = SQLAlchemy(app)

publisher = Publisher(app.config["RABBITMQ_CONNECTION_STRING"], app.config["EXCHANGE"], app.config["ENABLE_RABBITMQ"])

import chaos.api
Example #21
0
    )
    file_handler.setFormatter(formatter)
    app.logger.addHandler(file_handler)

# initialize configured database connections
for username, password, database, label, hidden in config.DEFAULT_DATABASES:
    models.add_database(username, password, database, label, hidden)


class LimitedRequest(Request):
    """ extending Flask's request class to limit form uploads to 500 MB """

    max_form_memory_size = 500 * 1024 * 1024


app.request_class = LimitedRequest
app.config.update(
    SECRET_KEY=config.SECRET_KEY,
    PERMANENT_SESSION_LIFETIME=datetime.timedelta(days=14),
    CACHE_TYPE="filesystem",
    CACHE_DIR=config.TEMP_DIR,
    MAIL_SERVER=config.MAIL_SERVER,
    MAIL_PORT=config.MAIL_PORT,
    MAIL_USE_TLS=config.MAIL_USE_TLS,
    MAIL_USE_SSL=config.MAIL_USE_SSL,
    MAIL_USERNAME=config.MAIL_USERNAME,
    MAIL_PASSWORD=config.MAIL_PASSWORD,
    DEFAULT_MAIL_SENDER=config.DEFAULT_MAIL_SENDER,
)
cache.init_app(app)
mail.init_app(app)