Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
747 views
in Technique[技术] by (71.8m points)

flask - Servicing html requests with Eve

I am attempting to build a MongoDB-backed Flask application which serves from the same endpoints:

  • A HTML web interface by default
  • A JSON response if Content-Type == application/json

The idea is that both a user consuming my application with a browser and a service consuming my API programatically can both hit http://myapp.com/users/12345 The former is served a HTML response and the latter is served a JSON response.

As I understand this is in keeping with 'pure' REST, in contrast to the tradition of serving the API from a separate path such as http://myapp.com/api/users/12345.

There is no discussion of views in the Eve docs, other than to say that results are served as JSON by default and XML if requested.

Is there any clean way to override this behaviour such that:

  • The standard Eve JSON response is served if Content-Type == application/json
  • Otherwise, a view applies a template to the data returned by Eve to generate a HTML response?

This seems like it would be an elegant means of creating an application which is both RESTful and DRY.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could look at the Eve-Docs extension which implements a HTML /docs endpoint on top of an existing, Eve-powered, MongoDB REST Service.

Remember Eve is a Flask application (a subclass actually), so everything you can do with Flask you can do with Eve too (like decorate rendering functions etc.)

UPDATED: Here's a little example snippet which adds a custom /hello endpoint to a Eve powered API (source). As you can see is pretty much identical to a standard Flask endpoint:

from eve import Eve
app = Eve()

@app.route('/hello')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...