django 文件详解

2016/6/4 posted in  python

django 文件详解

在python django中处理文件,可以从前台request上传,Model层,view层几个方面来进行解析。

django 文件模型

在模型中定义文件比较简单,只需要定义一个FileField就可以了,其中FileField主要定义了两个比较重要的参数。

FileField.upload_to : 一个本地文件系统的路径,它将附加到MEDIA_ROOT 设置的后面来确定url 属性的值。

FileField.storage: 用于文件的存储

这个定义比较简单,定义好了文件模型之后,在admin视图里面就可以直接上传使用了。他的存放方式一般采取数据库存放upload_to的相关参数,然后将文件存储到MEDIA_ROOT定义的文件目录中。

django 文件前台

在HTML中定义django需求的文件需要将File放置到form中,必须是POST请求,同时需要请求的类型为拥有enctype="multipart/form-data" 属性时,才会包含数据。否则request.FILES 为空。

定义方式可以参考:

    <form id="handfile" action="{% url 'blog:handlefile' %}" method="post" enctype="multipart/form-data">
          <fieldset>
             {% csrf_token %}
              <label for="name" id="name_label">blogfile</label>
              <input type="file" name="blogfile" id="blogfile" />
              <br />
              <input type="submit" name="submit" class="button" id="submit_btn" value="Send Message"/>
          </fieldset>

django view层

在view层中可以获取前台传来的request,request会将前台的多个文件传到File文件中去,需要进行key的匹配,详细的直接上代码

    def handlefile(request):
        for key in request.FILES:
            blog = request.FILES[key]
            print(blog._name)
            #print(blog.read())
            print("read trunk")
            for chunk in blog.chuncks():
                print(chunk)

这里是模型的读取

讲讲几个读取方法 read() readline() readlines() chuncks()
read()方法

.read() 每次读取整个文件,它通常用于将文件内容放到一个字符串变量中。然而 .read() 生成文件内容最直接的字符串表示,但对于连续的面向行的处理,它却是不必要的,并且如果文件大于可用内存,则不可能实现这种处理。

readlines()

.readlines() 同样是一次读取整个文件,象 .read()一样。.readlines() 自动将文件内容分析成一个行的列表,该列表可以由 Python 的 for ... in ... 结构进行处理。

readline()

readline() 每次只读取一行,通常比 .readlines() 慢得多。仅当没有足够内存可以一次读取整个文件时,才应该使用 .readline()。

chuncks()

按照区块来读取,如果是从request直接出来的,使用chuncks会报错,AttributeError: 'InMemoryUploadedFile' object has no attribute 'chuncks'

猜想由于文件已经在内存中了,这是不能在用chuncks()来分块读取了。