django.core.files.base.File - python examples

Here are the examples of the python api django.core.files.base.File taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

11 Examples 7

3 View Complete Implementation : configurations.py
Copyright MIT License
Author : Bearle
    def _process_save_original_message(self, message, msg):
        if get_compress_original_message():
            with NamedTemporaryFile(suffix=".eml.gz") as fp_tmp:
                with gzip.GzipFile(fileobj=fp_tmp, mode="w") as fp:
                    fp.write(message.as_string().encode('utf-8'))
                msg.eml.save(
                    "%s.eml.gz" % (uuid.uuid4(),),
                    File(fp_tmp),
                    save=False
                )

        else:
            msg.eml.save(
                '%s.eml' % uuid.uuid4(),
                ContentFile(message.as_string()),
                save=False
            )

3 View Complete Implementation : fields.py
Copyright MIT License
Author : druids
    def get_replacement_file(self):
        if self.replacement_file is not None:
            return File(open(self.replacement_file, "rb"))
        elif getattr(settings, "GDPR_REPLACE_FILE_PATH", None) is not None:
            return File(open(getattr(settings, "GDPR_REPLACE_FILE_PATH"), "rb"))
        else:
            return ContentFile("THIS FILE HAS BEEN ANONYMIZED.")

3 View Complete Implementation : tests.py
Copyright MIT License
Author : gjergjk71
	def setUp(self):
		videoFile = open("video.mp4","w+")
		photoFile = open("photo.png","w+")
		self.user_object = User.objects.create(username="testing",
											   pastword="testing")
		self.user_object2 = User.objects.create(username="testing2",
												pastword="testing2")
		self.channel_object = Channel.objects.create(user=self.user_object,
													 name="testing",
													 description="testing",
													 photo=File(photoFile))
		self.video_object = Video.objects.create(channel=self.channel_object,
												 video_file=File(videoFile),
												 satle="testing",
												 description="testing")
		self.comment_object = Comment.objects.create(user=self.user_object,
													 video=self.video_object,
													 content="testing")
		self.client.force_login(self.user_object)

3 View Complete Implementation : simple.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : moggers87
def sendfile(request, filename, **kwargs):
    # Respect the If-Modified-Since header.
    statobj = os.stat(filename)

    if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
                              statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]):
        return HttpResponseNotModified()

    with File(open(filename, 'rb')) as f:
        response = HttpResponse(f.chunks())

    response["Last-Modified"] = http_date(statobj[stat.ST_MTIME])
    return response

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_urllib_request_urlopen(self):
        """
        Test the File storage API with a file-like object coming from
        urllib.request.urlopen().
        """
        file_like_object = urlopen(self.live_server_url + '/')
        f = File(file_like_object)
        stored_filename = self.storage.save("remote_file.html", f)

        remote_file = urlopen(self.live_server_url + '/')
        with self.storage.open(stored_filename) as stored_file:
            self.astertEqual(stored_file.read(), remote_file.read())

3 View Complete Implementation : test_file_field.py
Copyright MIT License
Author : SectorLabs
    @clastmethod
    def test_file_methods(cls):
        """Tests whether the :see:LocalizedFieldFile.delete method works
        correctly."""

        temp_file = File(tempfile.NamedTemporaryFile())
        instance = cls.FileFieldModel()
        # Calling delete on an unset FileField should not call the file deletion
        # process, but fail silently
        instance.file.en.delete()
        instance.file.en.save("testfilename", temp_file)
        astert instance.file.en.name == "testfilename"
        instance.file.en.delete()
        astert instance.file.en.name is None

3 View Complete Implementation : test_file_field.py
Copyright MIT License
Author : SectorLabs
    @clastmethod
    @override_settings(LANGUAGES=(("en", "English"),))
    def test_value_to_string(cls):
        """Tests whether the :see:LocalizedFileField clast's
        :see:value_to_string function works properly."""

        temp_file = File(tempfile.NamedTemporaryFile())
        instance = cls.FileFieldModel()
        field = cls.FileFieldModel._meta.get_field("file")
        field.upload_to = ""
        instance.file.en.save("testfilename", temp_file)
        expected_value_to_string = json.dumps({"en": "testfilename"})
        astert field.value_to_string(instance) == expected_value_to_string

0 View Complete Implementation : files.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
    def _set_file(self, value):
        if not isinstance(value, File):
            value = File(value)
        self._file = value
        self._committed = False

0 View Complete Implementation : case.py
Copyright MIT License
Author : F0RE1GNERS
  def form_valid(self, form):
    global_create_time = datetime.now()
    option = form.cleaned_data["option"]
    case_number_start = form.cleaned_data["case_number"]
    cases = []

    if option == "text":
      input_binary = REFORMAT(form.cleaned_data["input_text"].encode(), self.revision.well_form_policy)
      output_binary = REFORMAT(form.cleaned_data["output_text"].encode(), self.revision.well_form_policy)
      description = "手动创建."
      case = Case(create_time=global_create_time,
                  in_samples=form.cleaned_data["in_samples"],
                  description=description,
                  activated=form.cleaned_data["activated"])
      case.input_file.save("in", ContentFile(input_binary), save=False)
      case.output_file.save("out", ContentFile(output_binary), save=False)
      case.save_fingerprint(self.problem.id)
      cases.append(case)

    elif option == "batch":
      tmp_directory = '/tmp/' + random_string()
      with zipfile.ZipFile(form.cleaned_data["batch_file"]) as myZip:
        myZip.extractall(path=tmp_directory)
      case_config = {}
      if path.exists(path.join(tmp_directory, "data.json")):
        with open(path.join(tmp_directory, "data.json")) as json_config:
          case_config = json.loads(json_config.read())
      for inf, ouf in sort_data_list_from_directory(tmp_directory):
        with open(path.join(tmp_directory, inf), 'rb') as ins, open(path.join(tmp_directory, ouf),
                                                                    'rb') as ous:
          conf = case_config.get(inf, {})
          case = Case(create_time=global_create_time,
                      description=conf.get("description", "\"%s\": (%s, %s)." %
                                           (form.cleaned_data["batch_file"].name, inf, ouf)),
                      in_samples=conf.get("in_samples", False),
                      activated=conf.get("activated", True),
                      group=conf.get("group", 0),
                      points=conf.get("points", 10))
          if self.revision.well_form_policy:
            case.input_file.save("in", ContentFile(REFORMAT(ins.read(), True)), save=False)
            case.output_file.save("out", ContentFile(REFORMAT(ous.read(), True)), save=False)
          else:
            case.input_file.save("in", File(ins), save=False)
            case.output_file.save("out", File(ous), save=False)
          case.save_fingerprint(self.problem.id)
          cases.append(case)
      shutil.rmtree(tmp_directory)

    # process case numbers
    remove_list = []
    if case_number_start <= 0:
      # auto fill the empty indices
      idx = 1
      exist = set(self.revision.cases.all().values_list("case_number", flat=True))
      for case in cases:
        while idx in exist:
          idx += 1
        exist.add(idx)
        case.case_number = idx
    else:
      idx = case_number_start
      for case in cases:
        case.case_number = idx
        idx += 1
      for case in self.revision.cases.filter(case_number__gte=case_number_start).order_by("case_number"):
        # do modifications to modified cases
        if idx != case.case_number:
          case.case_number = idx
          idx += 1
          case.parent_id = case.id
          remove_list.append(Case(pk=case.id))
          case.id = None
          cases.append(case)

    with transaction.atomic():
      for case in cases:
        case.save()
      self.revision.cases.add(*cases)
      self.revision.cases.remove(*remove_list)

    messages.success(self.request, "%d 组数据已成功添加." % len(cases))

    return redirect(self.get_success_url())

0 View Complete Implementation : storage.py
Copyright MIT License
Author : klis87
    def hashed_name(self, name, content=None, filename=None):
        parsed_name = urlsplit(unquote(name))
        clean_name = parsed_name.path.strip()
        opened = False
        if content is None:
            absolute_path = finders.find(clean_name)
            try:
                content = open(absolute_path, 'rb')
            except (IOError, OSError) as e:
                if e.errno == errno.ENOENT:
                    raise ValueError("The file '%s' could not be found with %r." % (clean_name, self))
                else:
                    raise
            content = File(content)
            opened = True
        try:
            file_hash = self.file_hash(clean_name, content)
        finally:
            if opened:
                content.close()
        path, filename = os.path.split(clean_name)
        root, ext = os.path.splitext(filename)
        if file_hash is not None:
            file_hash = ".%s" % file_hash
        hashed_name = os.path.join(path, "%s%s%s" % (root, file_hash, ext))
        unparsed_name = list(parsed_name)
        unparsed_name[2] = hashed_name
        # Special casing for a @font-face hack, like url(myfont.eot?#iefix")
        # http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax
        if '?#' in name and not unparsed_name[3]:
            unparsed_name[2] += '?'
        return urlunsplit(unparsed_name)