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

    # Configure logging
    handler = logging.FileHandler(app.config["LOGGING_LOCATION"])
    handler.setLevel(app.config["LOGGING_LEVEL"])
    formatter = logging.Formatter(app.config["LOGGING_FORMAT"])
    handler.setFormatter(formatter)
    app.logger.addHandler(handler)

    bootstrap.init_app(app)
    mail.init_app(app)
    db.init_app(app)
    admin.init_app(app)

    from .main import main as main_blueprint

    app.register_blueprint(main_blueprint)

    from .userManagement import userMngmt as userMngmt_blueprint

    app.register_blueprint(userMngmt_blueprint, url_prefix="/userManagement")

    return app
Example #2
1
 def testAddEvent(self):
     app = Flask(__name__)
     conn = Connection()
     with app.test_client() as c:
         testRequest = c.get(
             "/event.json?activity=testing"
             "&variables=victory&types="
             "bool&officials=tester&descr=testing%20stuff&"
             "id=testing123&_username=tester&_session=1234"
         )
         expected = {
             "activity": "testing",
             "descr": "testing stuff",
             "fields": ["participants", "victory"],
             "types": ["varchar", "bool"],
             "officials": ["tester"],
             "id": "testing123",
             "rstarts": [],
             "checks": [],
             "rends": [],
         }
         db = conn.test_db
         statserv.server.database = conn.test_db
         statserv.server.sessions["1234"] = ("tester", None, True)
         statserv.server.add_event(request)
         actual = db.stattrtbls.find_one({})
         del actual["_id"]
         self.assertEquals(
             expected,
             actual,
             "The add_event method added something other than "
             "what we expected. Expected: `%s`, "
             "actual: `%s`." % (expected, actual),
         )
         conn.drop_database("test_db")
Example #3
1
 def testAddResults(self):
     app = Flask(__name__)
     conn = Connection()
     with app.test_client() as c:
         testRequest = c.get(
             "/results.json?_username=tester&_session=1234&"
             "_method=POST&results=tester&results=true&"
             "event=testing123"
         )
         event = {"id": "testing123", "fields": ["participants", "victory"], "types": ["varchar", "bool"]}
         db = conn.test_db
         db.stattrtbls.insert(event)
         del event["_id"]
         result = {"participants": ["tester"], "victory": [True]}
         statserv.server.sessions["1234"] = ("tester", None, True)
         statserv.server.database = conn.test_db
         statserv.server.add_results()
         actual = db.testing123.find_one({})
         del actual["_id"]
         self.assertEquals(
             result,
             actual,
             "The add_results method did something we didn't "
             "expect. Expected: `%s`, actual: `%s`." % (result, actual),
         )
         conn.drop_database("test_db")
Example #4
1
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    pagedown.init_app(app)

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

        sslify = SSLify(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")

    return app
Example #5
1
 def testGetTpls(self):
     app = Flask(__name__)
     with app.test_client() as c:
         testRequest = c.get("/tpls.json?which=asdfjdskfjs")
         self.assertEquals(
             statserv.server.send_error(request, "template does" " not exist"),
             statserv.server.get_tpls(),
             "The get_tpls method really shouldn't try to send " "back a template for 'asdfjdskfjs.'",
         )
     tplsempty = False
     with app.test_client() as c:
         testRequest = c.get("/tpls.json?which=")
         tplsempty = statserv.server.get_tpls()
     with app.test_client() as c:
         testRequest = c.get("/tpls.json?which=all")
         self.assertEquals(
             statserv.server.get_tpls(),
             tplsempty,
             "The get_tpls method should send back all " "templates on both which=all and which=.",
         )
     with app.test_client() as c:
         testRequest = c.get("/tpls.json?callback=blah" "&which=header&which=home")
         header = open(statserv.server.determine_path() + "/tpls/header.tpl").read()
         home = open(statserv.server.determine_path() + "/tpls/home.tpl").read()
         response = statserv.server.make_response("blah", dict({"header": header, "home": home}))
         self.assertEquals(
             statserv.server.get_tpls(),
             response,
             "The single-template support does not seem to be " "working properly.",
         )
Example #6
1
    def test_handle_error_signal(self):
        if not signals_available:
            # This test requires the blinker lib to run.
            print("Can't test signals without signal support")
            return
        app = Flask(__name__)
        api = flask_restful.Api(app)

        exception = Mock()
        exception.code = 400
        exception.data = {"foo": "bar"}

        recorded = []

        def record(sender, exception):
            recorded.append(exception)

        got_request_exception.connect(record, app)
        try:
            with app.test_request_context("/foo"):
                api.handle_error(exception)
                self.assertEquals(len(recorded), 1)
                self.assertTrue(exception is recorded[0])
        finally:
            got_request_exception.disconnect(record, app)
Example #7
1
    def test_handle_smart_errors(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)
        view = flask_restful.Resource

        api.add_resource(view, "/foo", endpoint="bor")
        api.add_resource(view, "/fee", endpoint="bir")
        api.add_resource(view, "/fii", endpoint="ber")

        with app.test_request_context("/faaaaa"):
            resp = api.handle_error(NotFound())
            self.assertEquals(resp.status_code, 404)
            self.assertEquals(resp.data.decode(), dumps({"message": NotFound.description}) + "\n")

        with app.test_request_context("/fOo"):
            resp = api.handle_error(NotFound())
            self.assertEquals(resp.status_code, 404)
            self.assertTrue("did you mean /foo ?" in resp.data.decode())

        app.config["ERROR_404_HELP"] = False

        with app.test_request_context("/fOo"):
            resp = api.handle_error(NotFound())
            self.assertEquals(resp.status_code, 404)
            self.assertEquals(resp.data.decode(), dumps({"message": NotFound.description}) + "\n")
Example #8
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",
        )
def create_app(debug=False):
    app = Flask(__name__, template_folder="template")
    app.config.from_object(BaseConfig)
    if "SITE_SETTINGS" in os.environ:
        app.config.from_envvar("SITE_SETTINGS")
    app.config["DEBUG"] |= True

    app.jinja_env.add_extension(JadeJinja)
    app.jinja_env.autoescape = False  # enable pyjade unescaping

    assets = AssetsEnvironment(app)
    content = MarkupContent(app)

    @app.before_first_request
    def before_first_request():
        pass

    @app.context_processor
    def context_processor():
        return {"base": {"title": "ithz"}}

    assets.register("base_css", "base.css", filters=None, output="{BUILD_PATH}/static/css".format(**app.config))
    assets.register("base_js", "base.js", filters=None, output="{BUILD_PATH}/static/js".format(**app.config))

    for name, bundle in six.iteritems(bundles):
        assets.register(name, bundle)

    for blueprint in blueprints:
        app.register_blueprint(blueprint)
    return app, assets
Example #10
0
    def test_will_prettyprint_json_in_debug_mode(self):
        app = Flask(__name__)
        app.config["DEBUG"] = True
        api = flask_restful.Api(app)

        class Foo1(flask_restful.Resource):
            def get(self):
                return {"foo": "bar", "baz": "asdf"}

        api.add_resource(Foo1, "/foo", endpoint="bar")

        with app.test_client() as client:
            foo = client.get("/foo")

            # Python's dictionaries have random order (as of "new" Pythons,
            # anyway), so we can't verify the actual output here.  We just
            # assert that they're properly prettyprinted.
            lines = foo.data.splitlines()
            lines = [line.decode() for line in lines]
            self.assertEquals("{", lines[0])
            self.assertTrue(lines[1].startswith("    "))
            self.assertTrue(lines[2].startswith("    "))
            self.assertEquals("}", lines[3])

            # Assert our trailing newline.
            self.assertTrue(foo.data.endswith(b"\n"))
Example #11
0
def create_app(config):
    app = Flask(__name__)
    app.config.from_object(_config)

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

    if app.config["DEBUG"]:
        from werkzeug.debug import DebuggedApplication

        app.wsgi_app = DebuggedApplication(app.wsgi_app, True)

    api.init_app(app)
    babel.init_app(app)
    cache.init_app(app)
    db.init_app(app)
    mail.init_app(app)
    redis_store.init_app(app)
    CsrfProtect(app)

    register_auth(app)
    register_hooks(app)
    register_static(app)
    register_blueprints(app)
    configure_error_handles(app)
    plug_to_db(db)

    return app
Example #12
0
def test_relative_path():
    app = Flask(__name__)

    path = _create_temp()

    def _remove_testfiles():
        safe_delete(path, "test1.txt")

    class TestForm(form.BaseForm):
        upload = form.FileUploadField("Upload", base_path=path, relative_path="inner/")

    class Dummy(object):
        pass

    my_form = TestForm()
    eq_(my_form.upload.base_path, path)
    eq_(my_form.upload.relative_path, "inner/")

    _remove_testfiles()

    dummy = Dummy()

    # Check upload
    with app.test_request_context(method="POST", data={"upload": (BytesIO(b"Hello World 1"), "test1.txt")}):
        my_form = TestForm(helpers.get_form_data())

        ok_(my_form.validate())

        my_form.populate_obj(dummy)

        eq_(dummy.upload, "inner/test1.txt")
        ok_(op.exists(op.join(path, "inner/test1.txt")))

        eq_(url_for("static", filename=dummy.upload), "/static/inner/test1.txt")
Example #13
0
    def test_exception_header_forwarded(self):
        """Test that HTTPException's headers are extended properly"""
        app = Flask(__name__)
        app.config["DEBUG"] = True
        api = flask_restful.Api(app)

        class NotModified(HTTPException):
            code = 304

            def __init__(self, etag, *args, **kwargs):
                super(NotModified, self).__init__(*args, **kwargs)
                self.etag = quote_etag(etag)

            def get_headers(self, *args, **kwargs):
                """Get a list of headers."""
                return [("ETag", self.etag)]

        class Foo1(flask_restful.Resource):
            def get(self):
                flask_abort(304, etag="myETag")

        api.add_resource(Foo1, "/foo")
        flask_abort.mapping.update({304: NotModified})

        with app.test_client() as client:
            foo = client.get("/foo")
            self.assertEquals(foo.get_etag(), unquote_etag(quote_etag("myETag")))
Example #14
0
def create_app(configfile=None):
    app = Flask(__name__)
    AppConfig(app, configfile)  # Flask-Appconfig is not necessary, but
    # highly recommend =)
    # https://github.com/mbr/flask-appconfig
    Bootstrap(app)

    # in a real app, these should be configured through Flask-Appconfig
    app.config["SECRET_KEY"] = "devkey"
    app.config["RECAPTCHA_PUBLIC_KEY"] = "6Lfol9cSAAAAADAkodaYl9wvQCwBMr3qGR_PPHcw"

    @app.route("/garage")
    def add_numbers():
        ajax_request = request.args.get("ajax_request", 0, type=str)
        print("wassup!\nwassup!\nwassup!\nwassup!\nwassup!\nwassup!\nwassup!\n")
        # open_garage()
        return jsonify(result=ajax_request)

    @app.route("/", methods=("GET", "POST"))
    def index():
        # form = ExampleForm()
        # form.validate_on_submit()  # to get error messages to the browser
        # flash('critical message', 'critical')
        # flash('error message', 'error')

        # flash('info message', 'info')
        # flash('debug message', 'debug')
        # flash('different message', 'different')
        # flash('uncategorized message')
        flash("This application is undergoing tests", "warning")
        # return render_template('index.html', form=form)
        return render_template("index.html")

    return app
Example #15
0
 def test_api_delayed_initialization(self):
     app = Flask(__name__)
     api = flask_restful.Api()
     api.add_resource(HelloWorld, "/", endpoint="hello")
     api.init_app(app)
     with app.test_client() as client:
         self.assertEquals(client.get("/").status_code, 200)
Example #16
0
def create_app(ignore_exceptions=None):
    import os

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

    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
Example #17
0
    def test_non_api_error_404_catchall(self):
        app = Flask(__name__)
        api = flask_restful.Api(app, catch_all_404s=True)
        app = app.test_client()

        resp = app.get("/foo")
        self.assertEquals(api.default_mediatype, resp.headers["Content-Type"])
Example #18
0
def create_cartographer(args):
    app = Flask(__name__)
    app.config["SECRET_KEY"] = "map the soul"

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

    @app.route("/getPoints", methods=["POST"])
    def getPoints():
        print(request.json)
        zoom = int(request.json.get("zoom", 1))
        seen = request.json.get("seen", [])
        ensure(seen).is_a_list_of(str)
        points = POI.objects(
            at__geo_within_box=(request.json["SW"], request.json["NE"]), min_zoom=zoom, name__nin=request.json["seen"]
        )

        return jsonify(
            {
                "points": [
                    {
                        "name": p.name,
                        "lat": p.at["coordinates"][1],
                        "lng": p.at["coordinates"][0],
                        "abstract": lz4.decompress(p.abstract).decode() if p.abstract else "",
                        "img": p.img,
                    }
                    for p in points
                ]
            }
        )

    return app
Example #19
0
 def test_resource_resp(self):
     app = Flask(__name__)
     resource = flask_restful.Resource()
     resource.get = Mock()
     with app.test_request_context("/foo"):
         resource.get.return_value = flask.make_response("")
         resource.dispatch_request()
Example #20
0
def create_app():
    app = Flask(__name__)
    from . import config

    app.config.from_object(config)

    DecentWeb(app)

    from . import models

    from . import auth

    auth.init(app)

    from . import admin

    with app.app_context():
        g.identity = AnonymousIdentity()
        admin.init_app(app)

    Mail(app)

    DebugToolbarExtension(app)

    return app
Example #21
0
    def test_will_pass_options_to_json(self):

        app = Flask(__name__)
        api = flask_restful.Api(app)

        class Foo1(flask_restful.Resource):
            def get(self):
                return {"foo": "bar"}

        api.add_resource(Foo1, "/foo", endpoint="bar")

        # We patch the representations module here, with two things:
        #   1. Set the settings dict() with some value
        #   2. Patch the json.dumps function in the module with a Mock object.

        from flask.ext.restful.representations import json as json_rep

        json_dumps_mock = Mock(return_value="bar")
        new_settings = {"indent": 123}

        with patch.multiple(json_rep, dumps=json_dumps_mock, settings=new_settings):
            with app.test_client() as client:
                client.get("/foo")

        # Assert that the function was called with the above settings.
        data, kwargs = json_dumps_mock.call_args
        self.assertTrue(json_dumps_mock.called)
        self.assertEqual(123, kwargs["indent"])
Example #22
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
    def setUp(self):
        app = Flask(__name__)
        self.username = "testing@example.com"
        self.password = "ShowMeTheMoney"

        def is_valid_user(username, password):
            return (username, password) == (self.username, self.password)

        self.tasks = [{"id": 1, "task": "Do the laundry"}, {"id": 2, "task": "Do the dishes"}]

        def get_tasks(request):
            return self.tasks

        api_201409 = Api(version="v1")
        api_201409.register_endpoint(
            ApiEndpoint(
                http_method="GET",
                endpoint="/task/basic",
                handler=get_tasks,
                authentication=BasicAuth(is_valid_user=is_valid_user),
            )
        )

        app.register_blueprint(api_201409)

        app.config["TESTING"] = True
        self.app = app.test_client()
Example #24
0
def create_app(**config):
    """Application Factory

    You can create a new He-Man application with::

        from heman.config import create_app

        app = create_app() # app can be uses as WSGI application
        app.run() # Or you can run as a simple web server
    """
    app = Flask(__name__, static_folder=None)

    if "MONGO_URI" in os.environ:
        app.config["MONGO_URI"] = os.environ["MONGO_URI"]

    app.config["LOG_LEVEL"] = "DEBUG"
    app.config["SECRET_KEY"] = "2205552d13b5431bb537732bbb051f1214414f5ab34d47"

    configure_logging(app)
    configure_sentry(app)
    configure_api(app)
    configure_mongodb(app)
    configure_login(app)

    return app
Example #25
0
 def testGetUsers(self):
     app = Flask(__name__)
     conn = Connection()
     with app.test_client() as c:
         testRequest = c.get("/users.json?_username=test&_session=1234" "&callback=blah")
         statserv.server.sessions["1234"] = ("test", request.remote_addr, True)
         statserv.server.config["adminuser"] = "admin"
         db = conn["test_db"]
         adminuser = {u"username": u"admin", u"password": "password", u"profile": ""}
         otherusers = [
             {u"username": u"other", u"password": "asdf", u"profile": u"The first other user"},
             {u"username": u"other_two", u"password": "aoeu", u"profile": u"The other other user"},
         ]
         db.stattrusers.insert(adminuser)
         db.stattrusers.insert(otherusers[0])
         db.stattrusers.insert(otherusers[1])
         statserv.server.database = conn["test_db"]
         del otherusers[0]["_id"]
         del otherusers[1]["_id"]
         del otherusers[0]["password"]
         del otherusers[1]["password"]
         expected = statserv.server.make_response("blah", {"users": otherusers})
         actual = statserv.server.get_users()
         conn.drop_database("test_db")
         self.assertEquals(
             actual,
             expected,
             "The get_users method returned something other "
             "than what we expected. Expected: `%s`, Actual: "
             "`%s`" % (expected, actual),
         )
Example #26
0
def create_app(config_name):
    app = Flask(__name__)
    """Based on the name passed as argument to
       create_app method, it is used as key to
       get the config object asociated to tha key
       in this case can be DevConfig or ProdConfig classes"""
    app.config.from_object(config[config_name])
    """Pass the object Flask referenced by the variable db
       to the Configuration Class obtained by key"""
    config[config_name].init_app(app)

    """Once the application is created and configured
       the extentions can be initialized. Calling __init_app
       on the extentions that were created earlies completes
       their initialization"""
    bootstrap.init_app(app)
    db.init_app(app)

    """Blueprints registre"""

    from .main import main as main_blueprint

    app.register_blueprint(main_blueprint)

    from .inventory import inventory as inventory_blueprint

    app.register_blueprint(inventory_blueprint, url_prefix="/inventory")

    return app
Example #27
0
 def testAddUser(self):
     app = Flask(__name__)
     conn = Connection()
     with app.test_client() as c:
         hashedpassword = hashlib.sha1("test").hexdigest()
         testRequest = c.get(
             "/user.json?_method=POST&_username=tester&"
             "_session=1234&username=test1&password=%s&"
             "fullname=tester&admin=false" % hashedpassword
         )
         db = conn.test_db
         user = {
             "username": "test1",
             "password": hashedpassword,
             "fullname": "tester",
             "admin": False,
             "profile": "",
         }
         statserv.server.sessions["1234"] = ("tester", None, True)
         statserv.server.database = conn.test_db
         statserv.server.add_user(request)
         actual = db.stattrusers.find_one({})
         del actual["_id"]
         self.assertEquals(
             user,
             actual,
             "The add_user method did something we didn't " "expect. Expected: `%s`, actual: `%s`." % (user, actual),
         )
         conn.drop_database("test_db")
def make_json_app(import_name, **kwargs):
    """
    Creates a JSON-oriented Flask app.

    All error responses that you don't specifically
    manage yourself will have application/json content
    type, and will contain JSON like this (just an example):

    { "message": "405: Method Not Allowed" }

    http://flask.pocoo.org/snippets/83/
    """
    def make_json_error(ex):
        response = jsonify(message=str(ex))
        response.status_code = (ex.code
                                if isinstance(ex, HTTPException)
                                else 500)
        return response

    app = Flask(import_name, **kwargs)

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error

    return app
Example #29
0
 def testModUser(self):
     app = Flask(__name__)
     conn = Connection()
     with app.test_client() as c:
         testRequest = c.get(
             "/user.json?_username=tester&_session=1234&"
             "_method=PUT&username=test2&fullname=tester&"
             "admin=false&olduser=test1&profile=asdf"
         )
         user = {"username": "test1", "fullname": "tester", "admin": False, "profile": "asdf", "password": "1234"}
         db = conn.test_db
         db.stattrusers.insert(user)
         del user["_id"]
         user["username"] = "test2"
         statserv.server.sessions["1234"] = ("tester", None, True)
         statserv.server.database = conn.test_db
         statserv.server.mod_user(request)
         actual = db.stattrusers.find_one({})
         del actual["_id"]
         self.assertEquals(
             user,
             actual,
             "The mod_user method did something we didn't " "expect. Expected: `%s`, actual: `%s`." % (user, actual),
         )
         conn.drop_database("test_db")
Example #30
0
    def assertRequest(self, method, request, response, want):
        """Execute a request and check the results."""
        error = isinstance(response, Exception)
        want_status = len(want) and want[1] or 200
        want_content = self.serialize(want[0])

        app = Flask(__name__)
        app.config["TESTING"] = True
        serializer = MockSerializer(app)

        route = self.create_view(app, serializer, response)
        client_method = getattr(app.test_client(), method.lower())
        client_res = client_method(route)

        view_req, view_res = serializer.after
        self.assertEqual(client_res.status_code, want_status)
        self.assertEqual(client_res.data, want_content)
        if method == "GET":
            self.assertIsNone(view_req)
        else:
            self.assertEqual(view_req, request)
        if isinstance(response, int):
            self.assertEqual(view_res[1], response)
        else:
            if isinstance(response, Exception):
                response = get_error_response(response)
            self.assertEqual(view_res, response)