Example #1
1
def create_app(config_name="default"):
    app = Flask(__name__, static_folder="static", static_url_path="")
    app.config.from_object(config[config_name])
    app.debug = True
    config[config_name].init_app(app)

    db.init_app(app)

    # attach routes and custom error pages here
    from hacer.api import api as api_blueprint

    app.register_blueprint(api_blueprint, url_prefix="/api")

    @app.route("/")
    def index():
        return app.send_static_file("index.html")

    # start discovery server
    with app.app_context():
        from discovery import run_discovery_server

        app.discovery_thread = Thread(
            target=run_discovery_server, kwargs={"Session": scoped_session(sessionmaker(bind=db.engine))}
        )
        app.discovery_thread.daemon = True
        app.discovery_thread.start()

    app.before_request(create_before_request(app))
    return app
Example #2
1
File: store.py Project: voidfiles/h
def includeme(config):
    app = Flask("annotator")  # Create the annotator-store app
    app.register_blueprint(store.store)  # and register the store api.

    # Set up the models
    settings = config.get_settings()
    if "es.host" in settings:
        app.config["ELASTICSEARCH_HOST"] = settings["es.host"]
    if "es.index" in settings:
        app.config["ELASTICSEARCH_INDEX"] = settings["es.index"]
    es.init_app(app)
    with app.test_request_context():
        Annotation.create_all()
        Document.create_all()

    # Configure authentication and authorization
    app.config["AUTHZ_ON"] = True
    app.before_request(before_request)

    # Configure the API views -- version 1 is just an annotator.store proxy
    api_v1 = wsgiapp2(app)

    config.add_view(api_v1, route_name="api")

    if not config.registry.queryUtility(interfaces.IStoreClass):
        config.registry.registerUtility(Store, interfaces.IStoreClass)
Example #3
1
def create_app(config="config.ProductionDevelopmentConfig"):
    app = Flask(__name__)

    app.config.from_object(config)

    db.init_app(app)

    mixer.init_app(app)

    app.before_request(setup_authomatic(app))
    app.before_request(load_user)

    app.add_url_rule("/", "index", index)

    app.register_blueprint(auth_bp, url_prefix="/auth")
    app.register_blueprint(issues_bp, url_prefix="/issues")
    app.register_blueprint(comments_bp, url_prefix="/comments")
    app.register_blueprint(organizations_bp, url_prefix="/organizations")

    admin = Admin(app)

    # add admin views.
    admin.add_view(AdminView(User, db.session))
    admin.add_view(AdminView(Issue, db.session))
    admin.add_view(AdminView(Comment, db.session))
    admin.add_view(AdminView(Organization, db.session))
    admin.add_view(AdminView(Vote, db.session))

    return app
Example #4
1
def setup_app(warnings=None):
    if warnings is None:
        warnings = []

    app = Flask(__name__)
    cfy_config = config.instance()

    _detect_debug_environment()

    app.logger_name = "manager-rest"
    # setting up the app logger with a rotating file handler, in addition to
    #  the built-in flask logger which can be helpful in debug mode.
    create_logger(
        logger_name=app.logger.name,
        log_level=cfy_config.rest_service_log_level,
        log_file=cfy_config.rest_service_log_path,
        log_file_size_MB=cfy_config.rest_service_log_file_size_MB,
        log_files_backup_count=cfy_config.rest_service_log_files_backup_count,
    )

    # log all warnings passed to function
    for w in warnings:
        app.logger.warning(w)

    # secure the app according to manager configuration
    if cfy_config.security_enabled:
        app.logger.info("initializing rest-service security")
        init_secured_app(app)

    app.before_request(log_request)
    app.after_request(log_response)

    # saving flask's original error handlers
    flask_handle_exception = app.handle_exception
    flask_handle_user_exception = app.handle_user_exception

    api = Api(app)

    # saving flask-restful's error handlers
    flask_restful_handle_exception = app.handle_exception
    flask_restful_handle_user_exception = app.handle_user_exception

    # setting it so that <500 codes use flask-restful's error handlers,
    # while 500+ codes use original flask's error handlers (for which we
    # register an error handler on somewhere else in this module)
    def handle_exception(flask_method, flask_restful_method, e):
        code = getattr(e, "code", 500)
        if code >= 500:
            return flask_method(e)
        else:
            return flask_restful_method(e)

    app.handle_exception = functools.partial(handle_exception, flask_handle_exception, flask_restful_handle_exception)
    app.handle_user_exception = functools.partial(
        handle_exception, flask_handle_user_exception, flask_restful_handle_user_exception
    )

    endpoint_mapper.setup_resources(api)
    return app
def test_noninstrospectable_hooks_dont_crash_everything():
    app = Flask(__name__)

    def do_nothing():
        pass

    app.before_request(partial(do_nothing))

    # It'd crash here
    FlaskInjector(app=app)
Example #6
1
def create_app(config):
    """
    This method is a factory for our Flask app which configures all the
    necessary behavior and register all the blueprints.

    All our views should belong to a blueprint and the blueprints mounted on
    the main App.

    To run our application you need only to instantiate a app using this
    function, given a config object, and call its run method.

    example:

        datalog_app = create_app(my_config_obj)
        datalog_app.run()

    """
    app = Flask("datalog")
    app.config.from_object(config)

    db = config.get_db()

    def call_end_request(response):
        """
        flush pending mongodb requests
        and return the connection to the poll
        """
        db.connection.end_request()
        return response

    def add_db_to_request():
        """
        makes possible to access the db directly from any view
        (possible, but **not encouraged**, avoid doing this)
        """
        g.db = db

    def permanet_sessions():
        """
        makes the session persistent for
        PERMANENT_SESSION_LIFETIME
        """
        session.permanent = True

    app.before_request(add_db_to_request)
    app.before_request(permanet_sessions)
    app.after_request(call_end_request)

    # register blueprints
    app.register_blueprint(app_views)

    connect_models(config)

    return app
Example #7
0
def create_app(config=None):
    app = Flask(__name__)
    app.name = APP_NAME

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

    app.before_request(ensure_session)
    app.register_blueprint(api.blueprint)

    return app
Example #8
0
def _create_app(config):
    app = Flask(__name__)
    api = ExceptionHandlingApi(app)
    api_doc_route = "/api-docs"

    api.add_resource(DataSetSearchResource, config.app_base_path)
    api.add_resource(ApiDoc, api_doc_route)
    api.add_resource(MetadataEntryResource, config.app_base_path + "/<entry_id>")
    api.add_resource(DataSetCountResource, config.app_base_path + "/count")
    api.add_resource(ElasticSearchAdminResource, config.app_base_path + "/admin/elastic")

    security = Security(auth_exceptions=[api_doc_route])
    app.before_request(security.authenticate)

    return app
Example #9
0
    def app(self):
        """ derive flask app based on the combination of command-line
            options and the contents of the .ini files
        """

        ## set flask specific things that are non-optional
        error = (
            lambda k: 'Fatal: You need to specify a "flask" section '
            + 'with an entry like  "'
            + k
            + '=..." in your .ini file'
        )
        try:
            app_name = self["flask.app"]
        except KeyError:
            raise SystemExit(error("app"))
        try:
            secret_key = self["flask.secret_key"]
        except KeyError:
            raise SystemExit(error("secret_key"))
        app = Flask(app_name)
        app.secret_key = secret_key

        ## set flask specific things that are optional
        if "flask.template_path" in self:
            app.jinja_loader = FileSystemLoader(self["template_path"])
        if "flask.before_request" in self:
            before_request = self["flask.before_request"]
            before_request = namedAny(before_request)
            app.before_request(before_request)
        if "flask.after_request" in self:
            after_request = self["flask.after_request"]
            after_request = namedAny(after_request)
            app.after_request(after_request)

        ## setup views
        try:
            view_holder = self["corkscrew.views"]
        except KeyError:
            error = 'Fatal: could not "view=<dotpath>" entry in your .ini file'
            raise SystemExit(error)
        else:
            view_list = namedAny(view_holder)
            [v(app=app, settings=self) for v in view_list]

            return app
Example #10
0
def init_app():
    app = Flask(__name__)
    app.config.from_object(config)
    app.before_request(get_current_user)
    app.before_request(db_session)
    blueprints = Blueprints(app)
    app = blueprints.register()
    login_manager.init_app(app)
    mail = Mail(app)
    Base = declarative_base()
    db = SQLAlchemy(app)

    class UserModify(db.Model, User):
        pass

    db_adapter = SQLAlchemyAdapter(db, UserModify)
    user_manager = UserManager(db_adapter, app)
    return app
Example #11
0
def test_enforce_auth():
    app = Flask(__name__)
    app.config["AUTH_KEY"] = "secretpassword"

    app.before_request(corral.util.enforce_auth)

    @app.route("/admin")
    def admin_panel():
        return "Admin panel.\n"

    with app.test_client() as c:
        rv = c.get("/admin")
        assert b"You must be authenticated" in rv.data
        assert rv.status_code == 403

        rv = c.get("/admin", headers={"Cookie": "key=secretpassword"})
        assert rv.data == b"Admin panel.\n"
        assert rv.status_code == 200
Example #12
0
File: eapp.py Project: Inkvi/ella
def create_app():
    app = Flask(__name__)
    with open("/etc/ella/settings.yml") as f:
        app.config.update(**yaml.load(f))

    ELLIPTICS_HOSTNAME = app.config.get("ELLIPTICS_HOSTNAME")

    if ELLIPTICS_HOSTNAME:
        app.node = init_elliptics(ELLIPTICS_HOSTNAME)
    else:
        app.before_request(before)

    app.add_url_rule("/", "home", view_func=views.home, methods=["GET", "POST"])
    app.add_url_rule("/routing", view_func=views.routing)
    app.add_url_rule("/stats", view_func=views.stats)
    app.add_url_rule("/find", view_func=views.find)
    app.add_url_rule("/download/<string:key>", view_func=views.download)
    return app
Example #13
0
def test_detect_auth():
    app = Flask(__name__)
    app.config["AUTH_KEY"] = "secretpassword"

    app.before_request(corral.util.detect_auth)

    @app.route("/checkauth")
    def check_auth():
        return jsonify({"authed": g.authed})

    with app.test_client() as c:
        rv = c.get("/checkauth")
        data = json.loads(rv.data.decode("utf-8"))
        assert data["authed"] == False

        rv = c.get("/checkauth", headers={"Cookie": "key=secretpassword"})
        data = json.loads(rv.data.decode("utf-8"))
        assert data["authed"] == True
Example #14
0
def create_app(config_object=None):
    app = Flask(__name__)

    app.config.from_object("config.default")
    if config_object:
        app.config.from_object(config_object)

    app.add_url_rule("/", view_func=views.get_apps, methods=["GET"])
    app.add_url_rule("/login", view_func=views.get_login, methods=["GET"])
    app.add_url_rule("/login", view_func=views.do_login, methods=["POST"])
    app.add_url_rule("/logout", view_func=views.do_logout, methods=["GET"])
    app.add_url_rule("/deploy", view_func=views.do_deploy, methods=["POST"])
    app.add_url_rule("/ping/ping", view_func=views.healthcheck, methods=["GET"])
    app.register_error_handler(WBAPIHTTPError, views.wb_error_handler)
    app.register_error_handler(Exception, views.generic_error_handler)
    app.before_request(get_api_before_request)

    return app
Example #15
0
def includeme(config):
    """Include the annotator-store API backend.

    Example INI file:

        [app:h]
        api.key: 00000000-0000-0000-0000-000000000000

    """

    app = Flask("annotator")  # Create the annotator-store app
    app.register_blueprint(store.store)  # and register the store api.

    # Set up the models
    settings = config.get_settings()
    if "es.host" in settings:
        app.config["ELASTICSEARCH_HOST"] = settings["es.host"]
    if "es.index" in settings:
        app.config["ELASTICSEARCH_INDEX"] = settings["es.index"]
    es.init_app(app)
    with app.test_request_context():
        try:
            Annotation.create_all()
        except:
            Annotation.update_settings()
            Annotation.create_all()

    # Configure authentication (ours) and authorization (store)
    authenticator = auth.Authenticator(models.Consumer.get_by_key)

    def before_request():
        g.auth = authenticator
        g.authorize = authz.authorize

    app.before_request(before_request)

    # Configure the API view -- version 1 is just an annotator.store proxy
    config.add_view(wsgiapp2(app), context="h.resources.APIFactory", name="v1")
    config.add_view(wsgiapp2(app), context="h.resources.APIFactory", name="current")

    # And pick up the token view
    config.scan(__name__)
Example #16
0
def create_app(environment="ponyexpress.config.configuration.DefaultConfig"):
    app = Flask(__name__)

    # Load configuration
    app.config.from_object(environment)
    app.config.from_pyfile("/etc/pony-express/ponyexpress.cfg", True)

    # Database
    from ponyexpress.database import db

    db.init_app(app)

    # Register blueprints
    from ponyexpress.api.v1.collector import collector
    from ponyexpress.api.v1.query import query
    from ponyexpress.api.v1.updater import updater

    app.register_blueprint(collector)
    app.register_blueprint(query)
    app.register_blueprint(updater)

    # Error handler
    app.register_error_handler(InvalidAPIUsage, handle_invalid_usage)

    if app.debug is not True and app.testing is not True:
        import logging

        from logging.handlers import RotatingFileHandler

        file_handler = RotatingFileHandler(
            app.config.get("REQUEST_LOG", "ponyexpress.log"), maxBytes=1024 * 1024 * 100, backupCount=20
        )
        file_handler.setLevel(logging.INFO)

        formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        file_handler.setFormatter(formatter)

        app.logger.addHandler(file_handler)

        app.before_request(log_entry)

    return app
Example #17
0
class RestProvider(APIProvider):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.app = Flask("iris-rest")

        # Make sure we have config
        if "rest" not in self.daemon.config.providers:
            raise Exception("No config for RestProvider (need config.providers.rest)")

        self.config = self.daemon.config.providers["rest"]

        # Grab config vars
        self.host = self.config.get("host", "0.0.0.0")
        self.port = self.config.get("port", "8080")
        self.auth = self.config.get("auth")

        # Meta Registers
        self.app.register_error_handler(APIBase, self.handle_response)
        self.app.before_request(self.before_request)

        self.app.add_url_rule("/", "index", self.route_index)

        # Controllers
        self.app.register_blueprint(ShardController(self).bp)
        self.app.register_blueprint(EntryController(self).bp)

    def before_request(self):
        if self.auth and request.headers.get("IRIS_AUTH") != self.auth:
            raise APIError("Invalid Credentials", 1000)

    def handle_response(self, obj):
        return jsonify(obj.data)

    def run(self):
        super().run()
        self.app.run(host=self.host, port=self.port)

    def route_index(self):
        raise APIResponse(
            {"stats": {"uptime": float("{0:.4f}".format(time.time() - self.daemon.start_time))}, "version": __VERSION__}
        )
Example #18
0
def create_app():
    log.debug("Creating %s application", __name__)
    app = Flask(__name__)

    configure(app)

    # Configure database
    db.init_app(app)

    # Configure mailer
    mail.init_app(app)
    app.extensions["mail"] = mail

    # Configure ES
    es.init_app(app)

    # Add regex converter
    from annotateit.util import RegexConverter

    app.url_map.converters["regex"] = RegexConverter

    # Add filters
    from annotateit.util import filters

    for name, func in vars(filters).iteritems():
        if not name.startswith("_"):
            app.template_filter()(func)

    # Mount views
    from annotator import store
    from annotateit import user, main

    app.register_blueprint(store.store, url_prefix="/api")
    app.register_blueprint(user.user, url_prefix="/user")
    app.register_blueprint(main.main)

    app.before_request(main.before_request)
    app.errorhandler(404)(main.page_not_found)
    app.errorhandler(401)(main.not_authorized)

    log.debug("Successfully created %s application", __name__)
    return app
Example #19
0
def create_app():
    app = Flask(__name__)

    # 加载配置
    from .config import Config
    from .extensions import db

    app.config.from_object(Config)
    db.init_app(app)

    # 注册蓝图
    from .api import api_bp
    from .views import home

    app.register_blueprint(api_bp)
    app.register_blueprint(home)

    # 注册钩子方法
    app.before_request(init_user)
    return app
Example #20
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 #21
0
File: komoo.py Project: it3s/komoo
def create_app(config):
    """
    This method is a factory for our Flask app which configures all the
    necessary behavior and register all the blueprints.

    All our views should belong to a blueprint and the blueprints mounted on
    the main App.

    To run our application you need only to instantiate a app using this
    function, given a config object, and call its run method.

    example:

        komoo_app = create_app(my_config_obj)
        komoo_app.run()

    """
    app = Flask("komoo")
    app.config.from_object(config)

    db = config.get_db()

    # flush pending mongodb requests
    def call_end_request(response):
        db.connection.end_request()
        return response

    # makes possible to access the db directly from any view
    # (possible, but **not encouraged**, avoid doing this)
    def add_db_to_request():
        g.db = db

    app.before_request(add_db_to_request)
    app.after_request(call_end_request)

    # register all blueprints
    for bp in blueprints:
        app.register_blueprint(bp[0], url_prefix=bp[1])

    return app
Example #22
0
def create_app(config_file):
    app = Flask(__name__)

    # configuration settings are loaded from the `config.py` module
    # and (optionally) from a file `XSNIPPET_SETTINGS` env var points to
    app.config.from_pyfile(config_file)
    app.config.from_envvar("XSNIPPET_WEBUI_SETTINGS", silent=True)

    # set jinja2 global vars to be used in all templates
    app.jinja_env.globals.update(
        {"title": app.config["TITLE"], "abs_url_for": abs_url_for, "lang_by_short_name": lang_by_short_name}
    )
    # set assets env
    assets.Environment(app)

    app.register_blueprint(webui)

    # register all needed hooks
    app.before_request(create_http_object)

    # create cache connection (it's thread-safe)
    app.cache = create_cache_connection(app, key_prefix="webui_")

    return app
Example #23
0
from flask import Flask, request, render_template, jsonify
from flask_request_params import bind_request_params

import urllib
import json

myList = []
a = "features"
b = "properties"
c = "title"

app = Flask(__name__)
app.secret_key = "secret"
# bind rails like params to request.params
app.before_request(bind_request_params)

# Default route
@app.route("/")
def simple():
    return "Test Page"


# just return request.params
@app.route("/api/vi", methods=["GET"])
def getQ():
    global myList
    x = request.args.get("a")

    with open("symp.json") as json_file:
        theJSON = json.load(json_file)
        str = ""
Example #24
0
File: api.py Project: roc/backdrop

def setup_logging():
    log_handler.set_up_logging(app, "read", getenv("GOVUK_ENV", "development"))


app = Flask(__name__)

# Configuration
app.config.from_object("backdrop.read.config.%s" % getenv("GOVUK_ENV", "development"))

db = database.Database(app.config["MONGO_HOST"], app.config["MONGO_PORT"], app.config["DATABASE_NAME"])

setup_logging()

app.before_request(create_request_logger(app))
app.after_request(create_response_logger(app))


class JsonEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, ObjectId):
            return str(obj)
        if isinstance(obj, datetime.datetime):
            return obj.isoformat()
        return json.JSONEncoder.default(self, obj)


def raw_queries_allowed(bucket_name):
    raw_queries_config = app.config.get("RAW_QUERIES_ALLOWED", {})
    return bool(raw_queries_config.get(bucket_name, False))
Example #25
0
def create_app():
    from config import configs

    application = Flask(__name__)

    application.config.from_object(configs[os.environ["NOTIFY_ENVIRONMENT"]])

    init_app(application)
    statsd_client.init_app(application)
    logging.init_app(application, statsd_client)
    init_csrf(application)
    request_id.init_app(application)

    service_api_client.init_app(application)
    user_api_client.init_app(application)
    api_key_api_client.init_app(application)
    job_api_client.init_app(application)
    notification_api_client.init_app(application)
    status_api_client.init_app(application)
    invite_api_client.init_app(application)
    template_statistics_client.init_app(application)
    events_api_client.init_app(application)
    provider_client.init_app(application)
    organisations_client.init_app(application)

    login_manager.init_app(application)
    login_manager.login_view = "main.sign_in"
    login_manager.login_message_category = "default"
    login_manager.session_protection = None

    from app.main import main as main_blueprint

    application.register_blueprint(main_blueprint)

    from .status import status as status_blueprint

    application.register_blueprint(status_blueprint)

    proxy_fix.init_app(application)

    application.session_interface = ItsdangerousSessionInterface()

    application.add_template_filter(format_datetime)
    application.add_template_filter(format_datetime_24h)
    application.add_template_filter(format_datetime_normal)
    application.add_template_filter(format_datetime_short)
    application.add_template_filter(format_time)
    application.add_template_filter(syntax_highlight_json)
    application.add_template_filter(valid_phone_number)
    application.add_template_filter(linkable_name)
    application.add_template_filter(format_date)
    application.add_template_filter(format_date_normal)
    application.add_template_filter(format_date_short)
    application.add_template_filter(format_datetime_relative)
    application.add_template_filter(format_delta)
    application.add_template_filter(format_notification_status)
    application.add_template_filter(format_notification_status_as_time)
    application.add_template_filter(format_notification_status_as_field_status)
    application.add_template_filter(format_notification_status_as_url)

    application.after_request(useful_headers_after_request)
    application.after_request(save_service_after_request)
    application.before_request(load_service_before_request)

    @application.context_processor
    def _attach_current_service():
        return {"current_service": current_service}

    register_errorhandlers(application)

    setup_event_handlers()

    return application
Example #26
0
from functools import wraps
from flask import Flask, g, request, render_template, make_response, jsonify, abort

from lib import PING_PERIOD, ARCHIVE_PERIOD, IP_BAN_PERIOD, CHAT_FLAGS, get_time
from lib.api import ping, change_state, disconnect, get_online_state
from lib.groups import MOD_GROUPS, GROUP_RANKS, MINIMUM_RANKS
from lib.messages import send_message, get_userlists, parse_messages
from lib.requests import connect_redis, create_chat_session, set_cookie, disconnect_redis

app = Flask(__name__)

# Pre and post request stuff
app.before_request(connect_redis)
app.before_request(create_chat_session)
app.after_request(set_cookie)
app.after_request(disconnect_redis)

# Decorators


def mark_alive(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        g.joining = ping(g.redis, request.form["chat"], g.user, g.chat_type)
        return f(*args, **kwargs)

    return decorated_function


# Views
Example #27
0
from lib.messages import parse_line
from lib.model import Log, LogPage
from lib.requests import connect_mysql, disconnect_mysql

from werkzeug.contrib.fixers import ProxyFix

app = Flask(__name__)

# Export config
app.config["PROPAGATE_EXCEPTIONS"] = True
app.config["EXPORT_URL"] = os.environ.get("EXPORT_URL", "http://unsupportedlogs.msparp.com")

app.wsgi_app = ProxyFix(app.wsgi_app, 2)

# Pre and post request stuff
app.before_request(connect_mysql)
app.teardown_request(disconnect_mysql)

# Chat


@app.route("/chat")
@app.route("/chat/<chat>")
def chat(chat=None):
    if chat is None:
        return redirect(url_for("configure"))
    return redirect(url_for("view_log", chat=chat))


@app.route("/logs/group/<chat>")
def old_view_log(chat):
Example #28
0
File: app.py Project: GTxx/youjiao
def create_app():
    app = Flask(__name__)
    app.config.from_object(youjiao_config)

    # flask_sqlalchemy
    # import ipdb; ipdb.set_trace()
    db.init_app(app)

    # flask_redis
    redis_cli.init_app(app)

    # flask_debug
    if app.config.get("DEBUG"):
        DebugToolbarExtension(app)

    # flask_login
    login_manager.user_loader(load_user)
    login_manager.login_view = "user_view.login"
    login_manager.init_app(app)

    # flask_jwt
    jwt.init_app(app)

    # flask_principal
    Principal(app)
    identity_loaded.connect_via(app)(_on_identity_loaded)

    # flask_wtf csrf
    csrf = CsrfProtect()
    csrf.init_app(app)
    app.before_request(check_csrf(csrf))

    # flask_babel
    Babel(app)

    # flask_limiter
    limiter.init_app(app)

    # flask_qiniu
    flask_qiniu.init_app(app)

    # flask_admin
    admin.init_app(app)

    # register blueprint
    app.register_blueprint(content_bp)

    app.register_blueprint(user_bp)

    app.register_blueprint(user_api_bp)

    # import ipdb; ipdb.set_trace()
    app.register_blueprint(book_bp)
    app.register_blueprint(book_api_bp)
    app.register_blueprint(user_util_api_bp)
    app.register_blueprint(media_bp)
    app.register_blueprint(online_course_bp)

    # register subscriber
    user_connect(app)

    # register home page
    app.add_url_rule("/", "index", index)

    with open(os.path.join(os.getcwd(), "youjiao/static/assets.json.py"), "r") as assets:
        app.assets = json.load(assets)

    return app
Example #29
0
class Phial(object):
    def __init__(self, appname, settings="settings"):
        self.__appname = appname
        self.__settings = __import__("%s.%s" % (appname, settings), fromlist=[settings.split(".")[1:]])
        self.__flask = None
        self.__celery = None

    def __default_debug_404(self, error):
        from flask import request
        from . import __version__ as phial_version

        return (
            render_template(
                "phial/default_debug_404.html",
                phial_version=phial_version,
                error=error,
                method=request.method,
                path=request.path,
                lst_route=self.__flask.url_map.iter_rules(),
            ),
            404,
        )

    def __default_welcome(self):
        from . import __version__ as phial_version

        return render_template("phial/default_welcome.html", phial_version=phial_version)

    def initApp(self, **kwargs):
        # Initialize Flask
        self.__flask = Flask(
            import_name=self.__appname,
            template_folder=self.__settings.FLASK_TEMPLATES_DIR,
            static_folder=self.__settings.FLASK_STATIC_DIR,
            **kwargs
        )
        self.__flask.secret_key = self.__settings.SECRET_KEY

        # Init G
        from . import g

        setattr(g, "__cur_phial", self)
        setattr(g, "__settings", self.__settings)

        # WSGI support
        self.__flask.wsgi_app = ProxyFix(self.__flask.wsgi_app)

        # Fix UTF-8 issue on python 2.x
        if sys.version_info[0] < 3:
            reload(sys)
            sys.setdefaultencoding("utf-8")

        # Add regex on Flask URL map
        self.__flask.url_map.converters["regex"] = FlaskURLMapRegexConverter

        # Init Peewee
        from .peewee_tools import base_model as peewee_bm

        if peewee_bm.BaseModel is not None and getattr(self.__settings, "DATABASE_CONN_STRING", None) is not None:
            if self.__settings.DATABASE_CONN_STRING.startswith("mysql://") is True:
                # Load lib
                try:
                    from peewee import MySQLDatabase
                except ImportError:
                    print("[Phial][ERRO] MySQL driver is not installed (pip install MySQL-python or PyMySQL)")
                    sys.exit(1)
                peewee_bm.gl_database_type = 1
                hdl = MySQLDatabase(None)

                # Override Peewee init to work with connstring
                from .peewee_tools import peewee_overrided_database_init
                from peewee import Database

                funcType = type(Database.init)
                hdl.init = funcType(peewee_overrided_database_init, hdl, Database)

                # Register to Proxy
                peewee_bm.gl_database.initialize(hdl)
            elif self.__settings.DATABASE_CONN_STRING.startswith("sqlite") is True:
                # Load lib
                try:
                    from peewee import SqliteDatabase
                except ImportError:
                    print("[Phial][ERRO] sqlite3 is not installed")
                    sys.exit(1)
                peewee_bm.gl_database_type = 2
                hdl = SqliteDatabase(None)

                # Override Peewee init to work with connstring
                from .peewee_tools import peewee_overrided_database_init
                from peewee import Database

                funcType = type(Database.init)
                hdl.init = funcType(peewee_overrided_database_init, hdl, Database)

                # Register to Proxy
                peewee_bm.gl_database.initialize(hdl)
            else:
                print("[Phial][ERRO] Database backend not supported")
                sys.exit(1)

            # Init Database
            peewee_bm.gl_database.init(self.__settings.DATABASE_CONN_STRING)

        # Session handler
        if (
            getattr(self.__settings, "FLASK_SESSION_HANDLER", None)
            and getattr(self.__settings, "FLASK_SESSION_HANDLER_CFG", None)
        ) is not None:
            try:
                mod_path = self.__settings.FLASK_SESSION_HANDLER.rsplit(".", 1)[0]
                class_name = self.__settings.FLASK_SESSION_HANDLER.split(".")[-1]
                hdl = __import__(mod_path, fromlist=[mod_path.split(".")[-1]])
                sess_handler = getattr(hdl, class_name)
                try:
                    self.__flask.session_interface = sess_handler(**self.__settings.FLASK_SESSION_HANDLER_CFG)
                except:
                    print("[Phial][ERRO] Session handler is misconfigured")
                    sys.exit(1)
            except (ImportError, AttributeError) as e:
                print('[Phial][ERRO] Can\'t load session backend "%s": %s' % (self.__settings.FLASK_SESSION_HANDLER, e))
                sys.exit(1)

        # Load user-defined routes
        try:
            url_map = __import__("%s.routes" % self.__appname, fromlist=["routes"])
            for u in getattr(url_map, "routes", []):
                try:
                    try:
                        self.__flask.add_url_rule(u[0], view_func=u[1], methods=u[2], defaults=u[3])
                    except IndexError:
                        self.__flask.add_url_rule(u[0], view_func=u[1], methods=u[2])
                except AttributeError:
                    print("[Phial][WARN] Ignoring bad route entry: %s" % str(u))
            for u in getattr(url_map, "errors", []):
                self.__flask.error_handler_spec[None][u[0]] = u[1]
        except ImportError:
            try:
                from cStringIO import StringIO
            except ImportError:
                from StringIO import StringIO
            import traceback

            stream_output = StringIO()
            traceback.print_exc(file=stream_output)
            print('[Phial][ERRO] File "%s.routes" does not exist or contain some errors...' % (self.__appname))
            print(stream_output.getvalue())
            sys.exit(1)

        # Set default welcome page if user-defined routes map is empty
        if len(self.__flask.url_map._rules) < 2:
            from os.path import dirname, join

            self.__flask.template_folder = join(dirname(__file__), "assets/templates")
            self.__flask.static_folder = join(dirname(__file__), "assets/static")
            self.__flask.add_url_rule("/", view_func=self.__default_welcome, methods=["GET"])

        # If application DEBUG==True -> redefine 404 error page
        if self.__settings.FLASK_DEBUG is True:
            self.__flask.error_handler_spec[None][404] = self.__default_debug_404

        # Jinja2 DEBUG
        self.__flask.jinja_env.globals.update({"DEBUG": self.__settings.FLASK_DEBUG})

        # Jinja2 built-in extensions
        self.__flask.jinja_env.add_extension("jinja2.ext.do")
        self.__flask.jinja_env.add_extension("jinja2.ext.with_")
        self.__flask.jinja_env.add_extension("jinja2.ext.i18n")
        self.__flask.jinja_env.add_extension("phial.jinja_tools.ext.SelectiveHTMLCompress")
        self.__flask.jinja_env.add_extension("phial.jinja_tools.ext.DatetimeExtension")

        # Jinja2 i18n callables
        self.__flask.jinja_env.install_gettext_callables(
            lambda x: jinja_get_translation_engine().ugettext(x),
            lambda s, p, n: jinja_get_translation_engine().ungettext(s, p, n),
            newstyle=True,
        )

        # Jinja2 user-defined extensions
        mod_path = getattr(self.__settings, "JINJA_CUSTOM_EXTENSION_DIR", "%s.phial.jinja.extension" % self.__appname)
        try:
            hdl = __import__(mod_path, fromlist=[mod_path.split(".")[-1]])
            for im in getattr(hdl, "__all__", []):
                try:
                    self.__flask.jinja_env.add_extension("%s.%s" % (mod_path, im))
                except AttributeError:
                    print('[Phial][WARN] Extension "%s.%s" does not exist' % (mod_path, im))
        except ImportError:
            pass

        # Jinja2 user-defined filters
        mod_path = getattr(self.__settings, "JINJA_CUSTOM_FILTER_DIR", "%s.phial.jinja.filter" % self.__appname)
        try:
            hdl = __import__(mod_path, fromlist=[mod_path.split(".")[-1]])
            for im in getattr(hdl, "__all__", []):
                item_hdl = getattr(hdl, im, None)
                if item_hdl is not None:
                    self.__flask.jinja_env.filters.update({im: item_hdl})
                else:
                    print('[Phial][WARN] Filter "%s.%s" does not exist' % (mod_path, im))
        except ImportError:
            pass

        # Jinja2 user-defined functions
        mod_path = getattr(self.__settings, "JINJA_CUSTOM_FUNCTION_DIR", "%s.phial.jinja.function" % self.__appname)
        try:
            hdl = __import__(mod_path, fromlist=[mod_path.split(".")[-1]])
            for im in getattr(hdl, "__all__", []):
                item_hdl = getattr(hdl, im, None)
                if item_hdl is not None:
                    self.__flask.jinja_env.globals.update({im: item_hdl})
                else:
                    print('[Phial][WARN] Function "%s.%s" does not exist' % (mod_path, im))
        except ImportError:
            pass

        # Register before & after callback
        from .flask_tools.callback import flask_before_url_remove_trailing_slash, flask_before_i18n_set_user_language
        from .flask_tools.callback import flask_before_peewee_connect, flask_after_peewee_close

        self.__flask.before_request(flask_before_url_remove_trailing_slash)
        self.__flask.before_request(flask_before_peewee_connect)
        self.__flask.before_request(flask_before_i18n_set_user_language)
        self.__flask.after_request(flask_after_peewee_close)
        for im in getattr(self.__settings, "FLASK_REQUEST_CALLBACK", []):
            try:
                mod_path = im[1].rsplit(".", 1)[0]
                class_name = im[1].split(".")[-1]
                hdl = __import__(mod_path, fromlist=[mod_path.split(".")[-1]])
                call_hdl = getattr(hdl, class_name)
                if im[0] == "before":
                    self.__flask.before_request(call_hdl)
                elif im[0] == "after":
                    self.__flask.after_request(call_hdl)
            except (ImportError, AttributeError) as e:
                print('[Phial][WARN] Can\'t load flask callback "%s": %s' % (im[1], e))
            except IndexError:
                print("[Phial][ERRO] FLASK_REQUEST_CALLBACK is misconfigured: %s" % e)
                sys.exit(1)

        # Register Celery (if lib is installed) and settings OK
        if getattr(self.__settings, "CELERY_BROKER_URL", None) is not None:
            try:
                from celery import Celery
            except ImportError:
                print("[Phial][ERRO] Celery is not installed (pip install -U celery)")
                sys.exit(1)
            else:
                self.__flask.config.update(
                    CELERY_BROKER_URL=self.__settings.CELERY_BROKER_URL,
                    CELERY_RESULT_BACKEND=getattr(self.__settings, "CELERY_RESULT_BACKEND"),
                    CELERY_ACCEPT_CONTENT=getattr(self.__settings, "CELERY_ACCEPT_CONTENT"),
                )
                self.__celery = Celery(
                    main=self.__flask.import_name,
                    broker=self.__flask.config["CELERY_BROKER_URL"],
                    backend=self.__flask.config["CELERY_RESULT_BACKEND"],
                )
                self.__celery.config_from_object(self.__flask.config)

                # Override Task to set the Flask app context
                TaskBase = self.__celery.Task

                class ContextTask(TaskBase):
                    abstract = True

                    def __call__(self, *args, **kwargs):
                        from . import current_phial

                        with current_phial.flaskapp.app_context():
                            return TaskBase.__call__(self, *args, **kwargs)

                setattr(self.__celery, "Task", ContextTask)

                # Register to globals
                setattr(g, "__celery", self.__celery)

                # Register tasks
                mod_path = getattr(self.__settings, "CELERY_CUSTOM_TASKS_DIR", "%s.celery" % self.__appname)
                try:
                    hdl = __import__(mod_path, fromlist=[mod_path.split(".")[-1]])
                    for im in getattr(hdl, "__all__", []):
                        item_hdl = getattr(hdl, im, None)
                        if item_hdl is not None:
                            self.__celery.tasks.register(item_hdl)
                        else:
                            print('[Phial][WARN] Async task "%s.%s" does not exist' % (mod_path, im))
                except ImportError as e:
                    print("[Phial][ERRO] Can't load celery async tasks: %s" % e)
                    sys.exit(1)

        # Register error handlers (RELEASE MODE ONLY)
        if (
            self.__settings.FLASK_DEBUG is False
            and len(self.__settings.ADMINS) > 0
            and len(self.__settings.MAIL_USERNAME) > 0
        ):
            hMailHandler = SMTPHandler(
                (self.__settings.MAIL_SMTP, self.__settings.MAIL_SMTP_PORT),
                self.__settings.MAIL_USERNAME,
                [a[1] for a in self.__settings.ADMINS],
                self.__settings.LOGGING_MAIL_TITLE,
                (self.__settings.MAIL_USERNAME, self.__settings.MAIL_PASSWORD),
            )
            if getattr(self.__settings, "LOGGING_MAIL_TEMPLATE", None) is not None:
                hMailHandler.setFormatter(Formatter(self.__settings.LOGGING_MAIL_TEMPLATE))
            hMailHandler.setLevel(ERROR)
            self.__flask.logger.addHandler(hMailHandler)
        hFileHandler = RotatingFileHandler(
            self.__settings.LOGGING_FILE_FILENAME,
            "a",
            self.__settings.LOGGING_FILE_MAXSIZE,
            self.__settings.LOGGING_FILE_NBROTATE,
        )
        if getattr(self.__settings, "LOGGING_FILE_TEMPLATE", None) is not None:
            hFileHandler.setFormatter(Formatter(self.__settings.LOGGING_FILE_TEMPLATE))
        hFileHandler.setLevel(ERROR)
        self.__flask.logger.addHandler(hFileHandler)

    @property
    def appname(self):
        return self.__appname

    @property
    def flaskapp(self):
        return self.__flask

    @property
    def celery(self):
        return self.__celery

    @property
    def settings(self):
        return self.__settings

    def startApp(self):
        # Create arguments parser
        parser = argparse.ArgumentParser(prog="phial")

        # Add built-in modules and retrieve user-defined modules
        lst_management = [("help", parser.print_help, False)]
        mod_path = "phial.phial_management"
        try:
            hdl = __import__(mod_path, fromlist=[mod_path.split(".")[-1]])
            for im in getattr(hdl, "__all__", []):
                item_hdl = getattr(hdl, im, None)
                if item_hdl is not None:
                    lst_management.append((item_hdl.initParser(parser), item_hdl, True))
                else:
                    print('[Phial][WARN] Management class "%s.%s" does not exist' % (mod_path, im))
        except ImportError:
            pass
        mod_path = getattr(self.__settings, "PHIAL_CUSTOM_MANAGEMENT_DIR", "%s.phial.management" % self.__appname)
        try:
            hdl = __import__(mod_path, fromlist=[mod_path.split(".")[-1]])
            for im in getattr(hdl, "__all__", []):
                item_hdl = getattr(hdl, im, None)
                if item_hdl is not None:
                    lst_management.append((item_hdl.initParser(parser), item_hdl, True))
                else:
                    print('[Phial][WARN] Management class "%s.%s" does not exist' % (mod_path, im))
        except ImportError:
            pass

        # Check arguements and run command
        from .flask_tools.callback import flask_before_i18n_set_user_language

        res = vars(parser.parse_args())
        for m in lst_management:
            if res.get(m[0], None) is not None:
                if m[0] != "server":
                    with self.__flask.test_request_context():
                        flask_before_i18n_set_user_language("en")
                        if m[1]() if m[2] is False else m[1]().run(self, res) is True:
                            break
                else:
                    if m[1]() if m[2] is False else m[1]().run(self, res) is True:
                        break

    def runServer(self):
        self.__flask.run(
            host=self.__settings.FLASK_LISTEN_ADDRESS,
            port=self.__settings.FLASK_LISTEN_PORT,
            debug=self.__settings.FLASK_DEBUG,
            use_reloader=self.__settings.FLASK_USE_RELOADER,
            threaded=getattr(self.__settings, "FLASK_THREADED_DEBUG_SERVER", False),
        )
Example #30
0
from social.apps.flask_app.template_filters import backends

from apiclient import discovery
from httplib2 import Http
from oauth2client.client import AccessTokenCredentials
from twilio.rest import TwilioRestClient
from twilio.twiml import Response


app = Flask("MailSMS")
app.config.from_object("settings")
db.init_app(app)

app.login_manager = LoginManager(app)
app.login_manager.user_callback = load_user
app.before_request(register)

app.register_blueprint(social_auth, url_prefix="/social")
app.context_processor(backends)
init_social(app, db.session)


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


@app.route("/main")
def main():
    return render_template("main.html", number=app.config["TWILIO_NUMBER"])