简体   繁体   English

使用python将数据库数据存储到json文件中

[英]store database data into json file using python

In my app I am trying to save the database data into a JSON file. 在我的应用程序中,我试图将数据库数据保存到JSON文件中。

Here is my views.py: 这是我的views.py:

if request.POST:
        form = BookForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            form.save()

            JSONSerializer = serializers.get_serializer("json")
            json_serializer = JSONSerializer()
            with open("book.json", "w") as out:
                json_serializer.serialize(Book.objects.all(), stream=out)

        return redirect('/index/')
    return render_to_response('addbook.html',{ 'form':form },context_instance=RequestContext(request))

I am using serializer for doing that. 我正在使用序列化器来做到这一点。
The problem is that the data is saved in the database, but not written to the file. 问题在于数据已保存在数据库中,但未写入文件中。

I am getting the following error,while running the above code 运行上面的代码时出现以下错误

IOError at /addbook/
[Errno 2] No such file or directory: 'fixtures/book.json'
Request Method: POST
Request URL:    http://localhost:8000/addbook/
Django Version: 1.3.7
Exception Type: IOError
Exception Value:    
[Errno 2] No such file or directory: 'fixtures/book.json'
Exception Location: /root/Samples/DemoApp/DemoApp/views.py in addbook, line 53
Python Executable:  /usr/bin/python
Python Version: 2.7.0
path = "{0}/app_name/fixtures/book.json".format(settings.PROJECT_ROOT)
with open(path, "w") as out:
    json_serializer.serialize(Book.objects.all(), stream=out)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM