0

Suppose I'm using requests to open an image url and read the data, save as BLOB data to MySQL, what is the most efficient way of doing it?

I did some search and looks like PIL.Image & StringIO method is recommended, as in this document : http://docs.python-requests.org/en/latest/user/quickstart/#binary-response-content

There are some other methods, as mentioned in this question : How do I read image data from a URL in Python?

However, I seem to be using a "simpler" way of implementing the task, I "think" the code works fine, since from my datbase I'm able to open the saved image. So I shouldn't be worried about it... However, I'm not sure whether there are potential problems (since it's not suggested anywhere, not as I'm aware of)... Could someone help me look at the following code and let me know if it is problematic.

import requests
import pymysql
import pymysql.cursor

connection = pymysql.connect(user='root',host='localhost',database='mysql')
mycursor=connection.cursor()    ## connect to database

pic_url='http://example_photo.jpg'
data=requests.get(pic_url)   # read image
photo=data.content

sql=""" INSERT INTO table_photo (url, photo) VALUES (%s, %s)""" 
mycursor.execute(sql, (pic_url, photo)) 
connection.commit()  # save to database
Community
  • 1
  • 1
Ruby
  • 284
  • 1
  • 5
  • 18

1 Answers1

0

Your code looks fine. The difference you see between reading the image with PIL and storing it in the database is that PIL needs to open the data from a file stream, not from a byte array. Since you do not need the file stream, you can skip the (c)StringIO step.

The only comment I have on your code is that you should keep in mind that since you are not opening the file as an image, you have no guarantee that an image is being inserted into the database. You're just storing whatever you get back as a response to your HTTP call. You might find it safer to open the file in PIL just to make sure it parses as an image.

sirdodger
  • 1,044
  • 11
  • 7