存储JSON输入

时间:2014-02-05 22:47:21

标签: json django django-views

我对Django有些新手,我正在尝试在我的应用程序上运行内容安全策略报告,并且遇到了解析和存储JSON违规输出的一些问题。我将所有报告发布到/ csp_reports /并构建了一个名为security_report的新应用程序,并将以下内容添加到我的urls.py中:

url(r'^csp_report/$', 'security_report.views.secreport'),

我的模特看起来像这样:

导入os

from django.db import models
from django.contrib.auth.models import User
from django.conf import settings

class security_report(models.Model):
    id=models.AutoField(primary_key=True)
    received=models.DateTimeField(null=True)
    csp_report=models.CharField()
    blocked_uri=models.CharField()
    column_number=models.CharField()
    document_uri=models.CharField()
    line_number = models.IntegerField()
    original_policy= models.CharField()
    referrer = models.CharField()
    status_code = models.IntegerField()
    violated_directive = models.CharField()
    source_file = models.CharField()
    script_sample = models.CharField()

    class Meta:
        app_label = "events"

我的views.py不完整且不起作用如下。我被困在如何实际抓取每个单独的参数并将其转储到我的数据库中。 json.loads是正确的方法吗?如果是这样,我该如何执行save()?我现在只测试视图中的blocked_uri来测试它。我只是继续打我的除外:并且“得到了”没有保存“

from security_report.models import security_report
from django.utils import simplejson
from django.http import HttpResponse, HttpRequest
from django.views.decorators.csrf import csrf_exempt, csrf_protect
import json

@csrf_exempt
def secreport(request):

    if request.method == "POST":
        json_data = simplejson.loads(request.raw_post_data)
        try:
            data = json_data['csp-report']

            blocked_uri = data['blocked-uri']
            document_uri = data['document-uri']
            referrer = data['referrer']
            script_sample = data['script-sample']
            violated_directive = data['violated-directive']
            source_file = data['source-file']

            b = security_report()
                b.blocked_uri = blocked_uri
                b.save()
                response = ("saved to database!")


        except:
            response = "not saved"

        return HttpResponse(response)

    else:
        return HttpResponse("not a post request")

0 个答案:

没有答案