Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added storage capabilities to pgzero #99

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions doc/builtins.rst
Original file line number Diff line number Diff line change
Expand Up @@ -738,3 +738,63 @@ This could be used in a Pygame Zero program like this::

def on_mouse_down():
beep.play()


.. _data_storage:


Data Storage
------------

The ``storage`` object behaves just like a dictionary but has two additional methods to
allow to save/load the data to/from the disk.

Because it's a dictionary-like object, it supports all operations a dictionary does.
For example, you can update the storage with another dictionary, like so::

my_data = {'player_turn': 1, 'level': 10}
storage.update(my_data)

On windows the data is saved under ``%APPDATA%/pgzero/saves/`` and on Linux/MacOS under ``~/.config/pgzero/saves/``.

The saved files will be named after their module name.

**NOTE:** Make sure your scripts have different names, otherwise they will be picking each other data.

.. class:: Storage

.. method:: save()

Saves the data to disk.

.. method:: load()

Loads the data from disk.
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should cover what happens if there is no previous save data.


Example of usage::

# Setting some values
storage['my_score'] = 500
storage['level'] = 1

# You can have nested lists and dictionaries
storage['high_scores'] = []
storage['high_scores'].append(10)
storage['high_scores'].append(12)
storage['high_scores'].append(11)
storage['high_scores'].sort()

# Save storage to disk.
storage.save()


Following on the previous example, when starting your program, you can load that data back in::
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please could you add an example where we define defaults before we call storage.load()?


storage.load()

my_score = storage['my_score']

level = storage['level']

# Can use the get method from dicts to return a default value
storage.get('lifes', 3)
1 change: 1 addition & 0 deletions pgzero/builtins.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from . import music
from . import tone
from .actor import Actor
from .storage import storage
from .keyboard import keyboard
from .animation import animate
from .rect import Rect, ZRect
Expand Down
3 changes: 3 additions & 0 deletions pgzero/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from .game import PGZeroGame, DISPLAY_FLAGS
from . import loaders
from . import builtins
from .storage import Storage


def _check_python_ok_for_pygame():
Expand Down Expand Up @@ -102,6 +103,8 @@ def prepare_mod(mod):
set before the module globals are run.

"""
fn_hash = hash(mod.__file__) % ((sys.maxsize + 1) * 2)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this hash might need to be stronger than this. Also I don't believe hash() is necessarily stable across Python interpreter versions. I'd suggest using hashlib.sha1().

Storage.set_app_hash(format(fn_hash, 'x'))
loaders.set_root(mod.__file__)
PGZeroGame.show_default_icon()
pygame.display.set_mode((100, 100), DISPLAY_FLAGS)
Expand Down
114 changes: 114 additions & 0 deletions pgzero/storage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import json
import os
import platform
import logging


logger = logging.getLogger(__name__)


__all__ = ['StorageCorruptionException', 'JSONEncodingException', 'Storage']


class StorageCorruptionException(Exception):
"""The data in the storage is corrupted."""


class JSONEncodingException(Exception):
"""The data in the storage is corrupted."""


class Storage(dict):

path = ''

"""Behaves like a dictionary with a few extra functions.
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This docstring needs to be the first thing in the class - above path = ''


It's possible to load/save the data to disk.

The name of the file will be the script's name hashed.

NOTE: If two scripts have the same name, they will load/save from/to
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would expect this only if they have exactly the same path in the filesystem, no?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was getting the name from mod.__file__ so basically, if people use the relative path for the script when calling pgzrun intro.py then I would only get intro.py.

I corrected this to check if the path is absolute and if it isn't I convert it to absolute, like so:

    filename = mod.__file__

    if not os.path.isabs(filename):
        filename = os.path.join(os.getcwd(), filename)

    fn_hash = hashlib.sha1(filename.encode('utf-8'))

    Storage.set_app_hash(fn_hash.hexdigest())

the same file.
"""
def __init__(self):
dict.__init__(self)

storage_path = self._get_platform_pgzero_path()
if not os.path.exists(storage_path):
os.makedirs(storage_path)

@classmethod
def set_app_hash(cls, name):
storage_path = cls._get_platform_pgzero_path()
cls.path = os.path.join(storage_path, '{}.json'.format(name))

def load(self):
"""Load data from disk."""
self.clear()

try:
with open(self.path, 'r') as f:
data = json.load(f)
except FileNotFoundError:
# If no file exists, it's fine
logger.debug('No file to load data from.')
except json.JSONDecodeError:
msg = 'Storage is corrupted. Couldn\'t load the data.'
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should use double-quotes for human readable strings so that you don't have to escape apostrophes :-)

logger.error(msg)
raise StorageCorruptionException(msg)
else:
self.update(data)

def save(self):
"""Save data to disk."""
try:
data = json.dumps(self)
except TypeError:
json_path, key_type_obj = self._get_json_error_keys(self)
msg = 'The following entry couldn\'t be JSON serialized: storage{} of type {}'
msg = msg.format(json_path, key_type_obj)
logger.error(msg)
raise JSONEncodingException(msg)
else:
with open(self.path, 'w+') as f:
f.write(data)

@classmethod
def _get_json_error_keys(cls, obj, json_path=''):
"""Work out which part of the storage failed to be JSON encoded.

This function returns None if there is no error.
"""

if type(obj) in (float, int, str, bool):
return None
elif isinstance(obj, list):
for i, value in enumerate(obj):
result = cls._get_json_error_keys(value, '{}[{}]'.format(json_path, i))
if result is not None:
return result
elif isinstance(obj, dict):
for k, v in obj.items():
result = cls._get_json_error_keys(v, '{}[\'{}\']'.format(json_path, k))
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should check that k is a string: JSON only supports strings as dict keys.

Also on this line, you're better to write:

'{}[{!r}]'.format(json_path, k)

as the repr of a string containing special characters is more complicated than "'{}'".format(s)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is done, need to write a unittest for it.

if result is not None:
return result
else:
# TODO: Could have a custom JSONEncoder in the future, in which case we would
# have to actually run json.dumps on it to get the result and possibly even
# drill down on the parameters we got back, if that object happens to have
# a list as an attribute, for example.
return (json_path, type(obj))

# Explicitly returning None for the sake of code readability
return None

@staticmethod
def _get_platform_pgzero_path():
"""Attempts to get the right directory in Windows/Linux.MacOS"""
if platform.system() == 'Windows':
return os.path.join(os.environ['APPDATA'], 'pgzero')
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will crash with KeyError if %APPDATA% is not defined. Does that happen? Is there a fallback?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure, I haven't used Windows in years. But I would assume it's always set like $HOME and $SHELL on Linux.

return os.path.expanduser(os.path.join('~', '.config/pgzero/saves'))
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks odd. The reason to use os.path.join() is so that you don't have to assume os.sep is /. But the second parameter contains /.

os.path.join() accepts multiple arguments, which will let you remove the /-s from .config/pgzero/saves.

Or you could assume that os.sep is / except on Windows, so just return `os.path.expanduser('~/.config/pgzero/saves').

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed, rookie mistake.



storage = Storage()
42 changes: 42 additions & 0 deletions test/test_storage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import unittest
from unittest import mock
from unittest.mock import patch

from pgzero.storage import Storage


class StorageStaticMethodsTest(unittest.TestCase):
def test_dict_with_no_errors(self):
obj = {'level': 10, 'player_name': 'Daniel'}

result = Storage._get_json_error_keys(obj)
self.assertIsNone(result)

def test_dict_with_errors(self):
obj = {'level': 10, 'player_name': 'Daniel', 'obj': object()}
expected_result = ("['obj']", type(object()))

result = Storage._get_json_error_keys(obj)
self.assertEqual(result, expected_result)

def test_dict_with_nested_dicts_errors(self):
subobj0 = {'this_key_fails': object()}
subobj1 = {'a': 10, 'b': 20, 'c': 30, 'obj': subobj0}
subobj2 = {'player_name': 'Daniel', 'level': 20, 'states': subobj1}
obj = {'game': 'my_game', 'state': subobj2}
expected_result = ("['state']['states']['obj']['this_key_fails']", type(object()))

result = Storage._get_json_error_keys(obj)
self.assertEqual(result, expected_result)


class StorageTest(unittest.TestCase):
@patch('pgzero.storage.os.path.exists')
def setUp(self, exists_mock):
exists_mock.return_value = True
self.storage = Storage()

def test_get(self):
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're just testing the "happy path" here. You should have tests for the file not existing, or existing but containing invalid JSON.

with patch('builtins.open', mock.mock_open(read_data='{"a": "hello"}')) as m:
self.storage.load()
self.assertEqual(self.storage['a'], 'hello')