Django

Code

Ticket #4948: safe_filename_gen__modelsonly.1.diff

File safe_filename_gen__modelsonly.1.diff, 1.7 kB (added by rcoup, 10 months ago)
  • django/db/models/base.py

    old new  
    380380            pass 
    381381        filename = field.get_filename(filename) 
    382382 
    383         # If the filename already exists, keep adding an underscore to the name of 
    384         # the file until the filename doesn't exist. 
    385         while os.path.exists(os.path.join(settings.MEDIA_ROOT, filename)): 
     383        # Generate a unique filename 
     384        while True: 
     385            full_filename = os.path.join(settings.MEDIA_ROOT, filename) 
    386386            try: 
     387                # Try and open our filename, but only if it doesn't exist  
     388                # and we can open it exclusively. This won't necessarily work on 
     389                # NFS and some other networked filesystems, but will be ok in normal 
     390                # cases. 
     391                fd = os.open(full_filename, os.O_RDWR | os.O_CREAT | os.O_EXCL) 
     392                break; 
     393            except OSError, e: 
     394                # Someone else grabbed this name already 
     395                pass 
     396 
     397            # If the filename already exists, keep adding an underscore to the name of 
     398            # the file until the filename doesn't exist. 
     399            try: 
    387400                dot_index = filename.rindex('.') 
    388401            except ValueError: # filename has no dot 
    389402                filename += '_' 
     
    393406        # Write the file to disk. 
    394407        setattr(self, field.attname, filename) 
    395408 
    396         full_filename = self._get_FIELD_filename(field) 
    397         fp = open(full_filename, 'wb') 
     409        fp = os.fdopen(fd, 'w+b') 
    398410        fp.write(raw_contents) 
    399411        fp.close() 
    400412