[英]How to handle web and mobile requests in django view
I know this is a pretty simple question, but I haven't understood how to tackle this problem. 我知道这是一个非常简单的问题,但是我还不了解如何解决这个问题。
I have a model called Restaurant with information about a restaurant (name, location, etc). 我有一个名为Restaurant的模型,其中包含有关餐厅的信息(名称,位置等)。 I have a view that handles requests to the url localhost:8000/restaurants and returns a JSON representation of the restaurants using django-rest-framework.
我有一个视图,用于处理对url localhost:8000 / restaurants的请求,并使用django-rest-framework返回餐厅的JSON表示形式。 I've made it this way because I'm consuming this data from an android app.
我之所以这样,是因为我正在使用Android应用程序中的数据。
Now I want to access the same url from the web, but this time I want to see a fully rendered html with the restaurants' info. 现在,我想从网络上访问相同的URL,但是这次,我想看到带有餐厅信息的完全呈现的html。
So, my specific question is, how can I know (and consequently responds with a JSON stream or html) whether the request is coming from the android app or from a web browser if both requests are pointed to the same url and view? 因此,我的具体问题是,如果两个请求都指向相同的url和视图,我如何知道(然后以JSON流或html响应)该请求是来自android应用还是来自Web浏览器?
You can use Django Rest Framework's TemplateHTMLRenderer . 您可以使用Django Rest Framework的TemplateHTMLRenderer 。 It conditionally outputs either JSON or HTML page based on the type of request.
它根据请求的类型有条件地输出JSON或HTML页面。 You can define the following attributes for the View that you are using
您可以为正在使用的视图定义以下属性
class YourView(generics.TypOfView):
renderer_classes = (TemplateHTMLRenderer, JSONRenderer,)
template_name = 'path_to_template.html'
I can not comment yet, so I will post it in the answer. 我还不能发表评论,所以将其张贴在答案中。
You might want to try to create the middleware as described by Adam here , and in your views you can perform checking with is_phone, is_tablet and then send response in appropriate format 您可能想要尝试按照Adam 在这里创建的中间件进行创建,并且在您的视图中可以使用is_phone,is_tablet执行检查,然后以适当的格式发送响应
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.