We want to import contacts photos from google API.
Following code was working for me.
for email, name, entry in feed:
photo = client.GetPhoto(entry)
if photo:
fname = str(uuid.uuid4()) + '.jpg'
image_file = open(dname + '/' + fname, 'wb')
image_file.write(photo)
image_file.close()
result[email] = '/media/import/%s/%s' % (dir, fname)
Now, for some reasons, we get in files atom feed copy. So method GetPhoto no working.
Any ideas, why it happened and what is current way to retrieve contacts photo?
Here is work around google API changes. Now we're using direct requests to API.
for email, name, entry in feed:
photo_link = e.GetPhotoLink()
if photo_link:
request = http.request(
'GET',
photo_link.href,
headers={
'Authorization':'OAuth %s' % client.current_token.access_token
}
)
if request.status == 200:
photo = str(request.read())
fname = str(uuid.uuid4()) + '.jpg'
image_file = open(dname + '/' + fname, 'wb')
image_file.write(photo)
image_file.close()
result[email] = '/media/import/%s/%s' % (tid, fname) #str(photo.href) #
Related
I am currently working on a Django app that allows me to download an image while only storing the image as a temporary file. My Django app is running on a server while I am accessing the website through a local windows machine. While I am able to download the image, the file will not open. For example, Windows Photos says that "It appears we don't support this file format". Is there something wrong with the code that would cause this problem?
Views.py
def download_png(request, study):
Names(study) #Function to retrieve (name) variable
Retrieve(study) #Function to retrieve (data) variable
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
pngfilename = str(name) + "_" + str(current_time) + ".png"
filepath = BASE_DIR + '/polls/graphics/' + pngfilename
temp, filepath = tempfile.mkstemp(suffix='.png')
with open(temp, 'w') as f:
f = df2img.plot_dataframe(data)
df2img.save_dataframe(fig=f, filename=filepath)
response = HttpResponse(temp, content_type=mimetypes.guess_type(filepath))
response['Content-Disposition'] = "attachment; filename=%s" % pngfilename
return response
Update 06/30/22:
Thank you for all the help. It turns out it is better to use FileResponse rather than HttpResponse when downloading a file Here's what the updated code looks like:
def download_png(request, study):
Names(study)
Retrieve(study)
pngfilename = str(name) + "_" + str(current_time) + ".png"
mime_type, _ = mimetypes.guess_type(pngfilename)
fig = df2img.plot_dataframe(data)
df2img.save_dataframe(fig=fig, filename=pngfilename)
response = FileResponse(open(pngfilename, 'rb'), content_type=mime_type)
response['Content-Disposition'] = "attachment; filename=%s" % pngfilename
os.remove(pngfilename)
return response
I am currently trying to create a function within a Django app to download a pandas dataframe as an image. I wanted to create the image as a temporary file, download it, then delete it. Does anyone know how to integrate tempfile into this code?
Views.py
def download_png(request, study):
Names(study) #Funciton to get (name) variable
Retrieve(study) #Function to get (data) variable
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
pngfilename = str(name) + "_" + str(current_time) + ".png"
temp = tempfile.NamedTemporaryFile(suffix=".png")
fig = temp.write(df2img.plot_dataframe(data))
filepath = temp.name
response = HttpResponse(df2img.save_dataframe(fig=fig, filename=filepath), content_type=mimetypes.guess_type(filepath))
response['Content-Disposition'] = "attachment; filename=%s" % pngfilename
return response
Update 06/30/22:
I had a lot of difficulty integrating the tempfile module because it requires data to be converted to bytes-like objects. Instead I simply resolved on deleting the file after creating it.
def download_png(request, study):
Names(study)
Retrieve(study)
pngfilename = str(name) + "_" + str(current_time) + ".png"
mime_type, _ = mimetypes.guess_type(pngfilename)
fig = df2img.plot_dataframe(data)
df2img.save_dataframe(fig=fig, filename=pngfilename)
response = FileResponse(open(pngfilename, 'rb'), content_type=mime_type)
response['Content-Disposition'] = "attachment; filename=%s" % pngfilename
os.remove(pngfilename)
return response
This is how you can use the tempfile library:
tempfile = tempfile.mktemp(suffix='.png')
with open(temp, 'w') as f:
f.write(df2img.plot_dataframe(data))
do_something_with_your_file(temp)
os.unlink(temp)
Edit: was just reading the tempfile documentation and apparently tempfile.mktemp is prone to race conditions, so you should either use tempfile.mkstemp like:
fd, tempf = tempfile.mkstemp()
Or there is a context manager:
with tempfile.NamedTemporaryFile() as tmp:
with open(tmp.name, 'w') as f:
f.write('some data')
# do something with your tempfile file
And then it will automatically delete the tempfile afterwards.
I am successfully saving the content for each email with the following code, as a .txt, .html or .PDF file. However, I would like to save a version of every content_type, for each email (for each uid). Currently it is only saving one file type for every uid.
For example, an email with a PDF attachment is only currently saving the PDF. I would like it to save the PDF attachment along with the plain text content of the email, in 2 separate files.
Thanks for any help.
import imaplib
import email
import os
import mimetypes
mail = imaplib.IMAP4_SSL('imap.secureserver.net',993)
mail.login('[user]', '[pw]')
mail.select('Inbox')
result, data = mail.uid('search', None, 'ALL')
item_list = data[0].split()
for item in item_list:
result2, email_data = mail.uid('fetch',item,'(RFC822)')
raw_email = email_data[0][1].decode("utf-8")
email_message = email.message_from_string(raw_email)
print_dir = False
if print_dir: print(dir(email_message)) #options, e.g. list of from, to etc.
from_ = email_message['From']
date_ = email_message['Date']
for part in email_message.walk():
option = str(item)[2:-1] + ' ' + date_[:-15] + ' ' + from_ + ' '
content_type = part.get_content_type()
print(str(item),' ',content_type)
if content_type == 'text/html':
filename = option + '.html'
elif content_type == 'text/plain':
filename = option + '.txt'
elif content_type == 'application/pdf':
attachment = part.get_filename() #attachment filename
filename = option + str(attachment)
else:
# Guesses the file type
ext = mimetypes.guess_extension(content_type)
if not ext:
ext = '.bin'
filename = option + ext
save_path = os.getcwd() + '/' + filename
with open(save_path, 'wb') as fp:
fp.write(part.get_payload(decode=True))
^ For multitypes I would like to save a file with all the type extensions. Such as for 22382, a PDF and txt
^ Current Output files
I'm not fully sure, but I think your problem is in the for item in item_list: loop.
email_message would only end up being whatever the last item in that loop creates.
Would you need to push nearly everything in that loop 1 tab's worth out?
Also I'd assume you'd want to use part instead of item in this line: option = str(item)[2:-1] + ' ' + date_[:-15] + ' ' + from_ + ' '
Again, not fully sure, but hope this helps!
I am trying to make a function that makes thumbnail of an image but I am unable to open the image file.
def create_thumbnail(request):
slug = 'yftguhjkn'
post = get_object_or_404(Post, slug=slug)
if post:
markdownify = import_string(MARKDOWNX_MARKDOWNIFY_FUNCTION)
content = BeautifulSoup(markdownify(post.content), "html5lib")
try:
img_link = content.findAll('img')[0].get('src')
print(img_link)
filename = img_link.split('/')[-1]
filename = filename.split('.')[0]
file_path = settings.MEDIA_URL + settings.DRACEDITOR_UPLOAD_PATH + post.author.username + '/' + filename + '.jpg'
print (file_path)
#im = Image.open(img_link)
im = Image.open(file_path)
print (im.size)
except:
img_link = 'http://howtorecordpodcasts.com/wp-content/uploads/2012/10/YouTube-Background-Pop-4.jpg'
return HttpResponse(img_link)
But it is going to except statement. Can someone please tell me how to fix it.
def create_thumbnail(request):
slug = 'yftguhjkn'
post = get_object_or_404(Post, slug=slug)
if post:
markdownify = import_string(MARKDOWNX_MARKDOWNIFY_FUNCTION)
content = BeautifulSoup(markdownify(post.content), "html5lib")
#try:
img_link = content.findAll('img')[0].get('src')
print(img_link)
filename = img_link.split('/')[-1]
filename = filename.split('.')[0]
file_path = settings.MEDIA_URL + settings.DRACEDITOR_UPLOAD_PATH + post.author.username + '/' + filename + '.jpg'
print (file_path)
im = Image.open(file_path)
print (im.size)
#except:
#img_link = 'http://howtorecordpodcasts.com/wp-content/uploads/2012/10/YouTube-Background-Pop-4.jpg'
return HttpResponse(file_path)
I think the Pillow need a correct path (full path) from the image to open.
im = Image.open(file_path)
the commond output of settings.MEDIA_URL is /media/ right?
so, you need to file_path is the full path, eg:
/home/myuser/myenv/myproject/media/images/uploads/2017/05/29/foobar.png
If your settings.MEDIA_ROOT is:
/home/myuser/myenv/myproject/media
You can doing with:
os.path.join(settings.MEDIA_ROOT, settings.DRACEDITOR_UPLOAD_PATH, image_name)
# example:
'/home/myuser/myenv/myproject/media' + 'images/uploads/2017/05/29/' + 'foobar.png'
you can also using BASE_DIR for absolute dir.
I'm trying to rotate and save the image to GCS with the below code.
img = images.Image(blob_key=image.blob)
img.rotate(270)
t = img.execute_transforms(output_encoding=images.PNG)
filename = '/' + UploadHandler.get_gs_bucket_for_images() + 'blobstore_demo.png'
with gcs.open(filename, 'w') as f:
f.write(t)
blobstore_filename = '/gs' + filename
key = blobstore.create_gs_key(blobstore_filename)
But when I try to view the file using GAE's blostore Viewer, I get an encoded image. That is, the content-type for that blob is not set to image/png. So how I managed to set the content-type?
You can define your image mimetype, just edit yor code this way:
img = images.Image(blob_key=image.blob)
img.rotate(270)
t = img.execute_transforms(output_encoding=images.PNG)
filename = '/' + UploadHandler.get_gs_bucket_for_images() + 'blobstore_demo.png'
mimetype = 'image/png'
with gcs.open(filename,'w', content_type=mimetype) as f:
f.write(t)
blobstore_filename = '/gs' + filename
key = blobstore.create_gs_key(blobstore_filename)