python, django: copy image - python

I created this function, to copy an image from a django-model to another django-model. The image has to be saved redundantly:
def __copy_file__(from_object,to_object,field):
attr = field.attname
try:
newpath = getattr(from_object,attr).path
dot_at = newpath.rfind(".")
while os.path.exists(newpath):
newpath = newpath[:dot_at] + "_" + newpath[dot_at:]
shutil.copyfile(getattr(from_object,attr).path, newpath)
getattr(to_object,attr).save(newpath, File(open(getattr(from_object,attr).path)))
return True
except ValueError:
return False
But this function creates somehow invalid files.. I can remember it worked one day, but i tested it today and it isn't working anymore..
Edit: Now i know that the function produces two images. One that works and one that doesn't. The line shutil.copyfile (etc) produces the working one and in the assignment getattr(to_object,attr).save (etc) the image gets saved again. So this is the problem. It should just be assigned, not copied again..
Can anybody help me? :)

the way I do it, assuming from_model and to_model are to models instances with an image ImageField:
def copy_image(from_model, to_model):
to_model.image.save(from_model.image.url.split('/')[-1],from_model.image.file,save=True)

Related

'str' object has no attribute 'open' in python

I have created a simple streamlit app which has two option one is file upload another one is capturing image
while trying to open the uploaded file i am getting an error 'str' object has no attribute 'open' .
I am not sure why the issue is occurring kindly let me know how to solve this so that i can move forward
import streamlit as st
import numpy as np
import cv2
from PIL import Image
Image = st.sidebar.selectbox(
'Choose your method',
('Upload','Capture'))
if Image == 'Upload':
uploaded_file = st.file_uploader("HI",type=['jpg','png','jpeg'])
if uploaded_file is not None:
image = Image.open(uploaded_file)
st.image(image,width=300)
else:
file_image = st.camera_input(label = "Take a pic of you to be sketched out")
You have here two Image keywords, one of them is the Image library you imported from PIL, and the other is the return from your selectbox, which is a string.
Since the second one is declared later, it has overridden the first one, thus giving you this error when you try to call open.
I suggest renaming the second one to anything else and it should work properly.

Python - Going over a list of words in python with for loop

Getting back into programming, I've been messing with this for a while now sure it's something super simple or maybe I have things set-up completely wrong.
It's an issue with it not iterating over the rest of the list.
So whenever you run the code you enter a file extension i.e. "File.jpg" and it comes back with image, but if you enter any of the other image types it returns application.
def main():
file = input("File name:")
extension(file)
def extension(s):
split = (s.split("."))
join_s = (''.join(split[1]))
image_e = ['jpg', 'gif', 'jpeg', '.png']
for i in image_e:
print(image_e)
if i == join_s:
return print("Image/")
else:
return print("Application")
main()
I haven't got to the part of implementing the application formats just yet, but I am sure once I figure this bit out it shouldn't be any sort of issue.
Change your if statement to "if join_s in image_e:" should work. Also,"png" inside image_e should not have a "." infront of it

TypeError while using Pool from multiprocessing (python 3.7)

I'm trying to sum up the sizes of all files in a directory including recursive subdirectories. The relevant function (self._count) works totaly fine if I just call it once. But for large amounts of files I want to use multiprocessing to make the program faster. Here are the relevant parts of the code.
self._sum_dict sums the values of the same keys of the given dicts up.
self._get_file_type returns the category (key for stats) the file shall be placed.
self._categories holds a list of all possible categorys.
number_of_threats specifies the number of workers thal shall be used.
path holds the path to the directory meantioned in the first sentence.
import os
from multiprocessing import Pool
def _count(self, path):
stats = dict.fromkeys(self._categories, 0)
try:
dir_list = os.listdir(path)
except:
# I do some warning here, but removed it for SSCCE
return stats
for element in dir_list:
new_path = os.path.join(path, element)
if os.path.isdir(new_path):
add_stats = self._count(new_path)
stats = self._sum_dicts([stats, add_stats])
else:
file_type = self._get_file_type(element)
try:
size = os.path.getsize(new_path)
except Exception as e:
# I do some warning here, but removed it for SSCCE
continue
stats[file_type] += size
return stats
files = []
dirs = []
for e in dir_list:
new_name = os.path.join(path, e)
if os.path.isdir(new_name):
dirs.append(new_name)
else:
files.append(new_name)
with Pool(processes=number_of_threats) as pool:
res = pool.map(self._count, dirs)
self._stats = self._sum_dicts(res)
I know, that this code won't consider files in path, but that is something that I can add easily add. When execuding the code I get the following exception.
Exception has occurred: TypeError
cannot serialize '_io.TextIOWrapper' object
...
line ... in ...
res = pool.map(self._count, dirs)
I found out, that this exception can occure when sharing resources betwenen processes, which - as far as I can see - I only do with stats = dict.fromkeys(self._categories, 0). But replacing this line with hardcoded values won't fix the problem. Even placing a breakpoint at this line won't help me, because it isn't reached.
Does anybody have an idea what the reason for this problem is and how I can fix this?
The problem is you try to transmit "self". If self has a Stream object it can't be serialized.
Try and move the multiprocessed code outside the class.
Python multiprocessing launches a new interpreter and if you try to access shared code that can't be pickled (or serialized) it fails. Usually it doesn't crash where you think it crashed... but when trying to recieve the object.
I converted a code using threads to multiprocessing and i had a lot of wierd errors even i didn't sent or used those objects, but i used their parent ( self )

Django - AttributeError _committed

I have a form that saves an image, and everything is working fine, but I want to be able to crop the image. However, when I used Pillow to do this, I get a strange error that doesn't really give me much to go on.
Attribute error at /userprofile/addGame/
_committed
Looking further into the traceback, the following sections were highlighted:
I'm not really sure what this error means. I think it has something to do with the form.save(committed=False), and not being able to edit files after that point, but I'm not positive. I can edit the user after that line using form.user = request.user, so I think it's the fact that I'm trying to change the image getting uploaded that is part of the issue.
This is an old post but I recently experienced a similar problem.
The information in the question is somewhat incomplete but I had the same error.
Assuming the Error being
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/PIL/Image.py", line 627, in __getattr__
raise AttributeError(name)
AttributeError: _committed
So the root problem lies with using PIL (Pillow). The function :
image = Image.open(self.cleaned_data['image'])
We wrongly assume that the object image would continue to have the
instance of image throughout the function(clean_image in my case).
So in my code structure,
def clean_image(self):
if self.cleaned_data['image']:
try:
image = Image.open(self.cleaned_data['image'])
image.verify()
except IOError:
raise forms.ValidationError(_('The file is not an image'))
return image
The error mentioned above is thrown after we execute this code. It is so because
After several of the other PIL(pillow) functions we use, we need to
open the file again. Check this out in pillow documentation
As in the code above(last line),
return image
doesn't really return anything.
To fix it
Simply add ,
image = self.cleaned_data['image']
before the return image line.
Code looks like,
except IOError:
raise forms.ValidationError(_('The file is not an image'))
image = self.cleaned_data['image']
return image
I had faced the same issue trying to save a model with an ImageFileField. My requirement was to save an image from a zip object.
Using pillow gave me the AttributeError: _committed error. Following is what worked for me:
from django.core.files.images import ImageFile
zf = zipfile.ZipFile(zip_file, mode='r')
image_list = zf.infolist()
Model.objects.create(img=ImageFile(zipObj.open(image_list[0])),
file_name=image_list[0].filename.split("/")[-1].strip(),
...)

How to use TideSDK openFolderChooseDialog

I'm trying to use TideSDK and python tp get the user to select a folder from the hard drive. Everything works, but I have no idea how obtain which folder the user selected.
I can't seem to find documentation on what Ti.UI.UserWindow.openFolderChooseDialog returns and what kind of object the callback function uses. I just get errors that "window" in "onopen" in my code below is a None Type object when I try to print it out.
Is there any documentation on the proper use of the openFolderChooseDialog, what signature the callback needs to be and how to get the Folder/directory from the dialog?
My code:
def onopen(window):
Ti.App.stdout("------------------ Opening Dialog")
Ti.App.stdout(window)
def burndir():
try:
dir = Ti.UI.getCurrentWindow().openFolderChooserDialog(onopen)
Ti.App.stdout(dir)
except:
Ti.App.stderr("------ There was an error: ")
Ti.App.stderr(sys.exc_info()[0])
Ti.App.stderr(sys.exc_info()[1])
Ti.App.stderr(sys.exc_info()[2])
Any help is much appreciated
I found the answer in a Javascript Code example here:
https://github.com/appcelerator/titanium_developer/blob/master/Resources/perspectives/projects/js/projects.js#L1338
It appears that openFolderChooserDialog return nothing (a None object in Python). The callback function passes one argument which is a StaticBoundList (a Tuple object in Python) that contains all of the selected folders (in case of allowing multiple selections)
Here is the updated code:
def onopen(window):
if (len(window) > 0):
Ti.App.stdout("------------------ Opening Dialog")
Ti.App.stdout(window[0])
else:
Ti.App.stdout("------------------ Nothing Selected")
def burndir():
try:
Ti.UI.getCurrentWindow().openFolderChooserDialog(onopen)
except:
Ti.App.stderr("------ There was an error: ")
Ti.App.stderr(sys.exc_info()[0])
Ti.App.stderr(sys.exc_info()[1])
Ti.App.stderr(sys.exc_info()[2])
I hope this helps someone struggling to find the same documentation!

Categories

Resources