initial (working) version of python client library (including CLI script)

This commit is contained in:
James Walker 2012-01-21 20:27:48 -05:00
parent 8971eba9f9
commit 259a2f2e56
5 changed files with 212 additions and 0 deletions

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
*.pyc
build

99
README.markdown Normal file
View file

@ -0,0 +1,99 @@
Open Photo API / Python Library
=======================
#### OpenPhoto, a photo service for the masses
----------------------------------------
<a name="install"></a>
### Installation
python setup.py install
----------------------------------------
<a name="python"></a>
### How to use the library
To use the library you need to first include `OpenPhotoOAuth.php`, then instantiate an instance of the class and start making calls.
from openphoto import OpenPhoto
client = OpenPhoto(host, consumerKey, consumerSecret, token, tokenSecret)
resp = client.get('/photos/list.json')
resp = client.post('/photo/62/update.json', {'tags': 'tag1,tag2'})
----------------------------------------
<a name="cli"></a>
### Using from the command line
You'll then want to export your secrets to the environment.
We suggest putting them in a file and sourcing it prior to running `openphoto` commands.
<a href="#credentials">Click here for instructions on getting credentials</a>.
# env.sh
export consumerKey=your_consumer_key
export consumerSecret=your_consumer_secret
export token=your_access_token
export tokenSecret=your_access_token_secret
You'll need to source that file once for each terminal session.
source env.sh
These are the options you can pass to the shell program.
-h # display help text
-H hostname # default=localhost
-e endpoint # default=/photos/list.json
-X method # default=GET
-F params # i.e. -F 'title=my title' -F 'tags=mytag1,mytag1'
-p # pretty print the json
-v # verbose output
--encode # base 64 encode the photo
Now you can run commands to the OpenPhoto API from your shell!
openphoto -H current.openphoto.me -p -e /photo/62/view.json -F 'returnSizes=20x20'
{
"message" : "Photo 62",
"code" : 200,
"result" : {
"tags" : [
],
"id" : "62",
"appId" : "current.openphoto.me",
"pathBase" : "\/base\/201108\/1312956581-opmeqViHrD.jpg",
"dateUploadedMonth" : "08",
"dateTakenMonth" : "08",
"exifCameraMake" : "",
"dateTaken" : "1312956581",
"title" : "Tomorrowland Main Stage 2011",
"height" : "968",
"description" : "",
"creativeCommons" : "BY-NC",
"dateTakenYear" : "2011",
"dateUploadedDay" : "09",
"longitude" : "4",
"host" : "opmecurrent.s3.amazonaws.com",
"hash" : "0455675a8c42148238b81ed1d8db655c45ae055a",
"status" : "1",
"width" : "1296",
"dateTakenDay" : "09",
"permission" : "1",
"pathOriginal" : "\/original\/201108\/1312956581-opmeqViHrD.jpg",
"size" : "325",
"dateUploadedYear" : "2011",
"views" : "0",
"latitude" : "50.8333",
"dateUploaded" : "1312956583",
"exifCameraModel" : "",
"Name" : "62",
"path20x20" : "http:\/\/current.openphoto.me\/photo\/62\/create\/ceb90\/20x20.jpg"
}
}
<a name="credentials"></a>
#### Getting your credentials
You can get your credentals by clicking on the arrow next to your email address once you're logged into your site and then clicking on settings.
If you don't have any credentials then you can create one for yourself by going to `/v1/oauth/flow`.
Once completed go back to the settings page and you should see the credential you just created

44
openphoto/__init__.py Normal file
View file

@ -0,0 +1,44 @@
import oauth2 as oauth
import urlparse
import urllib
import httplib2
class OpenPhoto:
""" Client library for OpenPhoto """
def __init__(self, host, consumer_key='', consumer_secret='',
token='', token_secret=''):
self.host = host
self.consumer_key = consumer_key
self.consumer_secret = consumer_secret
self.token = token
self.token_secret = token_secret
def get(self, endpoint, params={}):
url = urlparse.urlunparse(('http', self.host, endpoint, '',
urllib.urlencode(params), ''))
if self.consumer_key:
consumer = oauth.Consumer(self.consumer_key, self.consumer_secret)
token = oauth.Token(self.token, self.token_secret)
client = oauth.Client(consumer, token)
else:
client = httplib2.Http()
headers, content = client.request(url, "GET")
return content
def post(self, endpoint, params={}):
url = urlparse.urlunparse(('http', self.host, endpoint, '', '', ''))
if self.consumer_key:
consumer = oauth.Consumer(self.consumer_key, self.consumer_secret)
token = oauth.Token(self.token, self.token_secret)
client = oauth.Client(consumer, token)
body = urllib.urlencode(params)
headers, content = client.request(url, "POST", body)
return content

55
scripts/openphoto Normal file
View file

@ -0,0 +1,55 @@
#!/usr/bin/env python
import os
import sys
import string
import urllib
from optparse import OptionParser
try:
import simplejson as json
except:
import json
from openphoto import OpenPhoto
if __name__ == "__main__":
consumer_key = os.getenv('consumerKey')
consumer_secret = os.getenv('consumerSecret')
token = os.getenv('token')
token_secret = os.getenv('tokenSecret')
parser = OptionParser()
parser.add_option('-H', '--host', action='store', type='string', dest='host',
help="Hostname of the OpenPhoto install", default="localhost")
parser.add_option('-X', action='store', type='choice', dest='method', choices=('GET', 'POST'),
help="Method to use (GET or POST)", default="GET")
parser.add_option('-F', action='append', type='string', dest='fields',
help="Fields")
parser.add_option('-e', action='store', type='string', dest='endpoint',
help="Endpoint to call")
parser.add_option('-p', action="store_true", dest="pretty", default=False)
parser.add_option('-v', action="store_true", dest="verbose", default=False)
parser.add_option('--encode', action="store_true", dest="encode", default=False)
options, args = parser.parse_args(sys.argv)
params = {}
if options.fields:
for field in options.fields:
(key, value) = string.split(field, '=')
params[key] = value
client = OpenPhoto(options.host, consumer_key, consumer_secret, token, token_secret)
if options.method == "GET":
result = client.get(options.endpoint)
else:
result = client.post(options.endpoint)
if options.verbose:
print "==========\nMethod: %s\nHost: %s\nEndpoint: %s\n==========\n\n" % (options.method, options.host, options.endpoint)
if options.pretty:
print json.dumps(json.loads(result), sort_keys=True, indent=4, separators=(',',':'))
else:
print result

View file

@ -0,0 +1,12 @@
from distutils.core import setup
setup(name='openphoto',
version='0.1',
description='Client library for the openphoto project',
author='James Walker',
author_email='walkah@walkah.net',
url='https://github.com/openphoto/openphoto-python',
requires=['oauth2'],
packages=['openphoto'],
scripts=['scripts/openphoto'],
)