Example #1
1
def create_app(config=None, blueprints=None):
    """
    Create and initialise the application.
    """
    app = Flask(__name__)
    app.config.from_pyfile("%s/config/default.py" % app.root_path)
    app.url_map.converters["regex"] = RegexConverter

    app.add_template_filter(slugify)

    if blueprints is None:
        blueprints = DEFAULT_BLUEPRINTS

    configure_blueprints(app, blueprints)

    return app
Example #2
1
def create_app(config_name):
    application = Flask(__name__, static_folder="static/", static_url_path=configs[config_name].STATIC_URL_PATH)

    application.config["NOTIFY_ENVIRONMENT"] = config_name
    application.config.from_object(configs[config_name])

    init_app(application)
    csrf.init_app(application)

    @csrf.error_handler
    def csrf_handler(reason):
        if "user_id" not in session:
            application.logger.info(u"csrf.session_expired: Redirecting user to log in page")

            return application.login_manager.unauthorized()

        application.logger.info(
            u"csrf.invalid_token: Aborting request, user_id: {user_id}", extra={"user_id": session["user_id"]}
        )

        abort(400, reason)

    login_manager.init_app(application)
    admin_api_client.init_app(application)
    proxy_fix.init_app(application)

    from .main import main as main_blueprint

    application.permanent_session_lifetime = timedelta(hours=1)
    application.register_blueprint(main_blueprint, url_prefix="/admin")
    login_manager.login_view = "main.render_login"

    main_blueprint.config = application.config.copy()

    @application.before_request
    def remove_trailing_slash():
        if request.path != "/" and request.path.endswith("/"):
            return redirect(request.path[:-1], code=301)

    application.add_template_filter(datetimeformat)

    return application
def create_app(config_name):

    application = Flask(__name__, static_folder="static/", static_url_path=configs[config_name].STATIC_URL_PATH)

    init_app(
        application,
        configs[config_name],
        bootstrap=bootstrap,
        data_api_client=data_api_client,
        feature_flags=feature_flags,
        login_manager=login_manager,
    )
    # Should be incorporated into digitalmarketplace-utils as well
    csrf.init_app(application)

    application.permanent_session_lifetime = timedelta(hours=1)
    from .main import main as main_blueprint
    from .status import status as status_blueprint

    application.register_blueprint(status_blueprint, url_prefix="/admin")
    application.register_blueprint(main_blueprint, url_prefix="/admin")
    login_manager.login_view = "main.render_login"
    main_blueprint.config = application.config.copy()

    @application.before_request
    def remove_trailing_slash():
        if request.path != "/" and request.path.endswith("/"):
            return redirect(request.path[:-1], code=301)

    @application.template_filter("markdown")
    def markdown_filter(data):
        return Markup(markdown(data))

    application.add_template_filter(parse_document_upload_time)

    return application
Example #4
1
    def _crea_app(self, config=None):
        app = Flask(__name__, template_folder="plantillas")
        app.psdash = self
        app.config.from_envvar("PSDASH_CONFIG", silent=True)

        if config and isinstance(config, dict):
            app.config.update(config)

        self._cargar_direccciones_remotas_permitidas(app)

        # If the secret key is not read from the config just set it to something.
        if not app.secret_key:
            app.secret_key = "whatisthissourcery"
        app.add_template_filter(fromtimestamp)

        from controlador_web import webapp

        prefix = app.config.get("PSDASH_URL_PREFIX")
        if prefix:
            prefix = "/" + prefix.strip("/")
        webapp.url_prefix = prefix
        app.register_blueprint(webapp)

        return app
Example #5
1
    def _create_app(self, config=None):
        app = Flask(__name__)
        app.psdash = self
        app.config.from_envvar("PSDASH_CONFIG", silent=True)

        if config and isinstance(config, dict):
            app.config.update(config)

        self._load_allowed_remote_addresses(app)

        # If the secret key is not read from the config just set it to something.
        if not app.secret_key:
            app.secret_key = "whatisthissourcery"
        app.add_template_filter(fromtimestamp)

        from psdash.web import webapp

        prefix = app.config.get("PSDASH_URL_PREFIX")
        if prefix:
            prefix = "/" + prefix.strip("/")
        webapp.url_prefix = prefix
        app.register_blueprint(webapp)

        return app
def create_app(config={}):
    app = Flask(__name__, instance_relative_config=True)
    app.config.update(DEFAULT_CONFIG)
    app.config.from_pyfile("settings.py", silent=True)
    app.config.update(config)

    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        return getattr(g, "language", "en")

    assets_env.init_app(app)
    db.init_app(app)

    app.register_blueprint(admin)
    app.register_blueprint(auth)
    app.register_blueprint(meetings)

    app.add_template_filter(activity_map)
    app.add_template_filter(countries)
    app.add_template_filter(country_in)
    app.add_template_filter(region_in)
    app.add_template_filter(crop)
    app.add_template_filter(nl2br)
    app.add_template_filter(convert_to_dict, name="dict")
    app.add_template_filter(no_image_cache)
    app.add_template_filter(pluralize)
    app.add_template_filter(slugify)
    app.add_template_filter(sort_by_tuple_element)
    app.add_template_filter(clean_html)
    app.add_template_global(active)
    app.add_template_global(date_processor)
    app.add_template_global(inject_static_file)
    app.add_template_global(inject_badge_context)
    app.add_template_global(has_perm)
    app.add_template_global(Logo, name="get_logo")

    @app.context_processor
    def inject_context():
        return {
            "CustomField": {
                "TEXT": CustomField.TEXT,
                "IMAGE": CustomField.IMAGE,
                "EMAIL": CustomField.EMAIL,
                "CHECKBOX": CustomField.CHECKBOX,
                "SELECT": CustomField.SELECT,
                "COUNTRY": CustomField.COUNTRY,
                "LANGUAGE": CustomField.LANGUAGE,
                "CATEGORY": CustomField.CATEGORY,
                "EVENT": CustomField.EVENT,
            },
            "Participant": {
                "PARTICIPANT": Participant.PARTICIPANT,
                "MEDIA": Participant.MEDIA,
                "DEFAULT": Participant.DEFAULT,
                "DEFAULT_MEDIA": Participant.DEFAULT_MEDIA,
            },
        }

    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = "auth.login"
    login_manager.login_message_category = "warning"

    mail.init_app(app)
    redis_store.init_app(app, strict=True)

    if app.config.get("SENTRY_DSN"):
        sentry.init_app(app)

    _configure_uploads(app)
    _configure_logging(app)

    app.config["REPRESENTING_TEMPLATES"] = path("meetings/participant/representing")

    _translations = app.config["TRANSLATIONS"]
    if _DEFAULT_LANG not in _translations:
        _translations = [_DEFAULT_LANG] + _translations
    app.config["TRANSLATIONS"] = _translations

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(user_id)

    @app.route("/")
    def index():
        return redirect(url_for("meetings.home"))

    @app.errorhandler(413)
    def file_too_large(error):
        mb = 1024 * 1024
        max_size = app.config.get("UPLOAD_SIZE", mb) / mb
        return render_template("_file_too_large.html", max_size=max_size, url=request.url), 413

    return app
Example #7
0
app.add_url_rule("/admin/matakuliah/create/", "admin:matkul:create", admin_matkul_create, methods=["GET", "POST"])
app.add_url_rule(
    "/admin/matakuliah/update/<int:matkul_id>/", "admin:matkul:update", admin_matkul_update, methods=["GET", "POST"]
)
app.add_url_rule("/admin/matakuliah/delete/<int:matkul_id>/", "admin:matkul:delete", admin_matkul_delete)

app.add_url_rule("/dosen/", "dosen:home", dosen_home)
app.add_url_rule("/dosen/tugas/detail/<int:tugas_id>/", "dosen:tugas:detail", dosen_tugas_detail)
app.add_url_rule("/dosen/tugas/create/", "dosen:tugas:create", dosen_tugas_create, methods=["GET", "POST"])
app.add_url_rule("/dosen/tugas/", "dosen:tugas:list", dosen_tugas_list)
app.add_url_rule(
    "/dosen/tugas/update/<int:tugas_id>/", "dosen:tugas:update", dosen_tugas_update, methods=["GET", "POST"]
)
app.add_url_rule("/dosen/tugas/delete/<int:tugas_id>/", "dosen:tugas:delete", dosen_tugas_delete)

app.add_url_rule("/mhs/", "mhs:home", mhs_home)
app.add_url_rule("/mhs/detail/<int:tugas_id>/", "mhs:tugas:detail", mhs_tugas_detail)
app.add_url_rule("/mhs/kumpul/<int:tugas_id>/", "mhs:tugas:kumpulkan", mhs_tugas_kumpulkan, methods=["POST"])


@app.before_request
def before_request():
    g.user = None
    if "user_id" in session:
        g.user = User.get(User.id == session["user_id"])


from apps.filters import to_datetime

app.add_template_filter(to_datetime, "datetime")
Example #8
0

@app.route("/")
def index():
    articles = top_articles()
    return render_template("index.jinja2.html", rows=articles)


@app.template_filter()
def seconds_ago(val):
    return val_ago(val, unit="second")


@app.route("/experiment")
def experiment():
    return render_template("seconds.jinja2.html", seconds=range(60))


app.add_template_filter(human_date)


@app.route("/datetest")
def datetest():
    now = dt.datetime.now()
    deltas = [dt.timedelta(seconds=5), dt.timedelta(seconds=60 * 60), dt.timedelta(days=5), dt.timedelta(days=60)]
    dates = [(now - delta) for delta in deltas]
    return render_template("dates.jinja2.html", dates=dates)


if __name__ == "__main__":
    app.run(debug=True)
Example #9
0
app = Flask(__name__)
app.debug = app_config.DEBUG

try:
    file_handler = logging.FileHandler("%s/public_app.log" % app_config.SERVER_LOG_PATH)
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)
except IOError:
    pass

app.logger.setLevel(logging.INFO)

app.register_blueprint(static.static, url_prefix="/%s" % app_config.PROJECT_SLUG)

app.add_template_filter(smarty_filter, name="smarty")
app.add_template_filter(urlencode_filter, name="urlencode")
app.add_template_filter(format_commas_filter, name="format_commas")

# Example of rendering index.html with public_app
@app.route("/%s/" % app_config.PROJECT_SLUG, methods=["GET"])
def index():
    """
    Example view rendering a simple page.
    """
    context = make_context(asset_depth=1)

    context["users"] = SITE_USERS

    return make_response(render_template("admin/index.html", **context))

db = SQLAlchemy(app)

# Flask uploads
tournament_exports = UploadSet("tournamentExports", ("json", "txt"))

configure_uploads(app, [tournament_exports])

# Views
import views

# Blueprints
from .user.views import user_bp as user_blueprint

app.register_blueprint(user_blueprint)

from .tournament.views import tournament_bp as tournament_blueprint

app.register_blueprint(tournament_blueprint)

from .netrunner.views import nr_bp as nr_blueprint

app.register_blueprint(nr_blueprint)

# Netrunner
from .netrunner.models import Identity, Faction, Side

# Jinja2 Filters
from filters import name_format

app.add_template_filter(name_format)
Example #11
0
class TarbellSite:
    def __init__(self, path, client_secrets_path=None):
        self.app = Flask(__name__)

        self.app.jinja_env.finalize = silent_none  # Don't print "None"
        self.app.debug = True  # Always debug

        self.path = path
        self.project, self.base = self.load_project(path)

        self.data = {}
        self.expires = 0

        self.app.add_url_rule("/", view_func=self.preview)
        self.app.add_url_rule("/<path:path>", view_func=self.preview)
        self.app.add_template_filter(slughifi, "slugify")
        self.app.add_template_filter(pprint_lines, "pprint_lines")

    def load_project(self, path):
        base = None
        base_dir = os.path.join(path, "_base/")

        # Get the base as register it as a blueprint
        if os.path.exists(os.path.join(base_dir, "base.py")):
            filename, pathname, description = imp.find_module("base", [base_dir])
            base = imp.load_module("base", filename, pathname, description)
            self.app.register_blueprint(base.blueprint)
        else:
            puts("No _base/base.py file found")

        filename, pathname, description = imp.find_module("tarbell_config", [path])
        project = imp.load_module("project", filename, pathname, description)

        try:
            self.key = project.SPREADSHEET_KEY
            self.client = get_drive_api(self.path)
        except AttributeError:
            self.key = None
            self.client = None

        try:
            project.CREATE_JSON
        except AttributeError:
            project.CREATE_JSON = True

        try:
            project.DEFAULT_CONTEXT
        except AttributeError:
            project.DEFAULT_CONTEXT = {}

        try:
            self.app.register_blueprint(project.blueprint)
        except AttributeError:
            pass

        # Set up template loaders
        template_dirs = [path]
        if os.path.isdir(base_dir):
            template_dirs.append(base_dir)

        self.app.jinja_loader = TarbellFileSystemLoader(template_dirs)

        return project, base

    def preview(self, path=None, extra_context=None, publish=False):
        """ Preview a project path """
        if path is None:
            path = "index.html"

        ## Serve JSON
        if self.project.CREATE_JSON and path == "data.json":
            context = self.get_context(publish)
            return Response(json.dumps(context), mimetype="application/json")

        ## Detect files
        filepath = None
        for root, dirs, files in filter_files(self.path):
            # Does it exist under _base?
            basepath = os.path.join(root, "_base", path)
            try:
                with open(basepath):
                    mimetype, encoding = mimetypes.guess_type(basepath)
                    filepath = basepath
            except IOError:
                pass

            # Does it exist under regular path?
            fullpath = os.path.join(root, path)
            try:
                with open(fullpath):
                    mimetype, encoding = mimetypes.guess_type(fullpath)
                    filepath = fullpath
            except IOError:
                pass

        if filepath and mimetype and mimetype in TEMPLATE_TYPES:
            context = self.get_context(publish)
            # Mix in defaults
            context.update(
                {
                    "PROJECT_PATH": self.path,
                    "PREVIEW_SERVER": not publish,
                    "ROOT_URL": "127.0.0.1:5000",
                    "PATH": path,
                    "SPREADSHEET_KEY": self.key,
                }
            )
            if extra_context:
                context.update(extra_context)
            try:
                rendered = render_template(path, **context)
                return Response(rendered, mimetype=mimetype)
            except TemplateSyntaxError:
                puts("{0} can't be parsed by Jinja, serving static".format(colored.yellow(filepath)))

        if filepath:
            dir, filename = os.path.split(filepath)
            return send_from_directory(dir, filename)

        return Response(status=404)

    def get_context(self, publish=False):
        """
        Use optional CONTEXT_SOURCE_FILE setting to determine data source.
        Return the parsed data.

        Can be an http|https url or local file. Supports csv and excel files.
        """
        context = self.project.DEFAULT_CONTEXT
        try:
            file = self.project.CONTEXT_SOURCE_FILE
            # CSV
            if re.search(r"(csv|CSV)$", file):
                context.update(self.get_context_from_csv())
            # Excel
            if re.search(r"(xlsx|XLSX|xls|XLS)$", file):
                pass
        except AttributeError:
            context.update(self.get_context_from_gdoc())

        return context

    def get_context_from_csv(self):
        """
        Open CONTEXT_SOURCE_FILE, parse and return a context
        """
        if re.search("^(http|https)://", self.project.CONTEXT_SOURCE_FILE):
            data = requests.get(self.project.CONTEXT_SOURCE_FILE)
            reader = csv.reader(data.iter_lines(), delimiter=",", quotechar='"')
            ret = {rows[0]: rows[1] for rows in reader}
        else:
            try:
                with open(self.project.CONTEXT_SOURCE_FILE) as csvfile:
                    reader = csv.reader(csvfile, delimiter=",", quotechar='"')
                    ret = {rows[0]: rows[1] for rows in reader}
            except IOError:
                file = "%s/%s" % (os.path.abspath(self.path), self.project.CONTEXT_SOURCE_FILE)
                with open(file) as csvfile:
                    reader = csv.reader(csvfile, delimiter=",", quotechar='"')
                    ret = {rows[0]: rows[1] for rows in reader}
        ret.update({"CONTEXT_SOURCE_FILE": self.project.CONTEXT_SOURCE_FILE})
        return ret

    def get_context_from_gdoc(self):
        """Wrap getting context in a simple caching mechanism."""
        try:
            start = int(time.time())
            if not self.data or start > self.expires:
                self.data = self._get_context_from_gdoc(self.project.SPREADSHEET_KEY)
                end = int(time.time())
                self.expires = end + SPREADSHEET_CACHE_TTL
            return self.data
        except AttributeError:
            return {}

    def _get_context_from_gdoc(self, key):
        """Create a Jinja2 context from a Google spreadsheet."""
        try:
            content = self.export_xlsx(key)
            data = process_xlsx(content)
            if "values" in data:
                data = copy_global_values(data)
            return data
        except BadStatusLine:
            # Stale connection, reset API and data
            puts("Connection reset, reloading drive API")
            self.client = get_drive_api(self.path)
            self.data = {}
            return self._get_context_from_gdoc(key)

    def export_xlsx(self, key):
        """Download xlsx version of spreadsheet"""
        spreadsheet_file = self.client.files().get(fileId=key).execute()
        links = spreadsheet_file.get("exportLinks")
        downloadurl = links.get("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        resp, content = self.client._http.request(downloadurl)
        return content

    def generate_static_site(self, output_root, extra_context):
        base_dir = os.path.join(self.path, "_base/")

        for root, dirs, files in filter_files(base_dir):
            for filename in files:
                self._copy_file(root.replace("_base/", ""), filename, output_root, extra_context)

        for root, dirs, files in filter_files(self.path):
            for filename in files:
                self._copy_file(root, filename, output_root, extra_context)

    def _copy_file(self, root, filename, output_root, extra_context=None):
        # Strip out full filesystem paths
        rel_path = os.path.join(root.replace(self.path, ""), filename)
        if rel_path.startswith("/"):
            rel_path = rel_path[1:]
        output_path = os.path.join(output_root, rel_path)
        output_dir = os.path.dirname(output_path)

        puts("Writing {0}".format(output_path))
        with self.app.test_request_context():
            preview = self.preview(rel_path, extra_context=extra_context, publish=True)
            if not os.path.exists(output_dir):
                os.makedirs(output_dir)
            with open(output_path, "wb") as f:
                if isinstance(preview.response, FileWrapper):
                    f.write(preview.response.file.read())
                else:
                    f.write(preview.data)
Example #12
0
from mongokit import Connection
import steam

from models import Profile, Job, Match, User
from filters import unix_strftime, prettyprint

app = Flask(__name__)

app.config.from_pyfile("settings.cfg")
connection = Connection(app.config["MONGODB_HOST"], app.config["MONGODB_PORT"])

cache = Cache(app)
oid = OpenID(app)

connection.register([Profile, Job, Match, User])
app.add_template_filter(unix_strftime)
app.add_template_filter(prettyprint)

# Setup steamodd
steam.api.key.set(app.config["STEAM_API_KEY"])
steam.api.socket_timeout.set(10)

# Helpers
@cache.cached(timeout=60 * 60, key_prefix="league_passes")
def get_league_passes():
    try:
        return [x for x in steam.items.schema(570, "en_US") if x.type == "League Pass"]
    except steam.api.APIError:
        return []


@cache.cached(timeout=60 * 60, key_prefix="heroes")
Example #13
0
#!/usr/bin/env python

import json

from flask import Flask, make_response, render_template
from werkzeug.debug import DebuggedApplication

import app_config
from render_utils import make_context, smarty_filter, urlencode_filter
import static

app = Flask(__name__)
app.debug = app_config.DEBUG

app.add_template_filter(smarty_filter, name="smarty")
app.add_template_filter(urlencode_filter, name="urlencode")

# Example application views
@app.route("/")
def index():
    """
    Example view demonstrating rendering a simple HTML page.
    """
    context = make_context()

    return make_response(render_template("index.html", **context))


app.register_blueprint(static.static)

# Enable Werkzeug debug pages
Example #14
0
        "search.html", count=count, advanced=advanced, pagination=pagination, results=results, data_sources=DATA_SOURCES
    )


def join_if_list(value, separator):
    if isinstance(value, list):
        return separator.join(value)
    else:
        return value


def url_for_other_page(page):
    args = request.args.copy()
    args["page"] = page
    return url_for(request.endpoint, **args)


def _fbopen_uri():
    return "{}{}".format(FBOPEN_HOST, FBOPEN_PATH)


def _get_results(raw):
    return raw.get("docs")


app.jinja_env.globals["url_for_other_page"] = url_for_other_page
app.add_template_filter(join_if_list)


if __name__ == "__main__":
    app.run()
Example #15
0
File: app.py Project: rclanan/radar
def create_app():
    app = Flask(__name__)
    app.config.from_object("radar.default_settings")
    app.config.from_object("radar.web.default_settings")
    app.config.from_envvar("RADAR_SETTINGS")

    db.init_app(app)

    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.user_loader(load_user)
    login_manager.login_view = "auth.login"

    Markdown(app)

    mail.init_app(app)

    app.register_blueprint(radar_bp)
    app.register_blueprint(auth_bp)
    app.register_blueprint(disease_groups_bp, url_prefix="/disease-groups")
    app.register_blueprint(units_bp, url_prefix="/units")
    app.register_blueprint(users_bp, url_prefix="/users")
    app.register_blueprint(patients_bp, url_prefix="/patients")
    app.register_blueprint(recruit_bp, url_prefix="/patients")
    app.register_blueprint(news_bp, url_prefix="/news")
    app.register_blueprint(stats_bp, url_prefix="/stats")

    patient_blueprints = [
        (diagnosis_bp, "/diagnosis"),
        (dialysis_bp, "/dialysis"),
        (genetics_bp, "/genetics"),
        (hospitalisations_bp, "/hospitalisations"),
        (results_bp, "/results"),
        (medications_bp, "/medications"),
        (pathology_bp, "/pathology"),
        (plasmapheresis_bp, "/plasmapheresis"),
        (renal_imaging_bp, "/renal-imaging"),
        (salt_wasting_bp, "/salt-wasting"),
        (transplants_bp, "/transplants"),
    ]

    patient_base = "/patients/<int:patient_id>"

    for bp, url_prefix in patient_blueprints:
        app.register_blueprint(bp, url_prefix=patient_base + url_prefix)

    app.before_request(require_login)
    app.before_request(force_password_change)

    # Register template filters
    app.add_template_filter(strftime)
    app.add_template_filter(year_format)
    app.add_template_filter(date_format)
    app.add_template_filter(datetime_format)
    app.add_template_filter(nl2br)
    app.add_template_filter(missing)
    app.add_template_filter(yn)
    app.add_template_filter(number_format)

    # Register template globals/functions
    app.add_template_global(url_for_order_by)
    app.add_template_global(url_for_page)
    app.add_template_global(url_for_per_page)

    # Register context processors (data available in all templates)
    app.context_processor(inject_navigation)
    app.context_processor(inject_delete_form)

    # Register error handlers
    app.register_error_handler(403, forbidden)
    app.register_error_handler(404, page_not_found)
    app.register_error_handler(500, internal_server_error)

    # Automatically set the created_user and modified_user
    event.listen(SignallingSession, "before_flush", before_flush_set_created_listener)
    event.listen(SignallingSession, "before_flush", before_flush_set_modified_listener)

    return app
Example #16
0
from kagami.utils.nl2br import nl2br
from kagami.config import Config
from kagami.models import KagamiStatus
from kagami.i18n import i18n


def get_api(access_token: str, access_secret: str):
    tw_auth = tweepy.OAuthHandler(current_app.config["CK"], current_app.config["CS"])
    tw_auth.set_access_token(access_token, access_secret)
    return tweepy.API(tw_auth)


app = Flask(__name__)
app.config.from_object(Config)
app.config["STRINGS"] = i18n()
import kagami.handler
import kagami.auth
import kagami.status
import kagami.user
import kagami.user_config
import kagami.direct_message
import kagami.cookie

app.add_template_filter(nl2br)
app.jinja_env.globals.update(handler=kagami.handler)
app.jinja_env.globals.update(int=int, str=str)
app.jinja_env.globals.update(session=session)
app.jinja_env.globals.update(KagamiStatus=KagamiStatus)
Bootstrap(app)
if app.config["ENABLE_HTTPS"]:
    SSLify(app)
Example #17
0
# Set up jinja2 filters.
from filters import (
    escape_every_character,
    timestamp_to_datestring,
    datetime_to_datestring,
    seconds_to_time,
    dota_wiki_link,
    dotabuff_hero_link,
    dotabuff_item_link,
    dotabuff_match_link,
)

app.add_template_filter(escape_every_character)
app.add_template_filter(timestamp_to_datestring)
app.add_template_filter(datetime_to_datestring)
app.add_template_filter(seconds_to_time)
app.add_template_filter(dota_wiki_link)
app.add_template_filter(dotabuff_hero_link)
app.add_template_filter(dotabuff_item_link)
app.add_template_filter(dotabuff_match_link)


# Load views
import views

# Load blueprints
from app.admin.views import mod as admin_module
from app.users.views import mod as users_module
from app.replays.views import mod as replays_module
from app.leagues.views import mod as leagues_module
from app.teams.views import mod as teams_module
Example #18
0
def create_app(name, config_object, override=None):
    """App factory.

    The factory pattern makes unit testing much saner.

    :param name: the name of the app
    :param config_object: path to config object
    """
    app = Flask(name)
    app.json_encoder = LSOJSONEncoder

    try:
        app.config.from_object(config_object)
    except ImportError:
        print "ImportError with config object:", config_object
        pass

    if override:
        app.config.update(override)

    # Needed to locate templates and assets in various contexts (runserver,
    # testing, ...)
    # TODO: surely there's a way to avoid this?
    LSO_PATH = os.path.dirname(__file__)
    app.template_folder = os.path.join(LSO_PATH, "templates")
    app.static_folder = os.path.join(LSO_PATH, "static")

    # Template filters
    for _filter in template_filters:
        app.add_template_filter(_filter)

    # URL converters
    add_converters(app)

    # Extensions
    lso.admin.admin.init_app(app)

    assets.init_app(app)
    assets.app = app  # TODO: remove hack
    assets.url = "/static"
    assets.directory = app.config["STATIC_DEST"]

    cache.init_app(app)

    lso.database.db.init_app(app)

    mail.init_app(app)

    md = Markdown(app, extensions=["admonition"])
    from ext_markdown import SanskritExtension

    md.register_extension(SanskritExtension)

    # security.init_app(app)

    # 'sanskrit' package
    global ctx, simple_query, simple_analyzer
    ctx = sanskrit.Context(app.config)
    ctx.connect()
    try:
        simple_query = sanskrit.query.SimpleQuery(ctx)
        simple_analyzer = sanskrit.analyze.SimpleAnalyzer(ctx)
    except (sqlalchemy.exc.ProgrammingError, sqlalchemy.exc.OperationalError):
        simple_query = None
        simple_analyzer = None

    # Debug toolbar
    if app.debug:
        from flask.ext.debugtoolbar import DebugToolbarExtension

        toolbar = DebugToolbarExtension(app)

    # Blueprints
    if app.debug:
        import debug

        app.register_blueprint(debug.debug)
    else:
        do_logging(app)

    import views

    app.register_blueprint(views.main)
    register_blueprints(
        app,
        "dicts",
        "guide",
        "ref",
        "site",
        "texts",
        "tools",
        #'users'
    )

    return app
Example #19
0
@BABEL.localeselector
def get_locale():
    """Get locale.

    Returns:
        The locale that should be used for Babel. If not given as an option to
        Fava, guess from browser.

    """
    if app.config["language"]:
        return app.config["language"]
    return request.accept_languages.best_match(["de", "en"])


for _, function in inspect.getmembers(template_filters, inspect.isfunction):
    app.add_template_filter(function)


@app.template_global()
def url_for_current(**kwargs):
    """URL for current page with updated request args."""
    if not kwargs:
        return url_for(request.endpoint, **request.view_args)
    args = request.view_args.copy()
    args.update(kwargs)
    return url_for(request.endpoint, **args)


@app.template_global()
def url_for_source(**kwargs):
    """URL to source file (possibly link to external editor)."""
Example #20
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 #21
0
def create_app(config=None):
    """ config should be a python file """
    from pathlib import Path

    from flask import Flask, current_app, g, session, url_for, render_template

    from flask_sqlalchemy import SQLAlchemy
    from flask_security import Security, SQLAlchemyUserDatastore

    from flask_wtf.csrf import CsrfProtect

    from flask_assets import Environment, Bundle

    from .app_setup import init_db, setup_dirs
    from .core import db, load_blueprints, setup_logger
    from .lib.template_filters import fmt_datetime, none_as_str, next_page_url, prev_page_url, get_page_url, get_images

    from .models.user import User, Role, user_datastore

    from .Admin import index, series, images, texts, contact
    from .Public import index, contact, texts
    from .Security import user

    app = Flask(__name__.split(".")[0], instance_relative_config=True)

    app.config.from_object("config")
    app.config.from_pyfile("config.py")

    if config is not None:
        app.config.from_pyfile(config)
        setup_logger(app)
        app.logger.info("Started with config from: {}".format(config))
    else:
        setup_logger(app)
        app.logger.info("Started App")

    # Flask.sqlalchemy
    db.init_app(app)

    load_blueprints(app)

    # make sure db tables and required directories exist
    before_first_request_funcs = [setup_dirs(app), init_db(app)]

    # Security
    csrf = CsrfProtect()
    csrf.init_app(app)
    security = Security()
    security.init_app(app, user_datastore, register_blueprint=False)

    # Assets
    assets = Environment(app=app)
    assets.from_yaml("assets.yml")

    # template filters
    app.add_template_filter(fmt_datetime)
    app.add_template_filter(none_as_str)
    app.add_template_filter(next_page_url)
    app.add_template_filter(prev_page_url)
    app.add_template_filter(get_page_url)
    app.add_template_filter(get_images)

    return app
Example #22
0
    ret = "[not a timestamp]"
    ts = 0
    try:
        if isinstance(value, str):
            ts = int(value)
        elif isinstance(value, int):
            ts = value
        else:
            raise ValueError
    except exceptions.ValueError:
        return ret

    return "%s %s" % (datetime.datetime.fromtimestamp(ts).strftime(format), time.tzname[0])


app.add_template_filter(datetimeformat)


@app.template_filter("print_json")
def print_json_filter(s):
    json_string = json.dumps(s, sort_keys=True, indent=4, separators=(",", ": "))
    # result = highlight(json_string, json_lexer, json_formatter)
    return json_string


def json_style(**kwargs):

    choose_style = request.args.get("style", "friendly")
    app.jinja_env.globals["current_style"] = choose_style

    global json_lexer, json_formatter
# -*- coding: utf-8 -*-
__author__ = "venking"

from flask import Flask
from web import loginctrl
from module.util import fromtimestamp

app = Flask(__name__)
app.register_blueprint(loginctrl, url_prefix="/login")

app.add_template_filter(fromtimestamp)
app.secret_key = "zoupan19940907"

# @app.route('/')
# def index():
#     return 'Index Page!'
#
#
# @app.route('/hello')
# def hello_world():
#     return 'Hello World!'
#
#
# @app.route('/user/<username>')
# def show_user_profile(username):
#     # show the user profile for that user
#     flash('你好,%s'%(username))
#     return 'User %s' % username
#
#
# @app.route('/post/<int:post_id>')
Example #24
0
import os

from boto.s3.key import Key
from boto.s3.connection import S3Connection
from flask import Flask, request, render_template
from pbkdf2 import crypt

import forms
import filters
import models
import settings


app = Flask(__name__)
app.config.update(SECRET_KEY=settings.FLASK_SECRET_KEY)
app.add_template_filter(filters.nl2br)


@app.route("/", methods=["GET", "POST"])
def create_page():
    """ Main view to present the user with a form to create a signup page. """
    form = forms.PageForm(request.form)
    error = None

    if request.method == "POST" and form.validate():

        # if password incorrect or not entered, show an error
        if not valid_password(form.password.data):
            error = "Must enter correct password."
            return render_template("main.html", form=form, error=error)
Example #25
0
def create_web_app(db=None, facility_spec=None, _test_return_extra=False):
    """
    Function to prepare the Flask web application.

    :param db: database access object to use.  If `None` then one will be
        constructed based on the configuration (and `facility_spec`).
    :param facility_spec: facility specification used to construct the
        facility list (via :func:`hedwig.config.get_config`) and database
        object (if not given, via :func:`hedwig.config.get_database`).
    :param _test_return_extra: if true, instead of just returning the
        application object, return a dictionary of values useful for
        debugging.  (Currently just returns the output of `locals()`.)
    """

    home = get_home()
    config = get_config()

    if db is None:
        db = get_database(facility_spec=facility_spec)

    # Load facilities as specified in the configuration.
    facilities = OrderedDict()

    for facility_class in get_facilities(facility_spec=facility_spec):
        # Create facility object.
        facility_code = facility_class.get_code()
        facility_id = db.ensure_facility(facility_code)
        facility = facility_class(facility_id)

        # Store in our facilities list.
        facilities[facility_id] = FacilityInfo(facility_id, facility_code, facility.get_name(), facility)

    # Configure the web application.
    application_name = config.get("application", "name")

    app = Flask(
        __name__,
        static_folder=os.path.join(home, "data", "web", "static"),
        template_folder=os.path.join(home, "data", "web", "template"),
    )

    app.jinja_options["extensions"].append(OrderBlocks)

    log_file = config.get("application", "log_file")
    if log_file:
        file_handler = logging.FileHandler(log_file)
        file_handler.setLevel(logging.WARNING)
        file_handler.setFormatter(
            logging.Formatter(fmt="%(asctime)s %(levelname)s %(name)s %(message)s", datefmt="%Y-%m-%dT%H:%M:%S")
        )
        app.logger.addHandler(file_handler)

    # Determine maximum upload size: check all upload limits from the
    # configuration file.
    max_upload_size = max(
        int(upload_val)
        for (upload_key, upload_val) in config.items("upload")
        if upload_key.startswith("max_") and upload_key.endswith("_size")
    )
    app.config["MAX_CONTENT_LENGTH"] = max_upload_size * 1024 * 1024

    # Try to read the secret key from the configuration file, but if
    # there isn't one, generate a temporary key.
    secret_key = config.get("application", "secret_key")
    if not secret_key:
        app.logger.warning("Generating temporary secret key")
        secret_key = os.urandom(32)
    app.secret_key = secret_key

    # Set up routing converters.
    app.url_map.converters["hedwig_group"] = make_enum_converter(GroupType)
    app.url_map.converters["hedwig_thread"] = make_enum_converter(MessageThreadType)

    for facility in facilities.values():
        app.url_map.converters["hedwig_call_type_{}".format(facility.code)] = make_enum_converter(
            facility.view.get_call_types()
        )

        app.url_map.converters["hedwig_review_{}".format(facility.code)] = make_enum_converter(
            facility.view.get_reviewer_roles()
        )

        app.url_map.converters["hedwig_text_{}".format(facility.code)] = make_enum_converter(
            facility.view.get_text_roles()
        )

        for filter_ in facility.view.get_custom_filters():
            app.add_template_filter(filter_, "{}_{}".format(facility.code, filter_.__name__))

    app.register_blueprint(create_home_blueprint(db, facilities))
    app.register_blueprint(create_admin_blueprint(db, facilities), url_prefix="/admin")
    app.register_blueprint(create_people_blueprint(db, facilities))
    app.register_blueprint(create_help_blueprint(), url_prefix="/help")
    app.register_blueprint(create_query_blueprint(db), url_prefix="/query")

    # Register blueprints for each facility.
    for facility in facilities.values():
        app.register_blueprint(create_facility_blueprint(db, facility.view), url_prefix="/" + facility.code)

    @app.context_processor
    def add_to_context():
        return {"application_name": application_name}

    register_error_handlers(app)
    register_template_utils(app)

    if _test_return_extra:
        return locals()

    return app