class collection(magic_object): five_hundred_px = five_hundred_px.FiveHundredPx(authentication.get_consumer_key(), authentication.get_consumer_secret()) def __init__(self, id, data=None, authorized_client=None): self.id = id self.authorized_client = authorized_client data = data or self.get_long_public_collection_data(id) self.add_colleciton_data(data) def add_colleciton_data(self, collection_data): self.photos = {} for photo in collection_data['photos']: photo_id = photo['id'] self.photos[photo_id] = fhp.models.photo.Photo(photo_id, data={"photo": photo}) del(collection_data['photos']) for key in collection_data: setattr(self, key, collection_data[key]) def get_long_public_collection_data(self, id): return collection.five_hundred_px.get_collection(id, self.authorized_client)
class photo(magic_object): five_hundred_px = five_hundred_px.FiveHundredPx( authentication.get_consumer_key(), authentication.get_consumer_secret()) def __init__(self, id, data=None): self.id = id data = data or photo.five_hundred_px.get_photo(id) photo_data = data["photo"] self.add_photo_data(photo_data) def add_photo_data(self, photo_data): for key in photo_data: if key == 'user': continue if key == 'comments': continue elif key == 'category': self.add_category_name(photo_data['category']) elif key == 'status': self.add_status_name(photo_data['status']) setattr(self, key, photo_data[key]) def add_category_name(self, category_number): categories = { 0: 'Uncategorized', 1: 'Celebrities', 2: 'Film', 3: 'Journalism', 4: 'Nude', 5: 'Black and White', 6: 'Still Life', 7: 'People', 8: 'Landscapes', 9: 'City and Architecture', 10: 'Abstract', 11: 'Animals', 12: 'Macro', 13: 'Travel', 14: 'Fashion', 15: 'Commercial', 16: 'Concert', 17: 'Sport', 18: 'Nature', 19: 'Performing Arts', 20: 'Family', 21: 'Street', 22: 'Underwater', 23: 'Food', 24: 'Fine Art', 25: 'Wedding', 26: 'Transportation', 27: 'Urban Exploration' } if category_number in categories: self.category_name = categories[category_number] else: self.category_name = "unknown" def _get_comments_(self): iter_source = partial(photo.five_hundred_px.get_photo_comments, self.id) def build_comment(photo_id, comment_data): return fhp.models.photo_comment.PhotoComment( comment_data["id"], photo_id, comment_data) iter_destination = partial(build_comment, self.id) self.comments = MagicGenerator(iter_source=iter_source, iter_destination=iter_destination) def add_status_name(self, status_number): status = { 8: 'status_uploaded', 0: 'status_created', 1: 'status_active', 7: 'status_inactive_user_photo', 9: 'status_deleted', 6: 'status_file_deleted' } if status_number in status: self.status_name = status[status_number] else: self.status_name = 'unknown' def __getattr__(self, name): if name == 'user': self._get_user_(self.user_id) return self.user if name == 'comments': self._get_comments_() return self.comments if name == 'tags': self._get_tags_() return self.tags else: raise AttributeError def _get_user_(self, user_id): self.user = fhp.models.user.User(self.user_id) def _get_tags_(self): data = photo.five_hundred_px.get_photo(self.id, tags=True) self.add_photo_data(data['photo']) def __dir__(self): results = [ 'aperture', 'camera', 'category', 'category_name', 'clear_cache', 'comments_count', 'created_at', 'description', 'empty_cache', 'favorites_count', 'five_hundred_px', 'focal_length', 'for_sale', 'for_sale_date', 'height', 'hi_res_uploaded', 'highest_rating', 'highest_rating_date', 'id', 'image_url', 'images', 'iso', 'latitude', 'lens', 'location', 'longitude', 'name', 'nsfw', 'privacy', 'rating', 'sales_count', 'shutter_speed', 'status', 'status_name', 'store_download', 'store_print', 'taken_at', 'times_viewed', 'user_id', 'user', 'votes_count', 'width', 'tags' ] return results
parser = argparse.ArgumentParser() parser.add_argument('username') parser.add_argument('-s', '--friends-stats', dest='stat', action='store_true', help='show following stats') parser.add_argument('-p', '--pxmagic path', dest='pxpath', default=os.path.join( os.path.abspath(os.path.dirname(sys.argv[0])), 'PxMagic'), help='PxMagic package path, default to %(default)s') args = parser.parse_args() sys.path.append(args.pxpath) import fhp.api.five_hundred_px as _fh import fhp.helpers.authentication as _a from fhp.models.user import User from fhp.models.photo import Photo _a.VERIFY_URL = "http://verify-oauth.herokuapp.com/" _f = _fh.FiveHundredPx(_a.get_consumer_key(), _a.get_consumer_secret(), _a.get_verify_url()) username = args.username.decode('utf-8') me = User(username=username) #, authorize=True) if args.stat: show_stat(me) else: friends_update(me)
from fhp import api FiveHundredPx = src.five_hundred_px.FiveHundredPx except ImportError: from fhp.api.five_hundred_px import * from fhp.helpers.authentication import get_consumer_key,get_consumer_secret pil_exists = None try: from PIL import Image pil_exists = True except ImportError: print "no PIL found... try 'pip install PIL' " CONSUMER_KEY = get_consumer_key() CONSUMER_SECRET = get_consumer_secret() def main(): api = FiveHundredPx(CONSUMER_KEY, CONSUMER_SECRET) generator = api.get_photos(feature='popular',limit=3) for p in generator: thumbnail_url = p['image_url'] fhpx_url = 'http://500px.com/photo/%d' % p['id'] fileio = urllib.urlopen(thumbnail_url) im = StringIO(fileio.read()) # if you have PIL you can play with the image if pil_exists: img = Image.open(im) img.show() try: print '(%s,%s)' % (thumbnail_url,fhpx_url)
class user(magic_object): five_hundred_px = five_hundred_px.FiveHundredPx( authentication.get_consumer_key(), authentication.get_consumer_secret(), authentication.get_verify_url()) def __init__(self, id=None, username=None, email=None, data=None, authorize=False): if email: raise NotImplementedError if not bool(id) != bool(username): raise TypeError, "user requires exactly 1 of id, username" self.authorized_client = None if authorize: self.authorize() data = data or self.get_long_user_data(id, username) user_data = data["user"] self.add_user_data(user_data) self._setup_dir_() def add_user_data(self, user_data): for key in user_data: setattr(self, key, user_data[key]) def authorize(self): """ Intended for client python applications (for example, an Ubuntu app). See self.authorize_step_one() to create an authorized server. """ self.authorized_client = user.five_hundred_px.get_authorized_client() def initialize_authorization(self): self._oauth_token, self._oauth_secret = user.five_hundred_px.get_oauth_token_and_secret( ) def complete_authorization(self, oauth_verifier, oauth_url_fn=None): client = user.five_hundred_px.get_authorized_client( oauth_url_fn, self._oauth_token, self._oauth_secret, oauth_verifier) self.authorized_client = client # since we are authorized, the id will basically be ignored # this is a hack for now data = self.get_long_user_data(id=self.id) user_data = data["user"] self.add_user_data(user_data) def __getattr__(self, name): if name == 'friends': self._get_friends_() return self.friends elif name == 'followers': self._get_followers_() return self.followers elif name == 'collections': self._get_collections_() return self.collections elif name == 'blog_posts': self._get_blog_posts_() return self.blog_posts elif name == 'photos': self._get_photos_() return self.photos elif name == 'favorites': self._get_favorites_() return self.favorites elif name in dir(self): data = self.get_long_user_data(self.id, self.authorized_client) new_user_data = data["user"] self.add_user_data(new_user_data) return getattr(self, name) else: raise AttributeError, name def get_long_user_data(self, id=None, username=None): if id: result = user.five_hundred_px.get_user_by_id( id, self.authorized_client) elif username: result = user.five_hundred_px.get_user_by_username( username, self.authorized_client) else: raise NotImplementedError return result def find_friend(self, **kwargs): for friend in self.friends: is_match = True for kwarg in kwargs: if not getattr(friend, kwarg) == kwargs[kwarg]: is_match = False if is_match: return friend def find_follower(self, **kwargs): for follower in self.followers: is_match = True for kwarg in kwargs: if not getattr(follower, kwarg) == kwargs[kwarg]: is_match = False if is_match: return follower def find_photo(self, **kwargs): return self.find_thing("photos", **kwargs) def add_photo(self, **kwargs): """ The photo upload process is the following: 1. Send the data about the photo 2. Receive the photo_id and the upload key. 3A. If a server, send the upload_key to your user and have them do a multi form upload with the upload key OR 3B. If a local app, use the upload_key to do the multi-form upload. Since both uses are acceptable, both the upload key and the new photo object are returned, even if, in most cases only the photo_id (not the full photo object) is needed until the step 3A is complete. """ data = user.five_hundred_px.create_new_photo_upload_key( self.authorized_client, **kwargs) self.photos.max_length += 1 photo_id = data["photo"]["id"] photo = fhp.models.photo.Photo(photo_id, data=data) upload_key = data["upload_key"] return upload_key, photo def upload_photo(self, upload_key, photo, photo_file): """ If you are writing a server side app, you probably *don't* need this method. This method is geared towards people making, say, Ubuntu apps. Of course if you're server is part of skynet and skynet takes picturs and wants to be part of the worlds best photography site, then this is acceptable to both 500px Inc, and me personally. Just don't steal other peoples photos and upload them as your own. """ if type(file) == str: import warnings warnings.warn("treating string as if it were a file, not filename") photo_id = self._get_photo_id_(photo) return user.five_hundred_px.upload_photo(upload_key, photo_id, photo_file, self.authorized_client) def follow(self, user): """ Warning: if you pass in a user_id instead of a user object then any user object you are currently using will not be informed of the additional follower. This may be especially tricky if the followed user is and authenticated user (which takes up it's own object) """ if hasattr(user, "id"): user_id = user.id else: user_id = user user = False result = user.five_hundred_px.user_follows_user( user_id, self.authorized_client) if result: self.friends.max_length += 1 if result and user: user.followers.max_length += 1 return result def unfollow(self, user): """ Warning: if you pass in a user_id instead of a user object then any user object you are currently using will not be informed that it has lost a follower. This may be especially tricky if the followed user is an authenticated user (which takes up it's own object) """ if hasattr(user, "id"): user_id = user.id else: user_id = user user = False result = user.five_hundred_px.user_unfollows_user( user_id, self.authorized_client) # This is necessary since we do not know where in the result # set the user was. if result: self.friends.reset_cache() if result and user: user.followers.reset_cache() return result def _get_friends_(self): iter_source = partial(user.five_hundred_px.get_user_friends, self.id) def build_user(user_data): data = dict(user=user_data) user_id = data["user"]['id'] return User(user_id, data=data) self.friends = MagicGenerator(iter_source=iter_source, iter_destination=build_user) def _get_followers_(self): iter_source = partial(user.five_hundred_px.get_user_followers, self.id) def build_user(user_data): data = dict(user=user_data) user_id = data["user"]['id'] return User(user_id, data=data) self.followers = MagicGenerator(iter_source=iter_source, iter_destination=build_user) def _get_photos_(self): kwargs = dict(feature='user', user_id=self.id, user=True) iter_source = partial(user.five_hundred_px.get_photos, **kwargs) def build_photo(photo_data): data = dict(photo=photo_data) photo_id = data["photo"]["id"] return fhp.models.photo.Photo(photo_id, data=data) self.photos = MagicGenerator(iter_source=iter_source, iter_destination=build_photo) def _get_favorites_(self): kwargs = dict(feature='user_favorites', user_id=self.id, user=True) iter_source = partial(user.five_hundred_px.get_photos, **kwargs) def build_photo(photo_data): data = dict(photo=photo_data) photo_id = data["photo"]["id"] return fhp.models.photo.Photo(photo_id, data=data) self.favorites = MagicGenerator(iter_source=iter_source, iter_destination=build_photo) def favorite(self, photo): """ Returns True upon successful favoriting """ photo_id = self._get_photo_id_(photo) return user.five_hundred_px.user_favorites_photo( photo_id, self.authorized_client) def unfavorite(self, photo): photo_id = self._get_photo_id_(photo) return user.five_hundred_px.user_unfavorites_photo( photo_id, self.authorized_client) def _get_photo_id_(self, photo): return photo.id if hasattr(photo, 'id') else photo def like(self, photo): photo_id = self._get_photo_id_(photo) return user.five_hundred_px.user_likes_photo(photo_id, self.authorized_client) def dislike(self, photo): """ Since there is no way in the API to find out if a user is able to dislike a photo I've decided not to implement it for now. Remember: A dislike is NOT an unlike. It is a seperate action that only qualified users can take. The vast majority of 500px users are not able to dislike a photo. """ raise NotImplementedError def comment_on_photo(self, photo, comment_body): photo_id = self._get_photo_id_(photo) response = user.five_hundred_px.user_comments_on_photo( photo_id, comment_body, self.authorized_client) """ To stop the photo from incorrectly thinking that it has fully cached the comments on the photo we increase the max length by 1. of course this will not stop the requirment to nuke the caches from time to time anyways. """ fhp.models.photo.Photo(photo_id).comments.max_length += 1 return response def comment_on_blog_post(self, blog_post, comment_body): blog_post_id = blog_post.id if hasattr(blog_post, 'id') else blog_post resp = user.five_hundred_px.user_comments_on_blog_post( blog_post_id, comment_body, self.authorized_client) fhp.models.blog_post.BlogPost(blog_post_id).comments.max_length += 1 return resp @magic_cache def _get_collections_(self): self.collections = {} kwargs = dict(authorized_client=self.authorized_client) collections = user.five_hundred_px.get_user_collections(**kwargs) for collection in collections: col_id = collection["id"] self.collections[col_id] = fhp.models.collection.Collection( col_id, collection) @magic_cache def _get_blog_posts_(self): self.blog_posts = {} for blog_post in user.five_hundred_px.get_user_blog_posts(self.id): blog_post_id = blog_post['id'] data = {"blog_post": blog_post} self.blog_posts[blog_post_id] = fhp.models.blog_post.BlogPost( blog_post_id, data=data, user=self) def _setup_dir_(self): base_dir_list = [ 'domain', 'locale', 'store_on', 'sex', 'id', 'city', 'userpic_url', 'photos_count', 'friends_count', 'contacts', 'followers_count', 'equipment', 'state', 'upgrade_status', 'show_nude', 'username', 'firstname', 'lastname', 'registration_date', 'birthday', 'in_favorites_count', 'about', 'country', 'fotomoto_on', 'fullname', 'affection', 'blog_posts' ] self.dir_list = list(set(base_dir_list)) def __dir__(self): return self.dir_list
class blog_post(magic_object): five_hundred_px = five_hundred_px.FiveHundredPx( authentication.get_consumer_key(), authentication.get_consumer_secret()) def __init__(self, id, data=None, authorized_client=None, user=None): self.id = id self.authorized_client = authorized_client data = data or self.get_long_public_blog_post_data(id) self.add_blog_post_data(data['blog_post'], user=user) def add_blog_post_data(self, blog_post_data, user=None): if user: self.user = user del (blog_post_data['user']) elif 'user' in blog_post_data: self.user_id = blog_post_data['user']['id'] del (blog_post_data['user']) if 'photos' in blog_post_data: self._make_photos_(blog_post_data['photos']) del (blog_post_data['photos']) for key in blog_post_data: setattr(self, key, blog_post_data[key]) def get_long_public_blog_post_data(self, blog_post_id): data = blog_post.five_hundred_px.get_blog_post(blog_post_id) return data def __getattr__(self, name): if name == 'user': return self._get_user_(self.user_id) elif name == 'photos': data = self.get_long_public_blog_post_data(self.id) photo_data = data.get('photos', {}) self._make_photos_(photo_data) return self.photos elif name == 'comments': self._get_comments_() return self.comments else: raise AttributeError @magic_cache def _get_user_(self, user_id): return fhp.models.user.User(self.user_id) def _get_comments_(self): iter_source = partial(blog_post.five_hundred_px.get_blog_post_comments, self.id) def build_comment(blog_post_id, comment_data): return fhp.models.blog_post_comment.BlogPostComment( comment_data["id"], blog_post_id, comment_data) iter_destination = partial(build_comment, self.id) self.comments = MagicGenerator(iter_source=iter_source, iter_destination=iter_destination) def _make_photos_(self, photo_data): self.photos = {} for photo in photo_data: photo_id = photo['id'] self.photos[photo_id] = fhp.models.photo.Photo(photo_id)
import fhp.api.five_hundred_px as f import fhp.helpers.authentication as authentication import urllib import sys from fhp.models.photo import Photo from nested_lookup import nested_lookup from pprint import pprint key = authentication.get_consumer_key() secret = authentication.get_consumer_secret() client = f.FiveHundredPx(key, secret) results = client.get_photos(feature='popular') def main(): image_id = 0 name_id = 0 photos_retrieved = 0 photos_needed = 10 failed = 0 for photo in results: image_id = nested_lookup('id', photo)[0] print (nested_lookup('id', photo)[0]) try: photo = Photo(image_id) failed = 0 except: print "Something didn't work, boss." failed = 1
import fhp.api.five_hundred_px as fh import fhp.helpers.authentication as a f = fh.FiveHundredPx(a.get_consumer_key(), a.get_consumer_secret(), a.get_verify_url()) for result in f.photo_search(tag="freckles", sort="rating"): print result break
from functools import partial from fhp.api import five_hundred_px from fhp.helpers import authentication import fhp.models.photo from fhp.magic.magic_cache import magic_cache, magic_fn_cache from fhp.magic.magic_generator import MagicGenerator five_hundred_px = five_hundred_px.FiveHundredPx( authentication.get_consumer_key(), authentication.get_consumer_secret()) @magic_fn_cache def PhotoSearch(term=None, tag=None, tags=None): if not bool(term) != bool(tag): error = "PhotoSearch requires exactly on of term and tag" error += "\n perhaps you meant to use a keyword argument" raise TypeError, error iter_source = partial(five_hundred_px.photo_search, term=term, tag=tag, tags=tags) def build_photo(photo_data): photo_id = photo_data["id"] data = dict(photo=photo_data) return fhp.models.photo.Photo(photo_id, data=data) iter_destination = build_photo
import fhp.api.five_hundred_px as f import fhp.helpers.authentication as authentication from pprint import pprint key = authentication.get_consumer_key() secret = authentication.get_consumer_secret() client = f.FiveHundredPx(key, secret) results = client.get_photos(feature='popular') i = 0 PHOTOS_NEEDED = 2 for photo in results: pprint(photo) i += 1 if i == PHOTOS_NEEDED: break
from fhp import api FiveHundredPx = src.five_hundred_px.FiveHundredPx except ImportError: from fhp.api.five_hundred_px import * from fhp.helpers.authentication import get_consumer_key, get_consumer_secret pil_exists = None try: from PIL import Image pil_exists = True except ImportError: print "no PIL found... try 'pip install PIL' " CONSUMER_KEY = get_consumer_key() CONSUMER_SECRET = get_consumer_secret() def main(): api = FiveHundredPx(CONSUMER_KEY, CONSUMER_SECRET) generator = api.get_photos(feature='popular', limit=3) for p in generator: thumbnail_url = p['image_url'] fhpx_url = 'http://500px.com/photo/%d' % p['id'] fileio = urllib.urlopen(thumbnail_url) im = StringIO(fileio.read()) # if you have PIL you can play with the image if pil_exists: img = Image.open(im) img.show() try: