Reputation: 321
Hi I'am generating QR code using qrcode library in Python. I have setup default storage location for images/files to be uploaded into S3 which is working fine if I am taking an input through API. But in case of generating QR code which is new image is not getting saved to the bucket in S3.
Models.py
class Item(models.Model):
name = models.CharField(max_length=30)
qr = models.ImageField(upload_to="asset_tags", null=True, blank=True)
image = models.ImageField(upload_to="asset_tags", null=True, blank=True)
Generate QR code:
def generate_qr(self, qr):
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_M,
box_size=15,
border=5
)
qr.add_data(qr)
qr.make(fit=True)
img = qr.make_image(fill='black', back_color='white')
img.save(qr+".png")
settings.py
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
Here Image field in models.py is the image which is uploaded by the user which gets saved in bucket. But the qrcode image gets saved in the root of project. I am confused if I need to convert this Pillow image object to django image field and it will get saved to bucket automatically.
Thanks, Any help will be appreciated.
Upvotes: 1
Views: 2958
Reputation: 321
I found the solution. I needed to call put_object API with aws credentials. This credentials should been passed in an environment variable file. This saves you file or Image into the bucket at the root if folder name isn't mentioned in key.
def generate_qr(self, qr):
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_M,
box_size=15,
border=5
)
qr.add_data(tag)
qr.make(fit=True)
img = qr.make_image(fill='black', back_color='white')
buffer = BytesIO()
img.save(buffer, "PNG")
buffer.seek(0) # rewind pointer back to start
s3 = boto3.client('s3')
s3 = boto3.client('s3', aws_access_key_id='ACCESS KEY HERE', aws_secret_access_key='SECRET ACCESS KEY', region_name='REGION NAME')
s3.put_object(
Bucket='BUCKET NAME',
Key='media/'+qr+'.png',
Body=buffer,
ContentType='image/png',
)
Thanks for all the help you guys did.
Upvotes: 4