Esempio n. 1
0
def create_app(config_class=Config):
    app = Flask(__name__)

    from flaskblog.users.routes import users
    from flaskblog.posts.routes import posts
    from flaskblog.main.routes import main
    from flaskblog.categories.routes import categories
    from flaskblog.errors.handlers import errors

    app.config.from_object(Config)
    app.register_blueprint(users)
    app.register_blueprint(posts)
    app.register_blueprint(main)
    app.register_blueprint(errors)
    app.register_blueprint(categories)

    db.init_app(app)

    with app.app_context():
        db.create_all()

    bcrypt.init_app(app)
    login_manager.init_app(app)
    md = Misaka(footnotes=True, tables=True)
    md.init_app(app)

    return app
Esempio n. 2
0
def init_app(app):
    # We load configurations first from the config file (where some options
    # are overridable via environment variables) or from the config file
    # pointed to by the MEASUREMENTS_CONFIG environment variable.
    # The later overrides the former.
    app.config.from_object('measurements.config')
    app.config.from_envvar('MEASUREMENTS_CONFIG', silent=True)

    app.logger.addHandler(logging.StreamHandler())

    if app.config['APP_ENV'] == 'production':
        app.logger.setLevel(logging.WARNING)
    elif app.config['APP_ENV'] == 'development':
        app.logger.setLevel(logging.DEBUG)
        # Set the jinja templates to reload when in development
        app.jinja_env.auto_reload = True
        app.config['TEMPLATES_AUTO_RELOAD'] = True
        app.config['DEBUG'] = True
    elif app.config['APP_ENV'] not in (
            'testing', 'staging'):  # known envs according to Readme.md
        raise RuntimeError('Unexpected APP_ENV', app.config['APP_ENV'])

    for key in app.config.keys():
        SECRET_SUBSTRINGS = ["_SECRET_", "DATABASE_URL"]
        # Do not log, even in debug, anything containing the word "SECRET" or "DATABASE_URL"
        if any([s in key for s in SECRET_SUBSTRINGS]):
            continue
        app.logger.debug("{}: {}".format(key, app.config[key]))

    md = Misaka(fenced_code=True)
    md.init_app(app)

    CORS(app, resources={r"/api/*": {"origins": "*"}})
Esempio n. 3
0
def init_app(app):
    # We load configurations first from the config file (where some options
    # are overridable via environment variables) or from the config file
    # pointed to by the MEASUREMENTS_CONFIG environment variable.
    # The later overrides the former.
    app.config.from_object('measurements.config')
    app.config.from_envvar('MEASUREMENTS_CONFIG', silent=True)

    app.logger.addHandler(logging.StreamHandler())

    if app.config['APP_ENV'] == 'production':
        app.logger.setLevel(logging.WARNING)
    elif app.config['APP_ENV'] == 'development':
        app.logger.setLevel(logging.DEBUG)

    # Set the jinja templates to reload when in development
    if app.config['APP_ENV'] == 'development':
        app.jinja_env.auto_reload = True
        app.config['TEMPLATES_AUTO_RELOAD'] = True

    for key in app.config.keys():
        # Do not log, even in debug, anything containing the work "SECRET"
        if "SECRET" in key:
            continue
        app.logger.debug("{}: {}".format(key, app.config[key]))

    md = Misaka(fenced_code=True)
    md.init_app(app)

    CORS(app, resources={r"/api/*": {"origins": "*"}})

    cache.init_app(app, config=app.config['CACHE_CONFIG'])
Esempio n. 4
0
File: app.py Progetto: cyBerta/api
def init_app(app, testmode=False):
    # We load configurations first from the config file (where some options
    # are overridable via environment variables) or from the config file
    # pointed to by the MEASUREMENTS_CONFIG environment variable.
    # The later overrides the former.
    app.config.from_object("measurements.config")
    app.config.from_envvar("MEASUREMENTS_CONFIG", silent=True)

    # Prevent messy duplicate logs during testing
    if not testmode:
        app.logger.addHandler(logging.StreamHandler())

    if app.config["APP_ENV"] == "production":
        app.logger.setLevel(logging.WARNING)
    elif app.config["APP_ENV"] == "development":
        app.logger.setLevel(logging.DEBUG)
        # Set the jinja templates to reload when in development
        app.jinja_env.auto_reload = True
        app.config["TEMPLATES_AUTO_RELOAD"] = True
        app.config["DEBUG"] = True
    elif app.config["APP_ENV"] not in (
            "testing",
            "staging",
    ):  # known envs according to Readme.md
        raise RuntimeError("Unexpected APP_ENV", app.config["APP_ENV"])

    for key in app.config.keys():
        SECRET_SUBSTRINGS = ["_SECRET_", "DATABASE_URL"]
        # Do not log, even in debug, anything containing the word "SECRET" or "DATABASE_URL"
        if any([s in key for s in SECRET_SUBSTRINGS]):
            continue
        app.logger.debug("{}: {}".format(key, app.config[key]))

    if app.config["APP_ENV"] == "production":
        sentry_sdk.init(
            dsn="https://[email protected]/1367288",
            integrations=[FlaskIntegration()],
        )
        # TODO Temporary workaround to ignore flask-limiter logs due to:
        # https://github.com/ooni/api/issues/145 &
        # https://github.com/alisaifee/flask-limiter/issues/186
        ignore_logger("flask-limiter")

    md = Misaka(fenced_code=True)
    md.init_app(app)

    CORS(app, resources={r"/api/*": {"origins": "*"}})
Esempio n. 5
0
def create_app(config_class=Config):
    md = Misaka(tables=True, hard_wrap=True)
    app = Flask(__name__)
    md.init_app(app)
    app.config.from_object(Config)

    db.init_app(app)
    bcrypt.init_app(app)
    login_manager.init_app(app)
    mail.init_app(app)

    from flasksite.errors.handlers import errors
    from flasksite.users.routes import users
    from flasksite.posts.routes import posts
    from flasksite.main.routes import main
    app.register_blueprint(errors)
    app.register_blueprint(users)
    app.register_blueprint(posts)
    app.register_blueprint(main)

    return app
Esempio n. 6
0
import psycopg2.extras
import pg2geojson
from flask_misaka import Misaka
from werkzeug.urls import url_unquote_plus
from datetime import datetime, timedelta
from jinja2 import ChoiceLoader, FileSystemLoader
from flask import Flask, render_template, request, make_response, url_for, send_from_directory
from flask_cors import CORS

import logging
from logging import StreamHandler

# Define the Flask app and add support for Markdown in templates
app = Flask(__name__)
md = Misaka(tables=True, autolink=True, toc=True)
md.init_app(app)

# Exposes all resources matching /developmentcontrol/* to CORS
CORS(app, resources=r'/developmentcontrol/*', allowed_headers=['Content-Type', 'X-Requested-With'])

# Configure logging to stderr
log_handler = StreamHandler()
log_handler.setLevel(logging.INFO)
app.logger.addHandler(log_handler)

# Add the to the template search path so that we can treat our built hubmap.js
# as a template without having to manually copy it to the standard template
# directory
DIST_DIR = os.path.join(app.static_folder, 'hubmap/dist')
template_loader = ChoiceLoader([
    app.jinja_loader,
Esempio n. 7
0
 def test_init(self):
     md = Misaka()
     app2 = Flask(__name__)
     md.init_app(app2)
     self.assertIn("markdown", app2.jinja_env.filters)
Esempio n. 8
0
def create_app(config="app.config"):
    app = Flask(__name__)
    with app.app_context():
        app.config.from_object(config)
        app.jinja_loader = BlogthemeLoader(os.path.join(
            app.root_path, app.template_folder),
                                           followlinks=True)

        from app.models import db, Users

        url = make_url(app.config['SQLALCHEMY_DATABASE_URI'])
        if url.drivername == 'postgres':
            url.drivername = 'postgresql'

        db.init_app(app)

        try:
            if not (url.drivername.startswith('sqlite')
                    or database_exists(url)):
                create_database(url)
            db.create_all()
        except OperationalError:
            db.create_all()
        else:
            db.create_all()

        app.db = db
        cache.init_app(app)
        app.cache = cache
        app.debug = False

        configure_uploads(app, photos)

        redis_store = FlaskRedis()
        redis_store.init_app(app)
        login_manager = LoginManager()
        login_manager.session_protection = 'strong'
        login_manager.login_view = 'auth.oauth'
        login_manager.init_app(app)

        toolbar = DebugToolbarExtension(app)
        #toolbar.DEBUG_TB_INTERCEPT_REDIRECTS = False
        md = Misaka()
        md.init_app(app)
        Analytics(app)
        app.config['ANALYTICS']['GAUGES']['SITE_ID'] = 'XXXXXXXXXXXXX'
        if not get_config('blog_theme'):
            set_config('blog_theme', 'blog')

        from app.views import views
        from app.utils import init_errors, init_utils, init_logs
        from app.post import blog
        from app.auth import auth
        from app.admin import admin
        from app.status import web
        #from app.api import
        init_errors(app)
        init_utils(app)
        init_logs(app)

        app.register_blueprint(views)
        app.register_blueprint(blog)
        app.register_blueprint(auth)
        app.register_blueprint(admin)
        app.register_blueprint(web)

        @login_manager.user_loader
        def load_user(user_id):
            try:
                return Users.query.get(int(user_id))
            except Users.DoesNotExist:
                return None

        return app
Esempio n. 9
0
# password hashing
bcrypt = Bcrypt(app)

# email
mail = Mail(app)

# login
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "users.login"

# Markdpwn Editor
SimpleMDE(app)
md = Misaka(fenced_code=True, tables=True)
md.init_app(app)

# Chat
# socketio = SocketIO()
# socketio.init_app(app)

from app.models import User


@login_manager.user_loader
def load_user(user_id):
    return User.query.filter(User.id == int(user_id)).first()


# blueprints
from app.users.views import users_blueprint
Esempio n. 10
0
import os
import sqlite3
import contextlib
from functools import reduce
from typing import List, Tuple, Optional

from flask import render_template, url_for, request
from flask_misaka import Misaka
from markupsafe import Markup

from readingbricks import app, utils
from readingbricks.user_query_processing import LogicalQueriesHandler

markdown_preprocessor = Misaka()
markdown_preprocessor.init_app(app)


@app.route('/')
def index() -> str:
    """Render home page."""
    tags_with_counts = []
    path_to_counts_of_tags = app.config.get('path_to_counts_of_tags')
    with open(path_to_counts_of_tags) as source_file:
        for line in source_file:
            tags_with_counts.append(line.split('\t'))
    home_url = url_for('index', _external=True)
    link_names = [
        f'{tag} ({count.strip()})' for (tag, count) in tags_with_counts
    ]
    links_to_tags = [
Esempio n. 11
0
 def test_init(self):
     md = Misaka()
     app2 = Flask(__name__)
     md.init_app(app2)
     self.assertIn("markdown", app2.jinja_env.filters)
Esempio n. 12
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    db.init_app(app)

    migrate = Migrate()
    migrate.init_app(app, db=db)

    login_manager.session_protection = 'strong'
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)

    principal = Principal()
    principal.init_app(app)

    from app.models import User, Sentence, Quiz, Answer

    # Flask-Blogging database config
    with app.app_context():
        storage = SQLAStorage(db=db)
        db.create_all()
        blog_engine = BloggingEngine()
        blog_engine.init_app(app, storage)

    misaka = Misaka(app=None,
                    renderer=None,
                    strikethrough=True,
                    underline=True,
                    tables=True,
                    wrap=True)
    misaka.init_app(app)

    from wtforms.fields import HiddenField

    def is_hidden_field_filter(field):
        return isinstance(field, HiddenField)

    app.jinja_env.globals['bootstrap_is_hidden_field'] = \
        is_hidden_field_filter

    # TODO: Move these auth handlers out of __init__.py
    @login_manager.user_loader
    # @blog_engine.user_loader
    def load_user(user_id):
        print "ID: ", user_id
        return User.query.get(int(user_id))

    @login_manager.unauthorized_handler
    def handle_unauthorized():
        if session.get('_id'):
            return redirect(url_for('auth.login'))
        else:
            login_user(User().save())
            return redirect(request.url)

    @identity_loaded.connect_via(app)
    def on_identity_loaded(sender, identity):
        identity.user = current_user

        if hasattr(current_user, "id"):
            identity.provides.add(UserNeed(current_user.id))

        # Shortcut to the give admins "blogger" role.
        if hasattr(current_user, "is_admin"):
            if current_user.is_admin:
                identity.provides.add(RoleNeed("blogger"))

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    # Initialise flask-admin
    admin = Admin(app, template_mode='bootstrap3', index_view=AdminIndexView())
    Post = storage.post_model
    # Add administrative views here
    admin.add_view(ModelView(User, db.session))
    admin.add_view(ModelView(Post, db.session))

    return app