Django根据客户端python返回json和html [英] Django return json and html depending on client python

查看:676
本文介绍了Django根据客户端python返回json和html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有html模板的django应用程序,我还有一个命令行python api,可以对服务器上的django应用程序执行GET和POST请求。 api几乎可以做django应用程序可以做的一切。我如何做到这一点,当我通过浏览器访问django应用程序返回html,但是当我通过api访问它返回json?



我将在哪里把json和我的应用程序有什么变化?



谢谢

解决方案

为JSON和HTML版本使用不同的URL。



我建议您的JSON版本可以在 r'normal / api(?P< json_flag> / json /?) ',并在您的视图中有一个参数来接收json标志。然后,您可以适当地进行服务。



当然,您的视图将不得不使用不同的逻辑来生成HTML和JSON。我强烈建议您使用 json 模块而不是模板生成JSON。


I have a django app which has html templates and I also have a command line python api which can do GET and POST requests to the django app on the server. The api can pretty much do everything that the django app can do. How do I make it such that when I access the django app through the browser it returns html but when I access it through the api it returns json?

Where will I have to put the json and what changes do I have to make to my app?

Thank you

解决方案

Use different URLs for the JSON and HTML versions.

I suggest that your JSON version be available on a url like r'normal/api(?P<json_flag>/json/?)$', and have a parameter in your view to receive the json flag. You can then serve appropriately.

Naturally, your view will have to use different logic to generate HTML and JSON. I strongly suggest that you use the json module instead of a template to generate JSON.

这篇关于Django根据客户端python返回json和html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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