Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

return html in flask-restful #529

Closed
ZimmerHao opened this issue Nov 10, 2015 · 3 comments
Closed

return html in flask-restful #529

ZimmerHao opened this issue Nov 10, 2015 · 3 comments
Labels

Comments

@ZimmerHao
Copy link

how can i return html directly in flask-restful. For example, my index.html is in /xxx/index.html, and how can i make a response to return the html directly not use render_template.

@justanr
Copy link
Contributor

justanr commented Nov 14, 2015

There's a method Api.representation that you'll want to look into. However, you'll need some way of mapping routes to templates. I'd recommend using flask.request.endpoint which tells you where the request was routed to. You could do something as simple as a dictionary that maps these endpoints to templates, maybe something like:

_endpoint_templates = {
    'main.index': 'index.html',
    'user.profile': 'profile.html',
    'default': 'default.html'
}

@api.representation('text/html')
def render_endpoint_template(data, code, headers):
    template = _endpoint_templates.get(request.endpoint, _endpoint_templates['default'])
    return render_template(template, **data), code, headers

Pretty low tech, but I'd imagine it'd go a fair distance. You'd probably want some way of automatically associating templates with endpoints so you're not constantly having to update the dictionary.

@joshfriend
Copy link
Member

@justanr's solution would probably work (though it's probably not very robust). I think you could also return a Response object from the endpoint with the HTML already rendered and Flask-RESTful won't try to serialize it to JSON.

Either way, Flask-RESTful isn't the tool you want to use for rendering webpages.

@justanr
Copy link
Contributor

justanr commented Nov 15, 2015

I could see a use case for returning HTML or JSON or something else depending on the Accept header sent in. Think using reddit's .json URLs except responding to headers. Though you're right, a more robust solution would be needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants