Django整合Extjs Crsf Json(二)

1.Crsf

Extjs里面所有的表单都是通过Ajax提交的,所以会被Crsf所拦截

所以在每个页面需要引入如下js,主要是在提交表单时设置 crsf信息

//crsf验证
Ext.Ajax.on('beforerequest', function (conn, options) {
    if (!(/^http:.*/.test(options.url) || /^https:.*/.test(options.url))) {

        if(Ext.util.Cookies.get('csrftoken')==null){
            Ext.util.Cookies.set('csrftoken','csrftoken')
        }
        if (typeof(options.headers) == "undefined") {
            options.headers = {'X-CSRFToken': Ext.util.Cookies.get('csrftoken')};
        } else {
            options.headers['X-CSRFToken']=Ext.util.Cookies.get('csrftoken');
        }
    }
}, this);

2. 封装Json结果和Ajax请求装饰器

import datetime
import decimal

from django.http import Http404, HttpResponse
from django.utils import simplejson
from django.utils.timezone import is_aware
from django.db import models
from science import settings
from const import Const

from django.core.serializers import serialize
from django.utils.simplejson import dumps, loads
from django.db.models.query import QuerySet, ValuesQuerySet
from django.utils.functional import curry


class DjangoJSONEncoder(simplejson.JSONEncoder):
	"""
		JSONEncoder subclass that knows how to encode date/time and decimal types.
	"""
	def default(self, o):
		# See "Date Time String Format" in the ECMA-262 specification.
		if isinstance(o, datetime.datetime):
			return o.strftime('%Y年%m月%d日')
		elif isinstance(o, datetime.date):
			return o.isoformat()
		elif isinstance(o, datetime.time):
			if is_aware(o):
				raise ValueError("JSON can't represent timezone-aware times.")
			r = o.isoformat()
			if o.microsecond:
				r = r[:12]
			return r
		elif isinstance(o, decimal.Decimal):
			return str(o)
		elif isinstance(o,ValuesQuerySet):
			return list(o)
		elif isinstance(o, QuerySet):
			return loads(serialize('json', o))
		elif isinstance(o, models.Model):
			return dict([(attr, getattr(o, attr)) for attr in [f.name for f in o._meta.fields]])
		else:
			return super(DjangoJSONEncoder, self).default(o)


dumps = curry(dumps, cls=DjangoJSONEncoder)

def Ajax(fn):
	def wrapper(*args, **kv):
		request = args[0]
		if not  settings.DEBUG and\
		not request.is_ajax():
			raise Http404
		result= fn(*args, **kv)
		result=dumps(result)
		return HttpResponse(result,mimetype="application/json")
	return wrapper

TODO ....

你可能感兴趣的:(Django整合Extjs Crsf Json(二))