用Eve来处理html请求 [英] Servicing html requests with Eve

查看:231
本文介绍了用Eve来处理html请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b

  • 默认的一个HTML网页界面

  • 如果 Content-Type == application / json


这个想法是,一个用户使用浏览器来使用我的应用程序和一个以编程方式使用我的API的服务都可以同时访问 http://myapp.com/users/12345 前者提供HTML响应,后者提供JSON响应。

据我所知,这与纯粹的REST保持一致,与从单独的路径(如 http://myapp.com/api/users/12345



在Eve文档中没有关于视图的讨论,除了假设结果默认为JSON,如果请求的话XML也是。

有没有干净方式来覆盖这样的行为:


  • 如果 Content-Type ==应用程序提供了标准的Eve JSON响应/ json

  • 否则,视图将模板应用于Eve所返回的数据以生成HTML响应? >

    这似乎是创建一个既RESTful又干的应用程序的优雅手段。

您可以查看 Eve-Docs 扩展,它在现有的Eve支持的MongoDB REST服务上实现HTML / docs 端点。


$ b $记住,Eve是一个Flask应用程序(实际上是一个子类),所以你可以用Flask做的所有事情都可以用Eve做(比如装饰渲染函数等)。

<更新:这是一个小例子,它添加了一个自定义 / hello 端点Eve支持的API()。正如您所看到的,与标准的Flask端点非常相似:

  from eve import Eve 
app = Eve( )

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

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


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.

解决方案

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()

这篇关于用Eve来处理html请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆