Skip to content

Commit

Permalink
Allow png factory to save to a string path
Browse files Browse the repository at this point in the history
  • Loading branch information
SmileyChris committed Feb 5, 2023
1 parent 8d38c15 commit 2ddbc55
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
3 changes: 2 additions & 1 deletion CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ Change log
7.5 (unreleased)
================

- Nothing changed yet.
- Allow ``pypng`` factory to allow for saving to a string (like
``qr.save("some_file.png")``) in addition to file-like objects.


7.4.1 (3 February 2023)
Expand Down
2 changes: 2 additions & 0 deletions qrcode/image/pure.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ def drawrect(self, row, col):
"""

def save(self, stream, kind=None):
if isinstance(stream, str):
stream = open(stream, "wb")
self._img.write(stream, self.rows_iter())

def rows_iter(self):
Expand Down
12 changes: 12 additions & 0 deletions qrcode/tests/test_qrcode.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,18 @@ def test_render_pypng(self):
print(img.width, img.box_size, img.border)
img.save(io.BytesIO())

def test_render_pypng_to_str(self):
qr = qrcode.QRCode()
qr.add_data(UNICODE_TEXT)
img = qr.make_image(image_factory=PyPNGImage)
self.assertIsInstance(img.get_image(), png.Writer)

mock_open = mock.mock_open()
with mock.patch("qrcode.image.pure.open", mock_open, create=True):
img.save("test_file.png")
mock_open.assert_called_once_with("test_file.png", "wb")
mock_open("test_file.png", "wb").write.assert_called()

@unittest.skipIf(not pil_Image, "Requires PIL")
def test_render_styled_Image(self):
qr = qrcode.QRCode(error_correction=qrcode.ERROR_CORRECT_L)
Expand Down

0 comments on commit 2ddbc55

Please sign in to comment.