Example #1
1
def create_app(source=None, config=None):
    app = Flask("flaskrst")

    # Set default config values
    app.config.setdefault("MODULES", {})
    app.config.setdefault("STYLESHEETS", [])
    app.config.setdefault("FEEDS", [])

    # Load config
    if config:
        app.config.from_pyfile(config)
        config_loaded = True
    # maybe there is a file declared by env
    elif "FLASK_RST_CONFIG" in os.environ:
        app.config.from_envvar("FLASK_RST_CONFIG")
        config_loaded = True
    # no config loaded try again later after source setting
    else:
        config_loaded = False

    # Set source path
    if source:
        app.config["SOURCE"] = source
    elif "FLASK_RST_SOURCE" in os.environ:
        app.config["SOURCE"] = os.environ["FLASK_RST_SOURCE"]
    else:
        # Use current working directory as source
        app.config["SOURCE"] = os.getcwd()

    # If no config already loaded than is a config maybe in source path
    if not config_loaded:
        config_path = os.path.join(app.config["SOURCE"], "config.py")
        app.config.from_pyfile(config_path, silent=True)

    # Set path of static folder
    if "STATIC_FOLDER" in app.config:
        app.static_folder = app.config["STATIC_FOLDER"]
    else:
        # Is a static folder called _static in source path?
        source_static_folder = os.path.join(app.config["SOURCE"], "_static")
        if os.path.isdir(source_static_folder):
            app.static_folder = source_static_folder

    # Load flask-rst modules
    manager.init_app(app)
    manager.load_from_config()

    # Add some jinja globals and context processors
    app.jinja_env.globals["date"] = date
    app.context_processor(inject_navigation)

    @app.errorhandler(404)
    def page_not_found(error):
        return render_template("404.html"), 404

    return app
Example #2
1
def create_app(config_name):
    app = Flask(config_name)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    app_admin.init_app(app)
    babel.init_app(app)
    celery.init_app(app)
    bootstrap.init_app(app)

    db.init_app(app)
    with app.app_context():
        print current_app.name
        db.create_all()
    login_manager.init_app(app)

    app_admin.base_template = "layout.html"

    from main import main as main_blueprint
    from admin import admin as admin_blueprint
    from auth import auth as auth_blueprint

    app.register_blueprint(main_blueprint)
    app.register_blueprint(auth_blueprint, url_prefix="/auth")

    import os.path

    _dir = os.path.dirname(os.path.abspath(__file__))
    app.template_folder = os.path.join(_dir, "templates")
    app.static_folder = os.path.join(_dir, "static")

    return app
Example #3
1
def create_app():
    app = Flask(__name__.split(".")[0], template_folder="../templates", static_url_path=None, static_folder=None)

    env = Development
    if os.environ.get("APPLICATION_ENV", "") == "Production":
        env = Production

    app.config.from_object(env)

    # Load config items into jinja settings
    for key, val in app.config.items():
        if key.startswith("JINJA"):
            setattr(app.jinja_env, key[6:].lower(), val)

    register_controllers(app)
    register_errorhandlers(app)
    register_extensions(app)

    app.static_folder = "../public/"
    app.add_url_rule(
        app.config["STATIC_URL_PATH"] + "/<path:filename>", endpoint="static", view_func=app.send_static_file
    )

    signal.signal(signal.SIGUSR1, sig_handler)
    signal.signal(signal.SIGUSR2, sig_handler)

    return app
Example #4
1
def create_app(config_name):
    app = Flask(config_name)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    Markdown(app)

    _dir = os.path.dirname(os.path.abspath(__file__))
    app.template_folder = os.path.join(_dir, "templates")
    app.static_folder = os.path.join(_dir, "static")

    return app
Example #5
1
def create_app():
    """Create the Flask app."""

    app = Flask("modelconvert", static_folder=None)

    app.config.from_object("modelconvert.settings")
    app.config.from_envvar("MODELCONVERT_SETTINGS", silent=True)

    # configure custom static path for serving files during
    # development
    app.static_folder = app.config["STATIC_PATH"]
    app.add_url_rule("/static/<path:filename>", endpoint="static", view_func=app.send_static_file)

    # custom template path, fall back to default
    jinja_loader = jinja2.ChoiceLoader([jinja2.FileSystemLoader(app.config["TEMPLATE_PATH"]), app.jinja_loader])
    app.jinja_loader = jinja_loader

    configure_logging(app)

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

    celery.add_defaults(app.config)

    # configure error handlers
    @app.errorhandler(403)
    def forbidden_page(error):
        return render_template("403.html"), 403

    # FIXME adapt this for json requests http://flask.pocoo.org/snippets/83/
    @app.errorhandler(404)
    def page_not_found(error):
        if request.headers["Content-Type"] == "application/json":
            message = {"status": 404, "detail": "Not Found: " + request.url}
            resp = jsonify(message)
            resp.status_code = 404
            return resp
        else:
            return render_template("404.html"), 404

    @app.errorhandler(500)
    def server_error_page(error):
        return render_template("500.html"), 500

    if app.config["DEBUG"]:
        from werkzeug.wsgi import SharedDataMiddleware

        app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {"/preview": app.config["DOWNLOAD_PATH"]})

    return app
Example #6
1
def create_app(config=None, app_name=None):
    if app_name is None:
        app_name = DEFAULT_APP_NAME

    app = Flask(app_name)

    app.template_folder = os.path.join(os.path.dirname(__file__), "_templates")
    app.static_folder = os.path.join(os.path.dirname(__file__), "_static")

    configure_app(app, config)
    configure_extensions(app)
    configure_template_filters(app)
    configure_blue_print(app, DEFAULT_BLUEPRINTS)

    return app
Example #7
0
def create_app(config=None):
    app = Flask(__name__, template_folder="templates")
    app.config.from_pyfile("config.py")
    env = EnvConfig()
    env.init_app(app, "BOOKMARKS_")
    if isinstance(config, dict):
        app.config.update(config)
    elif config:
        app.config.from_pyfile(os.path.realpath(config))
    app.static_folder = app.config.get("STATIC_FOLDER")

    register_exts(app)
    register_bps(app)

    return app
Example #8
0
def create_app():
    app = Flask(__name__, template_folder="views")
    app.static_folder = os.path.abspath("public")

    app.config.from_pyfile("../config/default.py")

    register_database(app)
    register_csrf(app)
    register_jwt(app)
    register_socketio(app)
    register_routes(app)
    register_api(app)
    register_view_filters(app)
    reigster_not_found(app)

    return app
Example #9
0
def create_app(config=None):
    config = "dev" if config is None else config

    app = Flask(__name__)
    app.config.from_object("main.config." + config)

    # Static resources
    app.static_folder = app.config["STATIC_DIR"]

    # Templating
    app.jinja_env.add_extension("pyjade.ext.jinja.PyJadeExtension")

    from main.server.controllers import gui, api

    app.register_blueprint(gui.blueprint)
    app.register_blueprint(api.blueprint, url_prefix="/api")

    return app
Example #10
0
def create_app(config=None):
    app = Flask(__name__, template_folder="templates")
    app.config.from_pyfile("_settings.py")

    if isinstance(config, dict):
        app.config.update(config)
    elif config:
        app.config.from_pyfile(os.path.abspath(config))

    app.static_folder = app.config.get("STATIC_FOLDER")
    app.config.update({"SITE_TIME": datetime.utcnow()})

    register_hooks(app)
    register_jinja(app)
    register_database(app)
    register_mail(app)
    register_routes(app)

    return app
Example #11
0
def create_app():
    """Create the Flask app."""

    app = Flask("modelconvert", static_folder=None)

    app.config.from_object("modelconvert.settings")
    app.config.from_envvar("MODELCONVERT_SETTINGS", silent=True)

    # configure custom static path for serving files during
    # development
    app.static_folder = app.config["STATIC_PATH"]
    app.add_url_rule("/static/<path:filename>", endpoint="static", view_func=app.send_static_file)

    # custom template path, fall back to default
    jinja_loader = jinja2.ChoiceLoader([jinja2.FileSystemLoader(app.config["TEMPLATE_PATH"]), app.jinja_loader])
    app.jinja_loader = jinja_loader

    configure_logging(app)

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

    celery.add_defaults(app.config)

    # configure error handlers
    @app.errorhandler(403)
    def forbidden_page(error):
        return render_template("403.html"), 403

    @app.errorhandler(404)
    def page_not_found(error):
        return render_template("404.html"), 404

    @app.errorhandler(500)
    def server_error_page(error):
        return render_template("500.html"), 500

    if app.config["DEBUG"]:
        from werkzeug.wsgi import SharedDataMiddleware

        app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {"/preview": app.config["DOWNLOAD_PATH"]})

    return app
Example #12
0
def create_app(config=None):
    app = Flask(__name__, template_folder="templates")

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

    if "ARCTIC_SETTINGS" in os.environ:
        app.config.from_envvar("ARCTIC_SETTINGS")

    if isinstance(config, dict):
        app.config.update(config)
    elif config:
        app.config.from_pyfile(os.path.abspath(config))

    app.static_folder = app.config.get("STATIC_FOLDER")
    app.config.update({"SITE_TIME": datetime.datetime.utcnow()})

    # register_jinja(app)
    # register_babel(app)
    register_routers(app)
    register_log(app)
    return app
Example #13
0
def create_app(config=None):
    config = "dev" if config is None else config

    app = Flask(__name__)
    app.config.from_object("glu.config." + config)

    # Static content
    app.static_folder = app.config.get("STATIC_DIR", "assets")

    # Use pyjade templates
    app.jinja_env.add_extension("pyjade.ext.jinja.PyJadeExtension")

    # Cache
    global cache
    cache = redis.Redis(host=app.config["REDIS_HOST"], port=app.config["REDIS_PORT"])

    from glu.views.api import api
    from glu.views.site import site

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

    return app
Example #14
0
def create_app(config=None):
    app = Flask(__name__)
    config = config or {}
    app.config.update(config)
    app.static_folder = app.config.get(keys.STATIC_FOLDER)
    app.api = get_api_instance(app.config)

    flask_gravatar.Gravatar(app)

    env = ViewEnvironment(app.api, app.config)
    app.register_blueprint(lang.create_blueprint(env), url_prefix="/lang")
    app.register_blueprint(auth.create_blueprint(env), url_prefix="/auth")
    app.register_blueprint(users.create_blueprint(env), url_prefix="/users")
    app.register_blueprint(games.create_blueprint(env), url_prefix="/games")
    app.register_blueprint(teams.create_blueprint(env), url_prefix="/teams")
    app.register_blueprint(notifications.create_blueprint(env), url_prefix="/notifications")

    create_logger(app)
    create_filters(app)
    create_bundles(app)
    create_main_views(app)
    initialize_cloudinary(app)

    return app
Example #15
0
File: app.py Project: theorm/apfa
        context["description"] = shorten_blog_content(photoset.get("caption", ""))
    return render_template("photo_set.html", **context)


@app.route("/video/<slug>")
def video(slug):
    video = db.video_by_slug(slug)
    if not video:
        raise NotFound("No such video.")
    context = ctx.get_for_path(["Video", "All", video["title"]])
    context["video"] = video
    return render_template("video.html", **context)


# @app.route('/blog/', defaults = {'page':0})
# @app.route('/blog/<int:page>')
# def blog(page):
# 	page = page
# 	context = ctx.get_for_path(['Blog'])
# 	context['posts'] = db.get_blog_posts(skip=page*POSTS_PER_PAGE,size=POSTS_PER_PAGE)
# 	total_posts = db.get_total_blog_posts()
# 	if page > 0:
# 		context['prev_page'] = page-1
# 	if total_posts > (page+1)*POSTS_PER_PAGE:
# 		context['next_page'] = page+1
# 	return render_template('blog.html', **context)

if __name__ == "__main__":
    if not settings.DEBUG:
        app.static_folder = "assets"
    app.run(debug=settings.DEBUG)
Example #16
0
# -*- coding: utf-8 -*-
import sys

sys.path.append("/opt/x1tool")

from flask import Flask, render_template, request, redirect, url_for
from utils import Utils

# Import server modules
from server.x1server import *

X1Tool = Flask("X1Tool")
utils = Utils()

X1Tool.debug = True
X1Tool.static_folder = "static"

# init x1tool server
X1Server.init_server(X1Tool)
category_list, app_list = utils.get_default_apps()
# Create template data
tpl_data = {"category_list": category_list, "app_list": app_list, "utils": utils}
# print category_list
# print app_list


def write_log(string):
    log = open("flask.log", "a")
    log.write(string + "\n")
    log.close()
import sys
import logging
import tempfile

from flask import Flask
from flask.ext import restful
from flask.ext.sqlalchemy import SQLAlchemy

from config import config_by_name

# Specify Environment via "export DEMO_ENV=<environment_name>"
env = os.getenv("DEMO_ENV") or "dev"

app = Flask(__name__)
app.config.from_object(config_by_name[env])
app.static_folder = app.config.get("STATIC_FOLDER", "")
app.template_folder = app.config.get("TEMPLATES_FOLDER", "")

# Change tmp dir when uploading
# comment this if you want the default one /tmp in linux
tempfile.tempdir = app.config.get("TMP_DIR", "")

# global SQLAlchemy instance
db = SQLAlchemy(app)

# Config for Logging
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s - %(filename)s %(funcName)s: %(message)s"))
stdout_handler.setLevel(logging.DEBUG)
app.logger.addHandler(stdout_handler)
app.logger.setLevel(logging.DEBUG)
Example #18
0
import flask
from flask import Flask, jsonify, Response, request
import json

app = Flask(__name__, static_folder=None)

app.static_folder = "app"
app.add_url_rule("/app/<path:filename>", endpoint="app", view_func=app.send_static_file)
# app.add_url_rule('/query/<path:filename>',
#                 view_func=app.send_static_file)
#

# @app.route('/query/user1/bib/_search', methods = ['GET', 'POST'])
@app.route("/query/user1/bib/_search", methods=["POST"])
def query():
    import requests

    prefix = "http://127.0.0.1:9200/user1/bib/_search"
    # url = '%s?%s' % (prefix, request.query_string)
    url = prefix
    data = request.get_json(force=True)
    # print url
    # print json.dumps(data)
    return Response(requests.post(url, json.dumps(data)).content, content_type="application/json; charset=UTF-8")
    # return jsonify(requests.get(prefix).json())


# app.run(debug=True, port=9000)
app.run(host="0.0.0.0", port=9000)
Example #19
0
    def init(cls, flask_or_import_name, project=None, directory=None, config=None, compress_html=True):
        """
        Allow to register all subclasses of WebPortfolio at once

        If a class doesn't have a route base, it will create a dasherize version
        of the class name.

        So we call it once initiating
        :param flask_or_import_name: Flask instance or import name -> __name__
        :param project: name of the project. If the directory and config is empty, it will guess them from here
        :param directory: The directory containing your project's Views, Templates and Static
        :param config: string of config object. ie: "app.config.Dev"
        :param compress_html: bool - If true it will use the plugin "jinja2htmlcompress"
                to remove white spaces off the html resul
        """

        if isinstance(flask_or_import_name, Flask):
            app = flask_or_import_name
        else:
            app = Flask(flask_or_import_name)

        app.wsgi_app = ProxyFix(app.wsgi_app)

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

        if not directory:
            directory = "application/%s" % project if project else "."

        if not config:
            config = "application.config.%s" % get_env()

        app.config.from_object(config)

        cls._setup_logger(app)

        if directory:
            app.template_folder = directory + "/templates"
            app.static_folder = directory + "/static"

        cls._add_asset_bundle(app.static_folder)

        # Extensions to remove extra white spaces in html
        if compress_html:
            app.jinja_env.add_extension("webportfolio.jinja2htmlcompress.HTMLCompress")

        cls._app = app

        # Flask Assets
        cls.assets = Environment(cls._app)

        # Register templates
        if cls._template_paths:
            loader = [cls._app.jinja_loader] + list(cls._template_paths)
            cls._app.jinja_loader = jinja2.ChoiceLoader(loader)

        # Register static
        if cls._static_paths:
            loader = [cls._app.static_folder] + list(cls._static_paths)
            cls.assets.load_path = loader

        # init_app
        for _app in cls._init_apps:
            _app(cls._app)

        # Register all views
        for subcls in cls.__subclasses__():
            route_base = subcls.route_base
            if not route_base:
                route_base = utils.dasherize(utils.underscore(subcls.__name__))
            subcls.register(cls._app, route_base=route_base)

        # Load all bundles
        [cls.assets.from_yaml(a) for a in cls._asset_bundles]

        @cls._app.after_request
        def _after_request_cleanup(response):
            cls._global["PAGE_META"] = cls._default_page_meta
            cls._global["PAGE_META"]["site_name"] = cls._app.config.get("APPLICATION_NAME", "")
            return response

        return cls._app
Example #20
0
import os
import xbmcaddon
from flask import Flask

__addonpath__ = xbmcaddon.Addon(id="script.webui").getAddonInfo("path")
app = Flask(__name__)

app.root_path = __addonpath__
app.static_path = "/static"
app.static_folder = os.path.join(__addonpath__, "resources", "static")
app.template_folder = os.path.join(__addonpath__, "resources", "templates")
app.add_url_rule(app.static_path + "/<path:filename>", endpoint="static", view_func=app.send_static_file)

from jinja2 import FileSystemLoader

app.jinja_loader = FileSystemLoader(os.path.join(__addonpath__, "resources", "templates"))
Example #21
0
from twisted.internet.defer import inlineCallbacks
from orbit.framing import TEXT
from flask import Flask, render_template, request, session
from orbit.server import WebSocketResource, WSGISiteResource
from orbit.transaction import Transaction, State, TransactionManager
from twisted.web.static import File
from twisted.internet import reactor
from twisted.web.server import Site
from twisted.web.wsgi import WSGIResource
from twisted.python import log
from twisted.web.resource import Resource
import cgi, urlparse, os, treq, sys

app = Flask(__name__)
app.root_path = os.path.join(os.path.dirname(__file__), "..")
app.static_folder = os.path.join(app.root_path, "static")
app.template_folder = os.path.join(app.root_path, "templates")
app.secret_key = "example-secret-key"

imgur_folder = os.path.join(app.static_folder, "imgur")

# The state is what holds all of the important data of our Transaction.
# In this case, the imgur filename to download.
class ImgurDownloadState(State):
    def __init__(self, imgur_filename):
        self.imgur_filename = imgur_filename.encode("utf8")  # for treq

    @inlineCallbacks
    def onNewConnection(self, ws):
        ws.opcode = TEXT
        local_file = os.path.join(imgur_folder, self.imgur_filename)
Example #22
0
import datetime
import os
import random
import sys

from flask import Flask, render_template, request, abort

import utils

app = Flask(__name__)
app.template_folder = os.path.join(os.path.dirname(sys.argv[0]), "templates")

app.static_folder = os.path.join(os.path.dirname(sys.argv[0]), "static")


@app.route("/compliments")
def compliment():
    """Compliments as a service (for my magic mirror)"""
    random_compliments = [
        "You look lovely today!",
        "Hey, good lookin'!",
        "Your smile is contagious.",
        "You should be proud of yourself.",
        "On a scale from 1 to 10, you're an 11.",
        "You're wonderful.",
        "Your hair looks stunning.",
        "You're gorgeous",
    ]
    return str(random.choice(random_compliments))

Example #23
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json

from os.path import dirname
from os.path import join
from flask import Flask

app = Flask(__name__)
app.template_folder = join(dirname(__file__), "templates")
app.static_folder = join(dirname(__file__), "static")


class UserConfig(dict):
    """ loads the json configuration file """

    def _string_decode_hook(self, data):
        rv = {}
        for key, value in data.iteritems():
            if isinstance(key, unicode):
                key = key.encode("utf-8")
            if isinstance(value, unicode):
                value = value.encode("utf-8")
            rv[key] = value
        return rv

    def __init__(self):
        dict.__init__(self)
        configfile = join(dirname(dirname(__file__)), "config.json")
        self.update(json.load(open(configfile), object_hook=self._string_decode_hook))
Example #24
0
        return Response(bson2json(router, sort_keys=True, indent=4), mimetype="application/json")
    else:
        return render_template("router.html", router=router, tileurls=tileurls)


@app.route("/statistics")
def global_statistics():
    hoods = stattools.hoods()
    return render_template(
        "statistics.html",
        stats=db.stats.find({}, {"_id": 0}),
        clients=stattools.total_clients(),
        router_status=stattools.router_status(),
        router_models=stattools.router_models(),
        router_firmwares=stattools.router_firmwares(),
        hoods=hoods,
        hoods_sum=stattools.hoods_sum(),
        newest_routers=db.routers.find({}, {"hostname": 1, "hood": 1, "created": 1})
        .sort("created", pymongo.DESCENDING)
        .limit(len(hoods) + 1),
    )


app.secret_key = os.urandom(24)

if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True)
else:
    app.template_folder = "/usr/share/ffmap/templates"
    app.static_folder = "/usr/share/ffmap/static"
    # app.debug = True
Example #25
0
import hashlib
from datetime import datetime

# flask dependencies
from flask import Flask
from flask import jsonify
from werkzeug.exceptions import NotFound

# ofcourse
from .render import render_init, render_template
from ofcourse.util import count_posts, app_path
from ofcourse.blueprints import homework, lectures, quizzes
from ofcourse.participants import participants_bp

app = Flask(__name__)
app.static_folder = app_path("static")
app.templates_folder = app_path("templates")
app.people_folder = app_path("people")
render_init(app)


# Automatically include site config
@app.context_processor
def inject_yaml():
    with open(app_path("site.yaml")) as site_yaml:
        site_config = yaml.safe_load(site_yaml)

        course_url = "http://localhost:5000/"

        if site_config["course"].get("public_url", None) is not None:
            course_url = site_config["course"]["public_url"]
Example #26
0
File: app.py Project: orf/simple
from simple.bing_images import get_latest_header_images
from simple.util import iter_to_stream, Pagination, slugify


if not os.getcwd() in sys.path:
    sys.path.append(os.getcwd())

app = Flask(__name__)
app.config.update(
    PERSONA_JS="https://login.persona.org/include.js", PERSONA_VERIFIER="https://verifier.login.persona.org/verify"
)
app.config.from_object("simple_settings")
app.secret_key = app.config["SECRET_KEY"]

if not app.config["DEBUG"]:
    app.static_folder = os.path.join(os.getcwd(), "static")

db = orm.Database("sqlite", os.path.join(os.getcwd(), app.config["DATABASE_FILE"]), create_db=True)
cache = FileSystemCache(app.config["CACHE_DIR"])
csrf = SeaSurf(app)
basic_auth = BasicAuth(app)
app.config["UPLOAD_FOLDER"] = os.path.join(os.getcwd(), "uploads")
ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg", "gif"}

app.jinja_env.globals.update(now=datetime.datetime.now)

md = markdown.Markdown(extensions=["fenced_code", "toc"], output_format="html5")


class Post(db.Entity):
    _table_ = "posts"
Example #27
0
File: msg_web.py Project: zhmsg/dms
def create_app():
    msg_web = Flask("__name__")
    msg_web.secret_key = "meisanggou"
    login_manager.init_app(msg_web)

    @msg_web.before_request
    def before_request():
        test_r, info = normal_request_detection(request.headers, request.remote_addr)
        if test_r is False:
            return make_response(info, 403)
        g.request_IP_s, g.request_IP = info
        if current_user.is_authenticated:
            g.user_role = current_user.role
            g.user_name = current_user.user_name
            if g.user_name in user_blacklist:
                message = u"不好意思,您的帐号存在异常,可能访问本系统出现不稳定的想象,现在就是不稳定中。本系统不是很智能,所以不知道啥时候会稳定,也许一分钟,也许一天,也许。。。"
                if "X-Requested-With" in request.headers:
                    return jsonify({"status": False, "data": message})
                return message
        else:
            g.user_role = 0

    @msg_web.after_request
    def after_request(res):
        if res.status_code == 302 or res.status_code == 301:
            if "X-Request-Protocol" in request.headers:
                pro = request.headers["X-Request-Protocol"]
                if "Location" in res.headers:
                    location = res.headers["location"]
                    if location.startswith("http:"):
                        res.headers["Location"] = pro + ":" + res.headers["Location"][5:]
                    elif location.startswith("/"):
                        res.headers["Location"] = "%s://%s%s" % (pro, request.headers["Host"], location)
        if "download_file" in g:
            try:
                os.system("rm -rf %s" % g.download_file)
            except Exception as e:
                print(e)
        res.headers["Server"] = "JingYun Server"
        return res

    @msg_web.errorhandler(500)
    def handle_500(e):
        return str(e)

    msg_web.session_interface = RedisSessionInterface(prefix=session_id_prefix)

    msg_web.static_folder = "static2"
    msg_web.add_url_rule("/static2" + "/<path:filename>", endpoint="static2", view_func=msg_web.send_static_file)
    msg_web.session_cookie_name = session_cookie_name
    if cookie_domain != "":
        msg_web.config.update(SESSION_COOKIE_DOMAIN=cookie_domain)
    msg_web.config.update(PERMANENT_SESSION_LIFETIME=600)

    api_files = os.listdir("./views")
    for api_file in api_files:
        if api_file.endswith("_view.py"):
            __import__("Web.views.%s" % api_file[:-3])

    from Web import blues

    for key, value in blues.items():
        if len(value[1]) > 1:
            msg_web.register_blueprint(value[0], url_prefix=value[1])
        else:
            msg_web.register_blueprint(value[0])

    env = msg_web.jinja_env
    env.globals["current_env"] = current_env
    env.globals["role_value"] = control.role_value
    env.globals["menu_url"] = dms_url_prefix + "/portal/"
    env.filters["unix_timestamp"] = unix_timestamp
    env.filters["bit_and"] = bit_and
    env.filters["ip_str"] = ip_str
    env.filters["make_static_url"] = make_static_url
    env.filters["make_default_static_url"] = make_default_static_url
    env.filters["make_static_html"] = make_static_html
    return msg_web
Example #28
0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from flask import Flask

app = Flask(__name__)


@app.route("/")
def index():
    return "It’s working!!!"


@app.route("/hola/<string:elephants>/<int:a>/<int:b>")
def hello(elephants, a, b):
    user = {"first_name": elephants, "last_name": "Chebib", "sum": a + b}
    return "Hello {first_name} {last_name}. <br /> {sum} ☺".format(**user)


if __name__ == "__main__":
    app.static_folder = "../static"
    app.static_url_path = "static"
    app.debug = True
    app.run()
Example #29
0
from flask import Flask
from flask.ext.assets import Bundle
from flask.ext.rq import RQ
from flask.ext.mail import Mail
from flask.ext.lastuser import Lastuser
from flask.ext.lastuser.sqlalchemy import UserManager
from baseframe import baseframe, assets, Version
import coaster.app
from ._version import __version__


# First, make an app and config it

app = Flask(__name__, instance_relative_config=True, static_folder=None)
app.static_folder = "static"
mail = Mail()
lastuser = Lastuser()

# Second, setup assets
version = Version(__version__)
assets["hasjob.js"][version] = "js/app.js"
assets["hasjob.css"][version] = "css/app.css"

# Third, after config, import the models and views

from . import models, views
from .models import db


# Configure the app
Example #30
0
from setman.utils.parsing import is_settings_container


if "LOGGING" in os.environ:
    logging.basicConfig(level=logging.INFO)

DIRNAME = os.path.abspath(os.path.dirname(__file__))
rel = lambda *parts: os.path.abspath(os.path.join(DIRNAME, *parts))

SETMAN_ADDITIONAL_TYPES = ("testapp.utils.IPAddressSetting",)
SETMAN_SETTINGS_FILES = {"namespace": rel("namespace.cfg")}

app = Flask(__name__)
app.config.from_object(__name__)
app.secret_key = "t:\xc6\x1d\xcd\x86\xb7_\x11\x1e\xfe\xc1AD\x9f>"
app.static_folder = rel("..", "..", "testproject-django", "media")

settings.configure(
    framework="setman.frameworks.flask_setman",
    app=app,
    backend="setman.backends.filebased",
    filename=rel("..", "settings.json"),
    format="json",
)


@app.route("/docs")
@app.route("/docs/<path>")
def docs(path=None):
    """
    View instructions on how to build documentation.