parse_rest is a Python client for the Parse REST API. It provides Python object mapping for Parse objects with methods to save, update, and delete objects, as well as an interface for querying stored objects.
The easiest way to install this package is from PyPI, either using easy_install:
easy_install parse_rest
or pip:
pip install parse_rest
(if you are using a Mac or Linux system you may need to prepend sudo
to either command).
Alternatively, you can install it from source by downloading or cloning this repository:
git clone git@github.com:dgrtwo/ParsePy.git
and performing the commands:
python setup.py build
python setup.py install
(again you may have to add sudo
before python setup.py install
).
To run the tests, you need to:
- create a
settings_local.py
file in your local directory with three variables that define a sample Parse application to use for testing:
APPLICATION_ID = "APPLICATION_ID_HERE"
REST_API_KEY = "REST_API_KEY_HERE"
MASTER_KEY = "MASTER_KEY_HERE"
- install the Parse CloudCode command line tool
You can then test the installation by running:
python setup.py test
Let's get everything set up first. You'll need to give parse_rest
your Application Id and REST API Key (available from your Parse dashboard) in order to get access to your data.
import parse_rest
parse_rest.APPLICATION_ID = "your application id"
parse_rest.REST_API_KEY = "your REST API key here"
To create a new object of the Parse class GameScore
, you first create such a class inheriting parse_rest.Object
:
class GameScore(parse_rest.Object):
pass
And then initialize it with your parameters:
gameScore = GameScore(score=1337, player_name='John Doe', cheat_mode=False)
You can change or set new parameters afterwards:
gameScore.cheat_mode = True
gameScore.level = 20
Supported data types are any type that can be serialized by JSON and Python's datetime.datetime object. (Binary data and references to other Object's are also supported, as we'll see in a minute.)
To save our new object, just call the save() method:
gameScore.save()
If we want to make an update, just call save() again after modifying an attribute to send the changes to the server:
gameScore.score = 2061
gameScore.save()
You can also increment the score in a single API query:
gameScore.increment("score")
Now that we've done all that work creating our first Parse object, let's delete it:
gameScore.delete()
That's it! You're ready to start saving data on Parse.
The attributes objectId, createdAt, and updatedAt show metadata about a Object that cannot be modified through the API:
gameScore.objectId
# 'xxwXx9eOec'
gameScore.createdAt
# datetime.datetime(2011, 9, 16, 21, 51, 36, 784000)
gameScore.updatedAt
# datetime.datetime(2011, 9, 118, 14, 18, 23, 152000)
If we want to store data in a Object, we should wrap it in a ParseBinaryDataWrapper. The ParseBinaryDataWrapper behaves just like a string, and inherits all of str's methods.
gameScore.victoryImage = parse_rest.ParseBinaryDataWrapper('\x03\xf3\r\n\xc7\x81\x7fNc ... ')
We can also store geoPoint dataTypes as attributes using the format 'POINT(longitude latitude)'
, with latitude and longitude as float values
class Restaurant(parse_rest.Object):
pass
restaurant = Restaurant(name="Los Pollos Hermanos")
restaurant.location ="POINT(12.0 -34.45)"
restaurant.save()
We can store a reference to another Object by assigning it to an attribute:
class CollectedItem(parse_rest.Object):
pass
collectedItem = CollectedItem(type="Sword", isAwesome=True)
collectedItem.save() # we have to save it before it can be referenced
gameScore.item = collectedItem
To retrieve an object with a Parse class of GameScore
and an objectId
of xxwXx9eOec
, run:
gameScore = GameScore.Query.where(objectId="xxwXx9eOec").get()
We can also run more complex queries to retrieve a range of objects. For example, if we want to get a list of GameScore objects with scores between 1000 and 2000 ordered by playerName, we would call:
query = GameScore.Query.gte("score", 1000).lt("score", 2000).order("playerName")
game_scores = query.all()
Notice how queries are built by chaining filter functions. The available filter functions are:
- Less Than
- lt(parameter_name, value)
- Less Than Or Equal To
- lte(parameter_name, value)
- Greater Than
- gt(parameter_name, value)
- Greater Than Or Equal To
- gte(parameter_name, value)
- Not Equal To
- ne(parameter_name, value)
- Limit
- limit(count)
- Skip
- skip(count)
We can also order the results using:
- Order
- order(parameter_name, descending=False)
You can sign up, log in, modify or delete users as well, using the User
object. You sign a user up as follows:
u = parse_rest.User.signup("dhelmet", "12345", phone="555-555-5555")
or log in an existing user with
u = parse_rest.User.login("dhelmet", "12345")
Once a User
has been logged in, it saves its session so that it can be edited or deleted:
u.highscore = 300
u.save()
u.delete()
Parse offers CloudCode, which has the ability to upload JavaScript functions that will be run on the server. You can use the parse_rest
client to call those functions.
The CloudCode guide describes how to upload a function to the server. Let's say you upload the following main.js
script:
Parse.Cloud.define("hello", function(request, response) {
response.success("Hello world!");
});
Parse.Cloud.define("averageStars", function(request, response) {
var query = new Parse.Query("Review");
query.equalTo("movie", request.params.movie);
query.find({
success: function(results) {
var sum = 0;
for (var i = 0; i < results.length; ++i) {
sum += results[i].get("stars");
}
response.success(sum / results.length);
},
error: function() {
response.error("movie lookup failed");
}
});
});
Then you can call either of these functions using the parse_rest.Function
class:
hello_func = parse_rest.Function("hello")
hello_func()
{u'result': u'Hello world!'}
star_func = parse_rest.Function("averageStars")
star_func(movie="The Matrix")
{u'result': 4.5}
That's it! This is a first try at a Python library for Parse, and is probably not bug-free. If you run into any issues, please get in touch -- dgrtwo@princeton.edu. Thanks!