Commit fd97cacb by Raphael Lullis

Removing all the Parse prefix name from classes (except for ParseBase and…

Removing all the Parse prefix name from classes (except for ParseBase and ParseResource, which are classes that are just base classes). Also, adding a very basic Push class.
parent 7228a08b
...@@ -66,6 +66,10 @@ class ParseBase(object): ...@@ -66,6 +66,10 @@ class ParseBase(object):
def PUT(cls, uri, **kw): def PUT(cls, uri, **kw):
return cls.execute(uri, 'PUT', **kw) return cls.execute(uri, 'PUT', **kw)
@classmethod
def DELETE(cls, uri, **kw):
return cls.execute(uri, 'DELETE', **kw)
@property @property
def _attributes(self): def _attributes(self):
# return "public" attributes converted to the base parse representation. # return "public" attributes converted to the base parse representation.
...@@ -87,7 +91,7 @@ class ParseBase(object): ...@@ -87,7 +91,7 @@ class ParseBase(object):
def _convertToParseType(self, prop): def _convertToParseType(self, prop):
key, value = prop key, value = prop
if type(value) == ParseObject: if type(value) == Object:
value = {'__type': 'Pointer', value = {'__type': 'Pointer',
'className': value._class_name, 'className': value._class_name,
'objectId': value._object_id} 'objectId': value._object_id}
...@@ -106,7 +110,32 @@ class ParseBase(object): ...@@ -106,7 +110,32 @@ class ParseBase(object):
return (key, value) return (key, value)
class ParseUser(ParseBase): class ParseResource(ParseBase):
def __init__(self, **kw):
self._object_id = kw.pop('objectId', None)
self._updated_at = kw.pop('updatedAt', None)
self._created_at = kw.pop('createdAt', None)
for attr, value in kw.items():
self.__dict__[attr] = value
@classmethod
def retrieve(cls, resource_id):
return cls(**cls.GET('/' + resource_id))
_absolute_url = property(lambda self: '/'.join([self.__class__.ENDPOINT_ROOT + self._object_id]))
def objectId(self):
return self._object_id
def updatedAt(self):
return (self._updated_at and self._ISO8601ToDatetime(self._updated_at) or None)
def createdAt(self):
return (self._created_at and self._ISO8601ToDatetime(self._created_at) or None)
class User(ParseResource):
ENDPOINT_ROOT = '/'.join([API_ROOT, 'users']) ENDPOINT_ROOT = '/'.join([API_ROOT, 'users'])
@classmethod @classmethod
...@@ -121,21 +150,6 @@ class ParseUser(ParseBase): ...@@ -121,21 +150,6 @@ class ParseUser(ParseBase):
def request_password_reset(cls, email): def request_password_reset(cls, email):
return cls.POST('/'.join([API_ROOT, 'requestPasswordReset']), email=email) return cls.POST('/'.join([API_ROOT, 'requestPasswordReset']), email=email)
@classmethod
def retrieve(cls, user_id):
return cls(**cls.GET('/' + user_id))
def __init__(self, **kw):
self._object_id = kw.pop('objectId', None)
self._updated_at = kw.pop('updatedAt', None)
self._created_at = kw.pop('createdAt', None)
for attr, value in kw.items():
self.__dict__[attr] = value
_absolute_url = property(lambda self: '/'.join([self.__class__.ENDPOINT_ROOT + self._object_id]))
def save(self, session=None): def save(self, session=None):
session_header = {'X-Parse-Session-Token': session and session.get('sessionToken') } session_header = {'X-Parse-Session-Token': session and session.get('sessionToken') }
...@@ -144,7 +158,11 @@ class ParseUser(ParseBase): ...@@ -144,7 +158,11 @@ class ParseUser(ParseBase):
) )
class ParseObject(ParseBase): class Installation(ParseResource):
ENDPOINT_ROOT = '/'.join([API_ROOT, 'installations'])
class Object(ParseResource):
ENDPOINT_ROOT = '/'.join([API_ROOT, 'classes']) ENDPOINT_ROOT = '/'.join([API_ROOT, 'classes'])
def __init__(self, class_name, attrs_dict=None): def __init__(self, class_name, attrs_dict=None):
...@@ -156,17 +174,6 @@ class ParseObject(ParseBase): ...@@ -156,17 +174,6 @@ class ParseObject(ParseBase):
if attrs_dict: if attrs_dict:
self._populateFromDict(attrs_dict) self._populateFromDict(attrs_dict)
def objectId(self):
return self._object_id
def updatedAt(self):
return (self._updated_at and self._ISO8601ToDatetime(self._updated_at)
or None)
def createdAt(self):
return (self._created_at and self._ISO8601ToDatetime(self._created_at)
or None)
def save(self): def save(self):
if self._object_id: if self._object_id:
self._update() self._update()
...@@ -177,10 +184,7 @@ class ParseObject(ParseBase): ...@@ -177,10 +184,7 @@ class ParseObject(ParseBase):
# URL: /1/classes/<className>/<objectId> # URL: /1/classes/<className>/<objectId>
# HTTP Verb: DELETE # HTTP Verb: DELETE
uri = '/%s/%s' % (self._class_name, self._object_id) self.__class__.DELETE('/%s/%s' % (self._class_name, self._object_id))
self.__class__.execute(uri, 'DELETE')
self = self.__init__(None) self = self.__init__(None)
def increment(self, key, amount=1): def increment(self, key, amount=1):
...@@ -228,7 +232,7 @@ class ParseObject(ParseBase): ...@@ -228,7 +232,7 @@ class ParseObject(ParseBase):
if type(value) == dict and '__type' in value: if type(value) == dict and '__type' in value:
if value['__type'] == 'Pointer': if value['__type'] == 'Pointer':
value = ParseQuery(value['className']).get(value['objectId']) value = Query(value['className']).get(value['objectId'])
elif value['__type'] == 'Date': elif value['__type'] == 'Date':
value = self._ISO8601ToDatetime(value['iso']) value = self._ISO8601ToDatetime(value['iso'])
elif value['__type'] == 'Bytes': elif value['__type'] == 'Bytes':
...@@ -241,14 +245,6 @@ class ParseObject(ParseBase): ...@@ -241,14 +245,6 @@ class ParseObject(ParseBase):
return (key, value) return (key, value)
@property
def _attributes(self):
# return "public" attributes converted to the base parse representation.
return dict([
self._convertToParseType(p) for p in self.__dict__.items()
if p[0][0] != '_'
])
def _create(self): def _create(self):
# URL: /1/classes/<className> # URL: /1/classes/<className>
# HTTP Verb: POST # HTTP Verb: POST
...@@ -266,19 +262,25 @@ class ParseObject(ParseBase): ...@@ -266,19 +262,25 @@ class ParseObject(ParseBase):
uri = '/%s/%s' % (self._class_name, self._object_id) uri = '/%s/%s' % (self._class_name, self._object_id)
response_dict = self.execute(uri, 'PUT', **self._attributes) response_dict = self.__class__.PUT(uri, **self._attributes)
self._updated_at = response_dict['updatedAt'] self._updated_at = response_dict['updatedAt']
class Push(ParseResource):
ENDPOINT_ROOT = '/'.join([API_ROOT, 'push'])
class ParseQuery(ParseBase): @classmethod
ENDPOINT_ROOT = '/'.join([API_ROOT, 'classes']) def send(cls, message, channels=None, **kw):
alert_message = { 'alert': message }
targets = {}
if channels: targets['channels'] = channels
if kw: targets['where'] = kw
return cls.POST('', data=alert_message, **targets)
def __init__(self, class_name): class Query(ParseBase):
self._class_name = class_name
def __init__(self):
self._where = collections.defaultdict(dict) self._where = collections.defaultdict(dict)
self._options = {} self._options = {}
self._object_id = ''
def eq(self, name, value): def eq(self, name, value):
self._where[name] = value self._where[name] = value
...@@ -320,14 +322,37 @@ class ParseQuery(ParseBase): ...@@ -320,14 +322,37 @@ class ParseQuery(ParseBase):
return self return self
def get(self, object_id): def get(self, object_id):
self._object_id = object_id return self.__class__.QUERY_CLASS.retrieve(object_id)
return self._fetch(single_result=True)
def fetch(self): def fetch(self):
# hide the single_result param of the _fetch method from the library # hide the single_result param of the _fetch method from the library
# user since it's only useful internally # user since it's only useful internally
return self._fetch() return self._fetch()
def _fetch(self):
options = dict(self._options) # make a local copy
if self._where:
# JSON encode WHERE values
where = json.dumps(self._where)
options.update({'where': where})
response = self.__class__.GET('', **options)
return [self.__class__.QUERY_CLASS(**result) for result in response['results']]
class ObjectQuery(Query):
ENDPOINT_ROOT = '/'.join([API_ROOT, 'classes'])
def __init__(self, class_name):
self._class_name = class_name
self._where = collections.defaultdict(dict)
self._options = {}
self._object_id = ''
def get(self, object_id):
self._object_id = object_id
return self._fetch(single_result=True)
def _fetch(self, single_result=False): def _fetch(self, single_result=False):
# URL: /1/classes/<className>/<objectId> # URL: /1/classes/<className>/<objectId>
# HTTP Verb: GET # HTTP Verb: GET
...@@ -344,19 +369,19 @@ class ParseQuery(ParseBase): ...@@ -344,19 +369,19 @@ class ParseQuery(ParseBase):
response = self.__class__.GET('/%s' % self._class_name, **options) response = self.__class__.GET('/%s' % self._class_name, **options)
if single_result: if single_result:
return ParseObject(self._class_name, response) return Object(self._class_name, response)
else: else:
return [ParseObject(self._class_name, result) for result in response['results']] return [Object(self._class_name, result) for result in response['results']]
class ParseUserQuery(ParseQuery): class UserQuery(Query):
ENDPOINT_ROOT = '/'.join([API_ROOT, 'users']) ENDPOINT_ROOT = '/'.join([API_ROOT, 'users'])
QUERY_CLASS = User
def __init__(self):
self._where = collections.defaultdict(dict)
self._options = {}
def get(self, object_id): class InstallationQuery(Query):
return ParseUser.retrieve(object_id) ENDPOINT_ROOT = '/'.join([API_ROOT, 'installations'])
QUERY_CLASS = Installation
def _fetch(self): def _fetch(self):
options = dict(self._options) # make a local copy options = dict(self._options) # make a local copy
...@@ -365,5 +390,6 @@ class ParseUserQuery(ParseQuery): ...@@ -365,5 +390,6 @@ class ParseUserQuery(ParseQuery):
where = json.dumps(self._where) where = json.dumps(self._where)
options.update({'where': where}) options.update({'where': where})
response = self.__class__.GET('', **options) extra_headers = {'X-Parse-Master-Key': MASTER_KEY }
return [ParseUser(**result) for result in response['results']] response = self.__class__.GET('', extra_headers=extra_headers, **options)
return [self.__class__.QUERY_CLASS(**result) for result in response['results']]
...@@ -6,23 +6,23 @@ import unittest ...@@ -6,23 +6,23 @@ import unittest
import urllib2 import urllib2
import datetime import datetime
import __init__ as ParsePy import __init__ as parse
try: try:
import settings_local import settings_local
except ImportError: except ImportError:
raise ImportError("You must create a settings_local.py file " + raise ImportError(
"with an example application to run tests") 'You must create a settings_local.py file with an example application to run tests'
)
ParsePy.APPLICATION_ID = settings_local.APPLICATION_ID parse.APPLICATION_ID = settings_local.APPLICATION_ID
ParsePy.API_KEY = settings_local.API_KEY parse.API_KEY = settings_local.API_KEY
### FUNCTIONS ### ### FUNCTIONS ###
def test_obj(saved=False): def test_obj(saved=False):
"""Return a test ParsePy.ParseObject (content is from the docs)""" """Return a test parse.Object (content is from the docs)"""
ret = ParsePy.ParseObject("GameScore") ret = parse.Object("GameScore")
ret.score = 1337 ret.score = 1337
ret.playerName = "Sean Plott" ret.playerName = "Sean Plott"
ret.cheatMode = False ret.cheatMode = False
...@@ -33,11 +33,10 @@ def test_obj(saved=False): ...@@ -33,11 +33,10 @@ def test_obj(saved=False):
### CLASSES ### ### CLASSES ###
class TestObjectAndQuery(unittest.TestCase):
class TestParseObjectAndQuery(unittest.TestCase):
""" """
Tests for the ParsePy.ParseObject interface for creating and updating Parse Tests for the parse.Object interface for creating and updating Parse
objects, as well as the ParsePy.ParseQuery interface for retrieving them objects, as well as the parse.Query interface for retrieving them
""" """
def check_test_obj(self, o): def check_test_obj(self, o):
...@@ -52,13 +51,13 @@ class TestParseObjectAndQuery(unittest.TestCase): ...@@ -52,13 +51,13 @@ class TestParseObjectAndQuery(unittest.TestCase):
self.assertEqual(o.location, "POINT(-30.0 43.21)") self.assertEqual(o.location, "POINT(-30.0 43.21)")
def test_object(self): def test_object(self):
"""Test the creation, retrieval and updating of a ParseObject""" """Test the creation, retrieval and updating of a Object"""
gameScore = test_obj() gameScore = test_obj()
gameScore.save() gameScore.save()
self.check_test_obj(gameScore) self.check_test_obj(gameScore)
# retrieve a new one # retrieve a new one
query = ParsePy.ParseQuery("GameScore") query = parse.Query('GameScore')
obj1 = query.get(gameScore.objectId()) obj1 = query.get(gameScore.objectId())
self.check_test_obj(obj1) self.check_test_obj(obj1)
...@@ -95,7 +94,7 @@ class TestParseObjectAndQuery(unittest.TestCase): ...@@ -95,7 +94,7 @@ class TestParseObjectAndQuery(unittest.TestCase):
o.increment("score") o.increment("score")
self.assertEqual(o.score, 1338) self.assertEqual(o.score, 1338)
query = ParsePy.ParseQuery("GameScore") query = parse.Query("GameScore")
o2 = query.get(o.objectId()) o2 = query.get(o.objectId())
self.assertEqual(o2.score, 1338) self.assertEqual(o2.score, 1338)
...@@ -107,12 +106,12 @@ class TestParseObjectAndQuery(unittest.TestCase): ...@@ -107,12 +106,12 @@ class TestParseObjectAndQuery(unittest.TestCase):
def test_relationship(self): def test_relationship(self):
"""Test relationship between objects""" """Test relationship between objects"""
post = ParsePy.ParseObject("Post") post = parse.Object("Post")
post.title = "I'm Hungry" post.title = "I'm Hungry"
post.content = "Where should we go for lunch?" post.content = "Where should we go for lunch?"
post.save() post.save()
comment = ParsePy.ParseObject("Comment") comment = parse.Object("Comment")
comment.content = "Let's do Sushirrito" comment.content = "Let's do Sushirrito"
comment.parent = post comment.parent = post
comment.save() comment.save()
...@@ -124,8 +123,8 @@ class TestParseObjectAndQuery(unittest.TestCase): ...@@ -124,8 +123,8 @@ class TestParseObjectAndQuery(unittest.TestCase):
self.assertEqual(comment_id.__class__, unicode) self.assertEqual(comment_id.__class__, unicode)
# retrieve new ones # retrieve new ones
post2 = ParsePy.ParseQuery("Post").get(post_id) post2 = parse.Query("Post").get(post_id)
comment2 = ParsePy.ParseQuery("Comment").get(comment_id) comment2 = parse.Query("Comment").get(comment_id)
# check the relationship between the saved post and comment # check the relationship between the saved post and comment
self.assertEqual(comment2.parent.objectId(), post_id) self.assertEqual(comment2.parent.objectId(), post_id)
self.assertEqual(comment2.parent.title, "I'm Hungry") self.assertEqual(comment2.parent.title, "I'm Hungry")
...@@ -135,11 +134,10 @@ class TestParseObjectAndQuery(unittest.TestCase): ...@@ -135,11 +134,10 @@ class TestParseObjectAndQuery(unittest.TestCase):
o = test_obj(True) o = test_obj(True)
obj_id = o.objectId() obj_id = o.objectId()
self.check_test_obj(o) self.check_test_obj(o)
o2 = ParsePy.ParseQuery("GameScore").get(obj_id) o2 = parse.Query("GameScore").get(obj_id)
self.check_test_obj(o2) self.check_test_obj(o2)
o2.delete() o2.delete()
self.assertRaises(urllib2.HTTPError, self.assertRaises(urllib2.HTTPError, parse.Query("GameScore").get, obj_id)
ParsePy.ParseQuery("GameScore").get, obj_id)
if __name__ == "__main__": if __name__ == "__main__":
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment