Python flask.render_template_string() Examples

The following are 30 code examples of flask.render_template_string(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask , or try the search function .
Example #1
Source File: test_misc.py    From flask-security with MIT License 8 votes vote down vote up
def test_method_view(app, client):
    # auth_required with flask method view
    from flask.views import MethodView
    from flask import render_template_string

    class MyView(MethodView):
        decorators = [auth_required("token", "session")]

        def get(self):
            return render_template_string("Hi view")

    myview = MyView.as_view("myview")

    app.add_url_rule("/myview", view_func=myview, methods=["GET"])

    response = client.get("/myview", follow_redirects=False)
    # should require login
    assert response.status_code == 302
    assert "/login" in response.location

    authenticate(client)
    response = client.get("/myview")
    assert response.status_code == 200
    assert b"Hi view" in response.data 
Example #2
Source File: test_frontend_filters.py    From udata with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_i18n_alternate_links_outside_i18n_blueprint(self, app, client):
        test = Blueprint('test', __name__)

        @test.route('/not-i18n/<key>/')
        def i18n(key):
            return render_template_string('{{ i18n_alternate_links() }}')

        app.register_blueprint(test)
        app.config['DEFAULT_LANGUAGE'] = 'en'
        app.config['LANGUAGES'] = {
            'en': 'English',
            'fr': 'Français',
            'de': 'German',
        }

        response = client.get(url_for('test.i18n', key='value', param='other'))
        assert response.data == b'' 
Example #3
Source File: ldap_app.py    From flask-ldap3-login with MIT License 6 votes vote down vote up
def login():
    template = """
    {{ get_flashed_messages() }}
    {{ form.errors }}
    <form method="POST">
        <label>Username{{ form.username() }}</label>
        <label>Password{{ form.password() }}</label>
        {{ form.submit() }}
        {{ form.hidden_tag() }}
    </form>
    """

    # Instantiate a LDAPLoginForm which has a validator to check if the user
    # exists in LDAP.
    form = LDAPLoginForm()

    if form.validate_on_submit():
        # Successfully logged in, We can now access the saved user object
        # via form.user.
        login_user(form.user)  # Tell flask-login to log them in.
        return redirect("/")  # Send them home

    return render_template_string(template, form=form) 
Example #4
Source File: helpers.py    From Flask-P2P with MIT License 6 votes vote down vote up
def test_template_escaping(self):
        app = flask.Flask(__name__)
        render = flask.render_template_string
        with app.test_request_context():
            rv = flask.json.htmlsafe_dumps('</script>')
            self.assert_equal(rv, u'"\\u003c/script\\u003e"')
            self.assert_equal(type(rv), text_type)
            rv = render('{{ "</script>"|tojson }}')
            self.assert_equal(rv, '"\\u003c/script\\u003e"')
            rv = render('{{ "<\0/script>"|tojson }}')
            self.assert_equal(rv, '"\\u003c\\u0000/script\\u003e"')
            rv = render('{{ "<!--<script>"|tojson }}')
            self.assert_equal(rv, '"\\u003c!--\\u003cscript\\u003e"')
            rv = render('{{ "&"|tojson }}')
            self.assert_equal(rv, '"\\u0026"')
            rv = render('{{ "\'"|tojson }}')
            self.assert_equal(rv, '"\\u0027"')
            rv = render("<a ng-data='{{ data|tojson }}'></a>",
                data={'x': ["foo", "bar", "baz'"]})
            self.assert_equal(rv,
                '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>') 
Example #5
Source File: ldap_app_tls.py    From flask-ldap3-login with MIT License 6 votes vote down vote up
def login():
    template = """
    {{ get_flashed_messages() }}
    {{ form.errors }}
    <form method="POST">
        <label>Username{{ form.username() }}</label>
        <label>Password{{ form.password() }}</label>
        {{ form.submit() }}
        {{ form.hidden_tag() }}
    </form>
    """

    # Instantiate a LDAPLoginForm which has a validator to check if the user
    # exists in LDAP.
    form = LDAPLoginForm()

    if form.validate_on_submit():
        # Successfully logged in, We can now access the saved user object
        # via form.user.
        login_user(form.user)  # Tell flask-login to log them in.
        return redirect("/")  # Send them home

    return render_template_string(template, form=form) 
Example #6
Source File: fields.py    From ara-archive with GNU General Public License v3.0 6 votes vote down vote up
def __call__(self, obj):
        """
        Extract a value from `obj` and return the formatted value.
        """
        # Extract value from the object.
        value = self.expr(**{x: getattr(obj, x)
                             for x in dir(obj)
                             if not x.startswith('_')})

        if value is None:
            if self.raise_on_err:
                raise AttributeError(self.path)

        # Get a template, maybe
        template = (self.template if self.template
                    else implicit_templates.get(type(value)))

        if template:
            return render_template_string(template, value=value)
        else:
            return value 
Example #7
Source File: test_blueprints.py    From vulyk with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_context_filler(self):
        class TestModule(VulykModule):
            pass

        app = flask.Flask('test')
        app.config.from_object('vulyk.settings')
        test_module = TestModule('test_module', __name__)
        test_module.add_context_filler(lambda: {'x': 'you speak'})
        test_module.add_context_filler(lambda: {'y': 'bollocks'})

        def fake_route():
            template = '{{test_module_x}} {{test_module_y}}'

            return flask.render_template_string(template)

        test_module.route('/test', methods=['GET'])(fake_route)
        app.register_blueprint(test_module)
        resp = app.test_client().get('/test')

        self.assertEqual(resp.data.decode('utf8'), 'you speak bollocks') 
Example #8
Source File: render_graphiql.py    From graphql-server-core with MIT License 6 votes vote down vote up
def render_graphiql(
    params,
    result,
    graphiql_version=None,
    graphiql_template=None,
    graphiql_html_title=None,
):
    graphiql_version = graphiql_version or GRAPHIQL_VERSION
    template = graphiql_template or TEMPLATE

    return render_template_string(
        template,
        graphiql_version=graphiql_version,
        graphiql_html_title=graphiql_html_title,
        result=result,
        params=params,
    ) 
Example #9
Source File: blueprints.py    From Flask-P2P with MIT License 6 votes vote down vote up
def test_context_processors(self):
        app = flask.Flask(__name__)
        admin = flask.Module(__name__, 'admin', url_prefix='/admin')
        @app.context_processor
        def inject_all_regular():
            return {'a': 1}
        @admin.context_processor
        def inject_admin():
            return {'b': 2}
        @admin.app_context_processor
        def inject_all_module():
            return {'c': 3}
        @app.route('/')
        def index():
            return flask.render_template_string('{{ a }}{{ b }}{{ c }}')
        @admin.route('/')
        def admin_index():
            return flask.render_template_string('{{ a }}{{ b }}{{ c }}')
        app.register_module(admin)
        c = app.test_client()
        self.assert_equal(c.get('/').data, b'13')
        self.assert_equal(c.get('/admin/').data, b'123') 
Example #10
Source File: views.py    From isthislegit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def send_test_template():
    '''
    Sends a test template to the provided address
    '''
    form = SendTestTemplateForm(request.form)
    if form.validate_on_submit():
        report = EmailReport.make_sample()
        try:
            subject = render_template_string(form.subject.data, report=report)
            text = render_template_string(form.text.data, report=report)
            email_provider.send(
                to=form.recipient.data,
                sender=g.user.email(),
                subject=subject,
                body=text)
            return jsonify({'success': True, 'message': 'Sent test email.'})
        except Exception as e:
            return json_error(400, str(e), {})
    return json_error(400, list_errors(form), {}) 
Example #11
Source File: publish.py    From sparrow with GNU General Public License v3.0 6 votes vote down vote up
def publish_query(secret_key=None):
    try:
        Msg_Key = 'op_publish_msg_%s' %secret_key
        Key_incr = '%s_incr' % Msg_Key
        Redis.expire(Msg_Key,30)
        if Redis.lrange(Msg_Key,0,-1):
            data = Redis.rpop(Msg_Key)
            if '_End_' in str(data):
                Redis.expire(Msg_Key,3)
            return render_template_string(data)
        else:
            Redis.incr(Key_incr, 1)
            if int(Redis.get(Key_incr)) >10000:
                Redis.delete(Key_incr)
                return render_template_string("_End_")
            return render_template_string("")
    except Exception as e:
        logging.error(e)
        return render_template_string(e) 
Example #12
Source File: k8s_deploy.py    From sparrow with GNU General Public License v3.0 6 votes vote down vote up
def deploy_query(redis_key = None):
    try:
        Key_incr = '%s_incr' % redis_key
        Redis.expire(redis_key,30)
        if Redis.lrange(redis_key,0,-1):
            data = Redis.rpop(redis_key)
            if '_End_' in data:
                Redis.expire(redis_key,3)
            return render_template_string(data)
        else:
            Redis.incr(Key_incr, 1)
            if int(Redis.get(Key_incr)) >10000:
                Redis.delete(Key_incr)
                return render_template_string("_End_")
            return render_template_string("")
    except Exception as e:
        logging.error(e)
        return redirect(url_for('error')) 
Example #13
Source File: test_frontend_filters.py    From udata with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_as_filter(self):
        '''URL helpers should exists as filter'''
        url = url_for('site.home', one='value')

        assert_urls_equal(
            render_template_string(
                "{{ url|url_rewrite(one='other-value') }}", url=url),
            url_for('site.home', one='other-value')
        )
        assert_urls_equal(
            render_template_string(
                "{{ url|url_add(two='other-value') }}", url=url),
            url_for('site.home', one='value', two='other-value')
        )
        assert_urls_equal(
            render_template_string("{{ url|url_del('one') }}", url=url),
            url_for('site.home')
        ) 
Example #14
Source File: test_frontend_filters.py    From udata with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_as_global(self):
        '''URL helpers should exists as global function'''
        url = url_for('site.home', one='value')

        assert_urls_equal(
            render_template_string(
                "{{ url_rewrite(url, one='other-value') }}", url=url),
            url_for('site.home', one='other-value')
        )
        assert_urls_equal(
            render_template_string(
                "{{ url_add(url, two='other-value') }}", url=url),
            url_for('site.home', one='value', two='other-value')
        )
        assert_urls_equal(
            render_template_string("{{ url_del(url, 'one') }}", url=url),
            url_for('site.home')
        ) 
Example #15
Source File: test_frontend_filters.py    From udata with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_as_global_default(self, app):
        '''URL helpers should exists as global function without url param'''
        url = url_for('site.home', one='value')

        with app.test_request_context(url):
            assert_urls_equal(
                render_template_string("{{ url_rewrite(one='other-value') }}"),
                full_url('site.home', one='other-value')
            )
            assert_urls_equal(
                render_template_string("{{ url_add(two='other-value') }}"),
                full_url('site.home', one='value', two='other-value')
            )
            assert_urls_equal(
                render_template_string("{{ url_del(None, 'one') }}"),
                full_url('site.home')
            )
            assert render_template_string("{{ in_url('one') }}") == 'True'
            assert render_template_string("{{ in_url('one') }}") == 'True'
            assert render_template_string("{{ in_url('two') }}") == 'False' 
Example #16
Source File: api_v0.py    From comet-core with Apache License 2.0 6 votes vote down vote up
def action_failed(message=None, status_code=500):
    """Generate html (for GET request) or json (for POST requests) response with a custom failure message.

    Args:
        message (str): custom failure message
        status_code (int): the http status code to return
    Returns:
        Tuple[Union[str,flask.Response],int]: rendered html code or json Response object and http code
                                              with an error message
    """
    if request.method == "POST":
        response = {"status": "error"}
        if message:
            response["message"] = message
        return jsonify(response), status_code

    template = (
        "<h2>Something went wrong: {{ message }}</h2> "
        "<p>Please complete the action by emailing to Security.</p>"
        "<p>Note: This feature is still early in development, "
        "please reach out to Security if you have any feedback.</p>"
    )
    return render_template_string(template, message=message), status_code 
Example #17
Source File: api_v0.py    From comet-core with Apache License 2.0 6 votes vote down vote up
def action_succeeded(message=None, status_code=200):
    """Generate html (for GET request) or json (for POST requests) response with a custom success message.

    Args:
        message (str): custom success message
        status_code (int): the http status code to return
    Returns:
        Tuple[Union[str,flask.Response],int]: rendered html code or json Response object and http code
                                              with a success message
    """
    if request.method == "POST":
        response = {"status": "ok"}
        if message:
            response["msg"] = message
        return jsonify(response), status_code

    template = (
        "<h2>{{ message }}</h2> "
        "<p>Note: This feature is still early in development, "
        "please reach out to Security if you have any feedback.</p>"
    )
    return render_template_string(template, message=message), status_code 
Example #18
Source File: test_frontend_filters.py    From udata with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_i18n_alternate_links(self, app, client):
        test = I18nBlueprint('test', __name__)

        @test.route('/i18n/<key>/')
        def i18n(key):
            return render_template_string('{{ i18n_alternate_links() }}')

        app.register_blueprint(test)
        app.config['DEFAULT_LANGUAGE'] = 'en'
        app.config['LANGUAGES'] = {
            'en': 'English',
            'fr': 'Français',
            'de': 'German',
        }

        response = client.get(url_for('test.i18n', key='value', param='other'))
        link = ('<link rel="alternate" '
                'href="/{lang}/i18n/value/?param=other" '
                'hreflang="{lang}" />')
        assert response.data.decode('utf8') == ''.join([link.format(lang='fr'),
                                                        link.format(lang='de')]) 
Example #19
Source File: test_markdown.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_mdstrip_custom_end(self, app):
        '''mdstrip should allow a custom ending string'''
        text = '1234567890'
        template = '{{ text|mdstrip(5, "$") }}'
        with app.test_request_context('/'):
            result = render_template_string(template, text=text)

        assert result.strip() == '1234$' 
Example #20
Source File: wikidata.py    From osm-wikidata with GNU General Public License v3.0 5 votes vote down vote up
def get_query(q, south, north, west, east):
    return render_template_string(q,
                                  south=south,
                                  north=north,
                                  west=west,
                                  east=east) 
Example #21
Source File: blog_gcdatastore.py    From Flask-Blogging with MIT License 5 votes vote down vote up
def index():
    return render_template_string(index_template) 
Example #22
Source File: blog_plugins.py    From Flask-Blogging with MIT License 5 votes vote down vote up
def index():
    return render_template_string(index_template) 
Example #23
Source File: approval.py    From sparrow with GNU General Public License v3.0 5 votes vote down vote up
def platform_token(action=None,id=None,args=None):
    tools.Async_log(g.user, request.url)
    db_token = db_op.platform_token
    tm = time.strftime('%Y-%m-%d', time.localtime())
    form = MyForm.FormPlatformToken()
    tables = ['第三方平台', '连接方式', 'Token', '颁发日期', '失效日期', '管理']
    if action == 'add':
        expire_date = "2999-12-30"
        if id >0:
            expire_date = datetime.datetime.now() + datetime.timedelta(days=id)
            expire_date = expire_date.strftime('%Y-%m-%d')
        try:
            c = db_token(platform=args,channel='api',token=Md5.Md5_make(tools.Produce(8,string.digits)),award=tm,expire=expire_date)
            db_op.DB.session.add(c)
            db_op.DB.session.commit()
            return render_template_string('success')
        except Exception as e:
            logging.error(e)
            return render_template_string('fail')
    if action == 'modify':
        try:
            db_token.query.filter(db_token.id==id).update({db_token.expire:args})
            db_op.DB.session.commit()
            return render_template_string('success')
        except Exception as e:
            logging.error(e)
            return render_template_string('fail')
    if action == 'drop':
        try:
            v = db_token.query.filter(db_token.id==id).all()
            for c in v:
                db_op.DB.session.delete(c)
                db_op.DB.session.commit()
            return render_template_string('success')
        except Exception as e:
            logging.error(e)
            return render_template_string('fail')
    vals = db_token.query.with_entities(db_token.id, db_token.platform, db_token.channel, db_token.token,
                                            db_token.award, db_token.expire).order_by(desc(db_token.id)).all()
    return render_template('platform_token.html',form=form,vals = vals,tables=tables,tm=tm) 
Example #24
Source File: wikidata.py    From osm-wikidata with GNU General Public License v3.0 5 votes vote down vote up
def osm_key_query(self):
        return render_template_string(wikidata_subclass_osm_tags,
                                      qid=self.qid) 
Example #25
Source File: wikidata.py    From osm-wikidata with GNU General Public License v3.0 5 votes vote down vote up
def get_point_query(lat, lon, radius):
    return render_template_string(wikidata_point_query,
                                  lat=lat,
                                  lon=lon,
                                  radius=float(radius) / 1000.0) 
Example #26
Source File: blog_roles.py    From Flask-Blogging with MIT License 5 votes vote down vote up
def index():
    return render_template_string(index_template) 
Example #27
Source File: test_markdown.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_mdstrip_does_not_truncate_in_tags(self, app):
        '''mdstrip should not truncate in middle of a tag'''
        text = '![Legend](http://www.somewhere.com/image.jpg) Here. aaaaa'
        with app.test_request_context('/'):
            result = render_template_string('{{ text|mdstrip(5) }}', text=text)

        assert result.strip() == 'Here…' 
Example #28
Source File: main.py    From Flask-Blogging with MIT License 5 votes vote down vote up
def index():
    return render_template_string(index_template) 
Example #29
Source File: test_markdown.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_mdstrip_filter_with_excerpt(self, app):
        '''mdstrip should truncate on token if shorter than required size'''
        text = ''.join(['excerpt', EXCERPT_TOKEN, 'aaaa ' * 10])
        with app.test_request_context('/'):
            result = render_template_string(
                '{{ text|mdstrip(20) }}', text=text)

        assert result == 'excerpt' 
Example #30
Source File: blog_dynamodb.py    From Flask-Blogging with MIT License 5 votes vote down vote up
def index():
    return render_template_string(index_template)