对小马的ajax请求
django-ajaxutils的Python项目详细描述
有多少次您发现自己在django中编写了一些视图来处理ajax请求?还有多少次您只是复制粘贴了为同步请求编写的视图并编辑它们以返回json对象?那么,有多少次您忘记了@login_required会在匿名用户的情况下将请求重定向到登录页?如果这种情况发生在你身上的次数和发生在我们身上的次数一样多,你可能会开始考虑使用django ajaxutils。
django ajaxutils允许您将视图定义为ajax视图,该视图将返回json对象,并将正确处理诸如用户未通过身份验证和无效请求等错误。一切都通过一个简单的装饰!
安装
只需点击:
pip install django-ajaxutils
去施魔法。
用法
如果要定义用于处理ajax请求的视图,只需用@ajax修饰它,并返回一个字典,表示要返回为json的对象。如果您缺乏想象力,请查看以下内容:
from ajaxutils.decorators import ajax @ajax() def check_for_some_task(request): exit_status = get_status_of_some_task() if exit_status is None: return { 'status': 'pending' } return { 'status': 'completed', 'exit_status': exit_status }
需要认证
如果您的视图要求对用户进行身份验证,只需编写它:
@ajax(login_required=True) def some_very_private_view(request): data = perform_something_private() return { 'data': data }
如果是未经身份验证的请求,将返回包含以下json对象的401: Unauthorized响应:
{ 'status': 'error', 'error': 'Unauthorized', }
需要get/post
@ajax还允许您使用一种快速的方法来请求视图。例如,如果视图将编辑某些服务器端数据,则只能接受POST请求。对于@ajax,这就像记住pi的前两个十进制数字一样简单(分别是1和4,btw):
@ajax(login_required=True, require_POST=True) def submit_my_data(request): new_obj = save_my_data() return { 'id': new_obj.pk }
这将返回一个405: Method not allowed响应,其中包含以下JSON对象,以防非法请求:
{ 'status': 'error', 'error': 'Method not allowed', }
当然,您可以为get请求设置require_GET=True。
您也可以使用此替代语法:
@ajax(require="GET") def my_cool_view(request): return { 'hello': 'world!' }
自定义状态代码
如果不想返回htp200呢?你想退404吗?写入:
from django.http import Http404 @ajax() def my_cool_view(request): raise Http404
返回:
{ 'status': 'error', 'error': 'Not found', }
或者是400个错误的请求:
from django.http import HttpResponseBadRequest @ajax() def my_cool_view(request): return HttpResponseBadRequest('My error message')
返回:
{ 'status': 'error', 'error': 'My error message', }
http响应的状态代码是400。
另一种语法,more flask ish:
@ajax() def my_cool_view(request): return { "i'm a": 'teapot' }, 418
从无限导入json
厌倦了编写无限导入语句来选择最好的json模块吗?让Ajaxutils为您做这件事:
from ajaxutils import json
目前,ajaxutils更喜欢simplejson而不是stdlib json。没有使用其他json模块。将来,我们可能会使用django设置为ujson提供支持。
更改日志
v0.2
- 将jsonresponse移动到ajaxutils.http
- 添加了自定义状态代码处理
- 添加了@ajax的文档(require=method)
- 添加了“from ajaxutils import json”