How to use Flask - 10 common examples

To help you get started, we’ve selected a few Flask examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github kamalgill / flask-appengine-template / src / lib / flask / testsuite / basic.py View on Github external
def test_none_response(self):
        app = flask.Flask(__name__)
        @app.route('/')
        def test():
            return None
        try:
            app.test_client().get('/')
        except ValueError, e:
            self.assert_equal(str(e), 'View function did not return a response')
            pass
        else:
            self.assert_("Expected ValueError")
github CCExtractor / sample-platform / mod_test / controllers.py View on Github external
def stop_test(test_id):
    """
    Admin or Test User can stop the running test.

    :param test_id: Test ID of the test which user want to stop
    :type test_id: int
    """
    test = Test.query.filter(Test.id == test_id).first()
    test_fork = TestFork.query.filter(TestFork.user_id == g.user.id, TestFork.test_id == test_id).first()
    if not g.user.is_admin and test_fork is None:
        g.log.warning('user with id: {g.user.id} tried to access restricted endpoint')
        abort(403)
    message = "Canceled by user"
    if g.user.is_admin:
        message = "Canceled by admin"
    test_progress = TestProgress(test.id, TestStatus.canceled, message)
    g.db.add(test_progress)
    g.db.commit()
    g.log.info(f'test with id: {test_id} stopped')
    return redirect(url_for('.by_id', test_id=test.id))
github mozilla-releng / balrog / vendor / lib / python / flask / testsuite / blueprints.py View on Github external
def test_add_template_test_with_template(self):
        bp = flask.Blueprint('bp', __name__)
        def boolean(value):
            return isinstance(value, bool)
        bp.add_app_template_test(boolean)
        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')
        @app.route('/')
        def index():
            return flask.render_template('template_test.html', value=False)
        rv = app.test_client().get('/')
        self.assert_in(b'Success!', rv.data)
github craws / OpenAtlas / tests / test_model.py View on Github external
def test_model(self) -> None:
        with app.app_context():  # type: ignore
            rv = self.app.get(url_for('model_index'))
            assert b'Browse' in rv.data
            rv = self.app.get(url_for('class_index'))
            assert b'E1' in rv.data
            rv = self.app.get(url_for('class_view', code='E4'))
            assert b'Domain for' in rv.data
            rv = self.app.get(url_for('property_index'))
            assert b'P1' in rv.data
            rv = self.app.get(url_for('property_view', code='P68'))
            assert b'P68' in rv.data
            data: Dict[str, Any] = {'domain': 'E1', 'range': 'E1', 'property': 'P13'}
            rv = self.app.post(url_for('model_index'), data=data)
            assert b'Wrong domain' in rv.data
            data = {'domain': 'E1', 'range': 'E1', 'property': 'P67'}
            self.app.post(url_for('model_index'), data=data)

            with app.test_request_context():  # Insert data to display in network view
                app.preprocess_request()  # type: ignore
                actor = Entity.insert('E21', 'King Arthur')
                event = Entity.insert('E7',
                                      'Battle of Camlann - a long name that has to be truncated ..')
github armadillica / pillar / tests / test_sdk.py View on Github external
resp = pillarsdk.Node.create_asset_from_file(
                str(self.project_id),
                str(parent_id),
                'image',
                blender_desktop_logo_path,
                mimetype='image/jpeg',
                always_create_new_node=False,
                fileobj=fileobj,
                api=self.sdk_api)

            node_id = resp._id
            self.assertTrue(node_id)

        # Check the node in MongoDB
        with self.app.test_request_context():
            resp = self.get(url_for('nodes|item_lookup', _id=node_id), auth_token='token')
            node_doc = resp.get_json()
            self.assertEqual('BlenderDesktopLogo.png', node_doc['name'])
github Flask-FlatPages / Flask-FlatPages / tests / test_flask_flatpages.py View on Github external
def test_other_encoding(self):
        app = Flask(__name__)
        app.config['FLATPAGES_ENCODING'] = 'shift_jis'
        app.config['FLATPAGES_ROOT'] = 'pages_shift_jis'
        pages = FlatPages(app)
        self.assert_unicode(pages)
github Flask-FlatPages / Flask-FlatPages / tests / test_flask_flatpages.py View on Github external
def test_yaml_meta(self):
        pages = FlatPages(Flask(__name__))
        foo = pages.get('foo')
        self.assertEqual(foo.meta, {
            'title': 'Foo > bar',
            'created': datetime.date(2010, 12, 11),
            'updated': datetime.datetime(2015, 2, 9, 10, 59, 0),
            'updated_iso': datetime.datetime(2015, 2, 9, 10, 59, 0,
                                             tzinfo=utc),
            'versions': [3.14, 42],
        })
        self.assertEqual(foo['title'], 'Foo > bar')
        self.assertEqual(foo['created'], datetime.date(2010, 12, 11))
        self.assertEqual(foo['updated'],
                         datetime.datetime(2015, 2, 9, 10, 59, 0))
        self.assertEqual(foo['updated_iso'],
                         datetime.datetime(2015, 2, 9, 10, 59, 0,
                                           tzinfo=utc))
github pallets / flask / tests / test_appctx.py View on Github external
def test_app_ctx_globals_methods(app, app_ctx):
    # get
    assert flask.g.get('foo') is None
    assert flask.g.get('foo', 'bar') == 'bar'
    # __contains__
    assert 'foo' not in flask.g
    flask.g.foo = 'bar'
    assert 'foo' in flask.g
    # setdefault
    flask.g.setdefault('bar', 'the cake is a lie')
    flask.g.setdefault('bar', 'hello world')
    assert flask.g.bar == 'the cake is a lie'
    # pop
    assert flask.g.pop('bar') == 'the cake is a lie'
    with pytest.raises(KeyError):
        flask.g.pop('bar')
    assert flask.g.pop('bar', 'more cake') == 'more cake'
    # __iter__
    assert list(flask.g) == ['foo']
github hammerlab / seltest / seltest / proxy.py View on Github external
# TODO: fix this; we want a content-length
    if headers.get('content-length'):
        del headers['content-length']
    is_html_response = 'text/html' in headers.get('content-type', '')
    def resp_iter():
        is_first_chunk = True
        for chunk in response.iter_content(CHUNK_SIZE):
            # TODO: Possible bug: '
github hpe-storage / python-3parclient / test / HPE3ParMockServer_flask.py View on Github external
if 'setmembers' not in host_set:
                        host_set['setmembers'] = []
                    if member not in host_set['setmembers']:
                        host_set['setmembers'].extend(members)
                    else:
                        throw_error(409, HOST_IN_SET,
                                    "The object is already part of the set")
                elif 2 == data['action']:
                    # 2 is memRemove- Removes a member from the set
                    for member in members:
                        host_set['setmembers'].remove(member)
                else:
                    throw_error(400, INV_INPUT_BAD_ENUM_VALUE,
                                desc='invalid input: bad enum value - action')

        resp = flask.make_response(json.dumps(host_set), 200)
        return resp

    throw_error(404, NON_EXISTENT_SET, "host set doesn't exist")