Beispiel #1
1
def test_gravatar_url():
    """Test that the gravatar url is generated correctly"""
    app = Flask(__name__)

    with app.test_request_context("/"):
        app.debug = True
        url = gravatar_url("test@test.com")
        eq_(url, "http://www.gravatar.com/avatar/" "b642b4217b34b1e8d3bd915fc65c4452?d=mm")

        url = gravatar_url("test@test.com", 200)
        eq_(url, "http://www.gravatar.com/avatar/" "b642b4217b34b1e8d3bd915fc65c4452?s=200&d=mm")

        app.debug = False

        url = gravatar_url("test@test.com")
        eq_(url, "http://www.gravatar.com/avatar/" "b642b4217b34b1e8d3bd915fc65c4452?d=mm")

        app.config["SITE_URL"] = "http://www.site.com"

        url = gravatar_url("test@test.com")
        eq_(
            url,
            "http://www.gravatar.com/avatar/"
            "b642b4217b34b1e8d3bd915fc65c4452"
            "?d=http%3A%2F%2Fwww.site.com%2Fstatic%2Fimg%2Fdefault-avatar.png",
        )
Beispiel #2
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
Beispiel #3
1
def create_app(config_filename=None):
    app = Flask(__name__, instance_relative_config=True)
    if app.config.from_pyfile("settings.conf", silent=True):
        print "Settings loaded from local instance"
    if app.config.from_envvar("RSVP_CONF", silent=True):
        print "Settings loaded from ENVVAR"
    if app.config["DEBUG"]:
        app.debug = True

    log_formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")
    root_logger = logging.getLogger("werkzeug")
    if app.config["DEBUG"]:
        root_logger.setLevel(logging.DEBUG)
    file_handler = logging.FileHandler("{}/{}".format(app.config["LOGDIR"], "rsvp.log"))
    file_handler.setFormatter(log_formatter)
    root_logger.addHandler(file_handler)
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(log_formatter)
    root_logger.addHandler(console_handler)

    from extensions import db
    import models

    db.init_app(app)
    models.create_all(app)

    from views import views_bp

    app.register_blueprint(views_bp)
    return app
Beispiel #4
1
def run_flask():
    root_dir = os.path.join(os.getcwd(), "web")
    app = Flask(__name__, static_folder=root_dir)
    app.use_reloader = False
    app.debug = False
    app.config["SECRET_KEY"] = "OpenPoGoBot"
    socketio = SocketIO(app, logging=False, engineio_logger=False)

    logging_buffer = []

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

    @app.route("/<path:path>")
    def static_proxy(path):
        return app.send_static_file(path)

    @manager.on("logging")
    def logging_event(event_name, output, color):
        line = {"output": output, "color": color}
        logging_buffer.append(line)
        socketio.emit("logging", [line], namespace="/event")

    @socketio.on("connect", namespace="/event")
    def connect():
        emit("logging", logging_buffer, namespace="/event")
        logger.log("Client connected", "yellow", fire_event=False)

    @socketio.on("disconnect", namespace="/event")
    def disconnect():
        logger.log("Client disconnected", "yellow", fire_event=False)

    socketio.run(app, host="0.0.0.0", port=8000, debug=False, use_reloader=False, log_output=False)
Beispiel #5
1
def create_app():
    app = Flask(__name__)
    app.debug = True
    app.secret_key = urandom(24)

    # 注册蓝本
    from .news import news as news_blueprint

    app.register_blueprint(news_blueprint)

    from .query import query as query_blueprint

    app.register_blueprint(query_blueprint)

    from .main import main as main_blueprint

    app.register_blueprint(main_blueprint)

    from .kebiao import kebiao as kebiao_blueprint

    app.register_blueprint(kebiao_blueprint)

    from .repair import repair as repair_blueprint

    app.register_blueprint(repair_blueprint)

    return app
def app():
    app = Flask(__name__)
    app.debug = True
    api = Api(app)

    class User(object):
        def __init__(self, name):
            self.name = name

    class Hello(Resource):
        name = "name&required&default='world'"
        date_in = {"validater": "datetime", "input": True, "default": datetime.utcnow}
        date_out = "datetime&required&output"
        schema_inputs = {"get": {"name": name}, "get_user": {"name": name}, "post": {"date": date_in}}
        schema_outputs = {
            "get": {"hello": "unicode&required"},
            "get_user": {"user": {"name": name}},
            "post": {"date": date_out},
        }
        output_types = [User]

        def get(self, name):
            return {"hello": name}

        def get_user(self, name):
            return {"user": User(name)}

        def post(self, date):
            return {"date": date}

    api.add_resource(Hello)
    return app
Beispiel #7
1
def create_app(config, debug=True):
    app = Flask(__name__)
    app.debug = debug
    app.config["SECRET_KEY"] = "secret"
    app.config["SECURITY_POST_LOGIN_VIEW"] = "/profile"
    app.config.from_object(Config)

    if config:
        for key, value in config.items():
            app.config[key] = value

    app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)

    @app.route("/")
    def index():
        return render_template("index.html", content="Home Page")

    @app.route("/profile")
    @login_required
    def profile():
        twitter = current_app.social.twitter
        twitter.get_api()

        return render_template(
            "profile.html",
            content="Profile Page",
            twitter_conn=twitter.get_connection(),
            google_conn=current_app.social.google.get_connection(),
            facebook_conn=current_app.social.facebook.get_connection(),
            foursquare_conn=current_app.social.foursquare.get_connection(),
        )

    return app
def create_test_app(debug=False, config=None):
    app = Flask(__name__)
    app.debug = debug

    if config:
        app.config.update(**config)
    return app
def test_parse_schema():
    hello = {"hello": "safestr&required"}
    sche_inputs = {
        "get": {"name": "name&default='world'"},
        "post_login": {"name": "name&default='world'", "password": "password&required"},
    }
    sche_outputs = {"get": hello, "post_login": hello}

    class Hello(Resource):

        schema_inputs = sche_inputs
        schema_outputs = sche_outputs
        output_types = [Flask]

        def get(self, name):
            pass

        def post_login(self, name, password):
            pass

    app = Flask(__name__)
    app.debug = True
    api = Api(app)
    api.add_resource(Hello)

    assert Hello.schema_inputs == validater.parse(sche_inputs)
    assert Hello.schema_outputs == validater.parse(sche_outputs)
    assert Hello.output_types == [Flask]
Beispiel #10
0
def create_app(app_state):
    app = Flask(__name__)
    app.debug = True

    if getattr(sys, "frozen", None):
        # set root_path to data dir from PyInstaller
        basedir = sys._MEIPASS
        app.root_path = os.path.join(basedir, os.path.join(*__name__.split(".")))

    app.config.geobox_state = app_state

    app.config["SECRET_KEY"] = app_state.config.get("web", "secret_key")

    from . import views

    app.register_blueprint(views.main)
    app.register_blueprint(views.editor)
    app.register_blueprint(views.tasks)
    app.register_blueprint(views.project)
    app.register_blueprint(views.admin)
    app.register_blueprint(views.vector)
    app.register_blueprint(views.downloads)
    app.register_blueprint(views.proxy)
    app.register_blueprint(views.boxes)
    app.register_blueprint(views.raster)

    @app.before_request
    def before_request():
        g.db = app_state.user_db_session()
        if request_for_static():
            return

        gbi_server = g.db.query(GBIServer).all()

        if len(gbi_server) == 0 and request.endpoint not in (
            "admin.initial_set_server",
            "admin.set_server",
            "admin.add_server",
        ):
            return redirect(url_for("admin.initial_set_server"))

    @app.teardown_request
    def teardown_request(exception):
        """Closes the database again at the end of the request."""
        if hasattr(g, "db"):
            g.db.close()

    from .helper import css_alert_category, add_auth_to_url
    import geobox.app

    app.jinja_env.globals.update(
        css_alert_category=css_alert_category,
        add_auth_to_url=add_auth_to_url,
        app_state=app_state,
        geobox_client_version=geobox.app.version,
    )

    configure_i18n(app, app_state.locale())
    configure_errorhandlers(app)
    return app
Beispiel #11
0
def create_app(ignore_exceptions=None, debug=False):
    import os

    app = Flask(__name__)
    app.config["SECRET_KEY"] = os.urandom(40)
    app.debug = debug

    if ignore_exceptions:
        app.config["RAVEN_IGNORE_EXCEPTIONS"] = ignore_exceptions

    @app.route("/an-error/", methods=["GET", "POST"])
    def an_error():
        raise ValueError("hello world")

    @app.route("/capture/", methods=["GET", "POST"])
    def capture_exception():
        try:
            raise ValueError("Boom")
        except:
            current_app.extensions["sentry"].captureException()
        return "Hello"

    @app.route("/message/", methods=["GET", "POST"])
    def capture_message():
        current_app.extensions["sentry"].captureMessage("Interesting")
        return "World"

    @app.route("/an-error-logged-in/", methods=["GET", "POST"])
    def login():
        login_user(User())
        raise ValueError("hello world")

    return app
Beispiel #12
0
def create_app(config=None):
    app = Flask(__name__, static_url_path="/static")

    # configをtlsに保存して、2回目以降呼び出したときにもmanage.pyで指定したconfigにアクセスする
    if config:
        tls.config_path = config
    if hasattr(tls, "config_path"):
        config_path = tls.config_path
        config = os.path.join(app.root_path, config_path)

    # config未設定のときはdefault configを読む
    if config is None:
        config = os.path.join(app.root_path, "config/config_local.py")

    app.config.from_pyfile(config)
    app.debug = app.config.get("debug")

    # 機能毎のURLを定義
    app.register_blueprint(site_top.app, url_prefix="/")
    app.register_blueprint(sitemap.app, url_prefix="/sitemap")
    app.register_blueprint(image.app, url_prefix="/img")
    app.register_blueprint(vote.app, url_prefix="/vote")
    app.register_blueprint(root.app, url_prefix="/<site_title>")
    app.register_blueprint(dat.app, url_prefix="/<site_title>/dat")

    # log
    handler = RotatingFileHandler("/tmp/log/error.log", maxBytes=1024 * 1024 * 10, backupCount=1)
    handler.setLevel(logging.DEBUG)
    app.logger.addHandler(handler)

    return app
Beispiel #13
0
def get_flask_application(core):
    application = Flask(__name__)
    application.debug = True
    for app in core.apps:
        for url, view in app.get_urls():
            application.add_url_rule(url, view.__class__.__name__, view(core))
    return application
Beispiel #14
0
    def setUp(self):
        app = Flask(__name__)
        app.debug = True
        app.secret_key = "1234"

        self.app = app

        csrf = SeaSurf()
        csrf._csrf_disable = False
        self.csrf = csrf

        # Initialize CSRF protection.
        self.csrf.init_app(app)
        self.csrf.exempt_urls(("/foo",))

        @app.route("/foo/baz", methods=["POST"])
        def foobaz():
            return "bar"

        @app.route("/foo/quz", methods=["POST"])
        def fooquz():
            return "bar"

        @app.route("/bar", methods=["POST"])
        def bar():
            return "foo"
Beispiel #15
0
def main():
    app = Flask(__name__)
    app.config.update(DB_CONNECTION_STRING=":memory:", CACHE_TYPE="simple", SQLALCHEMY_DATABASE_URI="sqlite://")
    app.debug = True
    injector = init_app(app=app, modules=[AppModule])

    configure_views(app=app, cached=injector.get(Cache).cached)

    post_init_app(app, injector)

    client = app.test_client()

    response = client.get("/")
    print("%s\n%s%s" % (response.status, response.headers, response.data))
    response = client.post("/", data={"key": "foo", "value": "bar"})
    print("%s\n%s%s" % (response.status, response.headers, response.data))
    response = client.get("/")
    print("%s\n%s%s" % (response.status, response.headers, response.data))
    response = client.get("/hello")
    print("%s\n%s%s" % (response.status, response.headers, response.data))
    response = client.delete("/hello")
    print("%s\n%s%s" % (response.status, response.headers, response.data))
    response = client.get("/")
    print("%s\n%s%s" % (response.status, response.headers, response.data))
    response = client.get("/hello")
    print("%s\n%s%s" % (response.status, response.headers, response.data))
    response = client.delete("/hello")
    print("%s\n%s%s" % (response.status, response.headers, response.data))
Beispiel #16
0
def create_app(config_filename):
    app = Flask(__name__)
    app.debug = True
    app.config.from_pyfile(config_filename)
    db.init_app(app)
    moment.init_app(app)
    bootstrap.init_app(app)
    login_manager.init_app(app)

    from .main import main as main_blueprint

    app.register_blueprint(main_blueprint)

    from .auth import auth as auth_blueprint

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

    from .student import student as student_blueprint

    app.register_blueprint(student_blueprint, url_prefix="/student")

    from .faculty import faculty as faculty_blueprint

    app.register_blueprint(faculty_blueprint, url_prefix="/faculty")

    from .staff import staff as staff_blueprint

    app.register_blueprint(staff_blueprint, url_prefix="/staff")

    app.jinja_env.globals.update(title=str.title, iteritems=dict.iteritems, len=len)
    return app
Beispiel #17
0
def create_app(config, debug=False, testing=False, config_overrides=None):
    app = Flask(__name__)
    app.config.from_object(config)

    app.debug = debug
    app.testing = testing

    if config_overrides:
        app.config.update(config_overrides)

    # Setup the data model.
    with app.app_context():
        model = get_model()
        model.init_app(app)

    # Register the Bookshelf CRUD blueprint.
    from .user_crud import user_crud

    app.register_blueprint(user_crud, url_prefix="/users")

    # Add a default root route.
    @app.route("/")
    def index():
        return redirect(url_for("user_crud.list"))

    return app
Beispiel #18
0
def main():
    try:
        # init
        lModel = RangeManager(int(sys.argv[1]), int(sys.argv[2]))

        monkey.patch_all()
        lApp = Flask(__name__)
        lApp.debug = True
        lApi = Api(lApp)
        FetchRange.sModel = lModel
        Report.sModel = lModel
        Progress.sModel = lModel
        Reset.sModel = lModel
        PushNamespace.sModel = lModel

        # routes
        lApp.add_url_rule("/", "poll", poll)
        lApp.add_url_rule("/socket.io/<path:path>", "socket.io", run_socketio)
        lApi.add_resource(FetchRange, "/fetch")
        lApi.add_resource(Report, "/report")
        lApi.add_resource(Progress, "/progress")
        lApi.add_resource(Reset, "/reset")

        # go
        lApp = SharedDataMiddleware(lApp, {})
        lServer = SocketIOServer(("0.0.0.0", 5000), lApp, resource="socket.io", policy_server=False)
        lServer.serve_forever()
    except IndexError:
        print "Usage: " + sys.argv[0] + " <number of ranges> <timeout per range>"
    except KeyboardInterrupt:
        lServer.stop()
Beispiel #19
0
def createapp():
    demo = "-d" in sys.argv
    # app.config["APPLICATION_ROOT"] = "/socialapi-directory"
    app = Flask(__name__)
    app.debug = True
    # app.config.from_pyfile('babel.cfg')
    babel = Babel(app)

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

    bp = Blueprint("bp", __name__)

    def get_supported_locales():
        langs = {}
        langs["en-US"] = "English (US)"
        for b in babel.list_translations():
            if b.territory:
                langs["%s-%s" % (b.language, b.territory)] = b.display_name
            else:
                langs[b.language] = b.display_name
        return langs

    @babel.localeselector
    def get_locale():
        print [str(b) for b in babel.list_translations()]
Beispiel #20
0
def create_app(config_name):
    app = Flask(__name__)
    app.debug = True
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    login_manager.init_app(app)
    pagedown.init_app(app)

    db = SQLAlchemy(app)
    bootstrap = Bootstrap(app)
    moment = Moment(app)
    manager = Manager(app)
    mail = Mail(app)
    migrate = Migrate(app, db)
    manager.add_command("db", MigrateCommand)

    from .main import main as main_blueprint

    app.register_blueprint(main_blueprint)

    from .auth import auth as auth_blueprint

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

    from .api_1_0 import api as api_1_0_blueprint

    app.register_blueprint(api_1_0_blueprint, url_prefix="/api/v1.0")

    if not app.debug and not app.testing and not app.config["SSL_DISABLE"]:
        from flask.ext.sslify import SSLify

        sslify = SSLify(app)

    return app
Beispiel #21
0
def create_app(debug=False):
    """
    Dynamically create a flask api app
    """

    app = Flask(__name__, template_folder="templates", static_folder="assets")

    app.config.from_object("wbaw.common.settings")
    app.debug = debug

    # Register blueprints
    from wbaw.web.blueprints.api.views import api_blueprint

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

    from blueprints.api.views import Main

    register_api(app, Main, "main_api", "/")

    from blueprints.api.views import Search

    register_api(app, Search, "search_api", "/search")

    from blueprints.api.views import Rss

    register_api(app, Rss, "rss_api", "/feeds/recently_added.xml")

    from blueprints.api.views import Atom

    register_api(app, Atom, "atom_api", "/feeds/recently_added.atom")

    # from .blueprints.api.views import Watches
    # register_api(app, Watches, 'watches_api', '/watches/')

    return app
def cmd():
    import argparse

    parser = argparse.ArgumentParser(description="Capitains Nemo CTS UI")
    parser.add_argument("endpoint", metavar="endpoint", type=str, help="CTS API Endpoint")
    parser.add_argument("--port", type=int, default=8000, help="Port to use for the HTTP Server")
    parser.add_argument("--host", type=str, default="127.0.0.1", help="Host to use for the HTTP Server")
    parser.add_argument("--inventory", type=str, default=None, help="Inventory to request from the endpoint")
    parser.add_argument("--css", type=str, default=None, nargs="*", help="Full path to secondary css file")
    parser.add_argument(
        "--groupby", type=int, default=25, help="Number of passage to group in the deepest level of the hierarchy"
    )
    parser.add_argument("--debug", action="store_true", default=False, help="Set-up the application for debugging")

    args = parser.parse_args()

    if args.endpoint:
        app = Flask(__name__)
        # We set up Nemo
        nemo = Nemo(
            app=app,
            name="nemo",
            base_url="",
            css=args.css,
            inventory=args.inventory,
            api_url=args.endpoint,
            chunker={"default": lambda x, y: Nemo.level_grouper(x, y, groupby=args.groupby)},
        )

        # We run the app
        app.debug = args.debug
        app.run(port=args.port, host=args.host)
def create_app():
    app = Flask(__name__, static_folder=os.path.join(PROJECT_ROOT, "public"), static_url_path="/public")

    app.config.update(os.environ)

    # TODO: read in right hand side from HT config vars
    app.config["SECRET_KEY"] = "secret"
    app.config["SECURITY_PASSWORD_HASH"] = "bcrypt"
    app.config["MONGODB_DB"] = "flask_security_test"
    app.config["MONGODB_HOST"] = "localhost"
    app.config["MONGODB_PORT"] = 27017

    app.debug = app.config["X_HT_DEBUG"] == "True"

    app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {"/": os.path.join(os.path.dirname(__file__), "public")})

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

    SecuritySetup(app)

    # import & register blueprints here:
    # ===================================
    from hero_tmpl.views.security import security

    app.register_blueprint(security)

    from hero_tmpl.views.misc import misc

    app.register_blueprint(misc)

    return app
Beispiel #24
0
def createapp():
    demo = "-d" in sys.argv
    app = Flask(__name__)
    if "--debug" in sys.argv:
        app.debug = True
    app.url_map.converters["regex"] = RegexConverter
    babel = Babel(app)

    config = json.load(app.open_resource("config.json"), object_pairs_hook=collections.OrderedDict)

    @app.context_processor
    def utility_processor():
        return dict(createDataURL=createDataURL)

    def get_supported_locales():
        langs = {}
        for b in babel.list_translations():
            if not demo and str(b) not in TRANSLATIONS:
                # print str(b)," is not in ",TRANSLATIONS
                continue
            if b.territory:
                langs["%s-%s" % (b.language, b.territory)] = b.display_name
            else:
                langs[b.language] = b.display_name
        return langs

    @babel.localeselector
    def get_locale():
        print [str(b) for b in babel.list_translations()]
Beispiel #25
0
def create_app():
    app = Flask(__name__)
    app.config.from_object("mbref.conf.{}".format(os.environ.get("ENV_NAME", "dev")))
    app.debug = app.config["DEBUG"]
    load_views(app, mbref.www.api)
    db.init_app(app)
    return app
Beispiel #26
0
def main():
    parser = argparse.ArgumentParser(description="Run a Senpy server")
    parser.add_argument("--level", "-l", metavar="logging_level", type=str, default="INFO", help="Logging level")
    parser.add_argument("--debug", "-d", action="store_true", default=False, help="Run the application in debug mode")
    parser.add_argument("--default-plugins", action="store_true", default=False, help="Load the default plugins")
    parser.add_argument("--host", type=str, default="127.0.0.1", help="Use 0.0.0.0 to accept requests from any host.")
    parser.add_argument("--port", "-p", type=int, default=SERVER_PORT, help="Port to listen on.")
    parser.add_argument("--plugins-folder", "-f", type=str, default="plugins", help="Where to look for plugins.")
    parser.add_argument(
        "--only-install",
        "-i",
        action="store_true",
        default=False,
        help="Do not run a server, only install the dependencies of the plugins.",
    )
    args = parser.parse_args()
    logging.basicConfig()
    rl = logging.getLogger()
    rl.setLevel(getattr(logging, args.level))
    app = Flask(__name__)
    app.debug = args.debug
    sp = Senpy(app, args.plugins_folder, default_plugins=args.default_plugins)
    if args.only_install:
        sp.install_deps()
        return
    sp.activate_all()
    http_server = WSGIServer((args.host, args.port), app)
    try:
        print("Senpy version {}".format(senpy.__version__))
        print("Server running on port %s:%d. Ctrl+C to quit" % (args.host, args.port))
        http_server.serve_forever()
    except KeyboardInterrupt:
        http_server.stop()
        print("Bye!")
Beispiel #27
0
def create_backend_app(service):
    from werkzeug.routing import Map

    # Create the backend_app
    backend_app = Flask(__name__)
    backend_app.debug = True
    backend_app.service = service

    # Reset view functions to reset the app
    backend_app.view_functions = {}
    backend_app.url_map = Map()
    backend_app.url_map.converters["regex"] = RegexConverter
    backend = BACKENDS[service]
    for url_path, handler in backend.flask_paths.items():
        if handler.__name__ == "dispatch":
            endpoint = "{0}.dispatch".format(handler.__self__.__name__)
        else:
            endpoint = None

        if endpoint in backend_app.view_functions:
            # HACK: Sometimes we map the same view to multiple url_paths. Flask
            # requries us to have different names.
            endpoint += "2"

        backend_app.add_url_rule(
            url_path,
            endpoint=endpoint,
            methods=HTTP_METHODS,
            view_func=convert_flask_to_httpretty_response(handler),
            strict_slashes=False,
        )

    backend_app.test_client_class = AWSTestHelper
    return backend_app
Beispiel #28
0
def main():
    try:
        # init
        #        lModel = RangeManager(int(sys.argv[1]), int(sys.argv[2]))

        monkey.patch_all()
        lApp = Flask(__name__)
        lApp.debug = True
        lApi = Api(lApp)
        #        FetchRange.sModel = lModel
        #        Report.sModel = lModel
        #        Progress.sModel = lModel
        #        Reset.sModel = lModel
        #        PushNamespace.sModel = lModel

        #  routes
        lApp.add_url_rule("/", "start", start)
        #        lApp.add_url_rule('/socket.io/<path:path>', 'socket.io', run_socketio)

        lApi.add_resource(Busses, "/busses")
        lApi.add_resource(IOConfig, "/ioconfig")
        lApi.add_resource(Set, "/set")
        lApi.add_resource(Get, "/get")
        lApi.add_resource(Dump, "/dump")
        lApi.add_resource(Detect, "/detect")

        # go
        #        lApp = SharedDataMiddleware(lApp, {})
        lServer = SocketIOServer(("0.0.0.0", 5000), lApp, resource="socket.io", policy_server=False)
        lServer.serve_forever()
    except IndexError:
        print "Usage: " + sys.argv[0] + " <number of ranges> <timeout per range>"
    except KeyboardInterrupt:
        lServer.stop()
Beispiel #29
0
def create_app(config=ProdConfig):
    app = Flask(__name__, static_url_path="")
    app.config.from_object(config)
    app.debug = app.config["DEBUG"]
    register_blueprints(app)
    register_extensions(app)
    register_context_processors(app)
    register_errorhandler(app)

    @app.before_first_request
    def before_first_request():
        if app.debug and not app.testing:
            app.logger.setLevel(logging.DEBUG)
        elif app.testing:
            app.logger.setLevel(logging.CRITICAL)
        else:
            stdout = logging.StreamHandler(sys.stdout)
            stdout.setFormatter(
                logging.Formatter(
                    "%(asctime)s | %(name)s | %(levelname)s \
                in %(module)s [%(pathname)s:%(lineno)d]: %(message)s"
                )
            )
            app.logger.addHandler(stdout)
            app.logger.setLevel(logging.DEBUG)

    return app
Beispiel #30
0
def test_config():
    app = Flask(__name__)
    app.config.from_object("testdata.config")
    app.debug = True
    configs = [
        "resource_json",
        "permission_json",
        "auth_header",
        "auth_token_name",
        "auth_secret",
        "auth_alg",
        "auth_exp",
        "resjs_name",
        "resdocs_name",
        "bootstrap",
    ]
    bp = Blueprint("blueprint", __name__)
    api_bp = Api(bp)
    api_app = Api(app)
    api_no_app = Api()
    for k in configs:
        key = "API_" + k.upper()
        assert key in app.config
        assert app.config[key] == key
        assert hasattr(api_app, k)
        assert getattr(api_app, k) == key

        assert getattr(api_no_app, k) != key
        # inited with blue_print can't load configs
        assert getattr(api_bp, k) != key

    api_bp.config(app.config)
    for k in configs:
        key = "API_" + k.upper()
        assert getattr(api_bp, k) == key