class Collaborator(GitHubRemoteObject): """A GitHub repo collaborator. Not sure if this could just as well be considered a User but it seems to have only a subset of the fields. `GET /repos/:user/:repo/collaborators/:user` { "login": "******", "id": 1, "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "somehexcode", "url": "https://api.github.com/users/octocat" } """ id = fields.Field() avatar_url = fields.Field() gravatar_id = fields.Field() url = fields.Field() login = fields.Field() def __unicode__(self): return u"<Collaborator %s>" % self.id
class Comment(GitHubRemoteObject): """A GitHub issue comment. `GET /repos/:user/:repo/issues/comments/:id` { "url": "https://api.github.com/repos/octocat/Hello-World/issues/comments/1", "body": "Me too", "user": { "login": "******", "id": 1, "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "somehexcode", "url": "https://api.github.com/users/octocat" }, "created_at": "2011-04-14T16:00:49Z", "updated_at": "2011-04-14T16:00:49Z" } """ id = fields.Field() url = fields.Field() body = fields.Field() user = fields.Object(User) created_at = fields.Field() updated_at = fields.Field() def __unicode__(self): return u"<Comment %s>" % self.id
class Committee(OpenStateObject): id = fields.Field() state = fields.Field() chamber = fields.Field() committee = fields.Field() subcommittee = fields.Field() members = fields.List(fields.Object(CommitteeMember)) sources = fields.List(fields.Object(Source)) @classmethod def get(cls, id): """ Get a committee. :param id: the committee's Open State ID (e.g. CAC000005) """ func = 'committees/%s' % id return super(Committee, cls).get(func) @classmethod def search(cls, **kwargs): """ Search comittees. Use keyword argmunents to filter by committee fields. For example, ``openstates.Committee.search(state='ca')``. """ return ListOf(cls).get('committees', kwargs).entries
class Image(Bombject): tiny_url = fields.Field() small_url = fields.Field() thumb_url = fields.Field() screen_url = fields.Field() super_url = fields.Field()
class Action(OpenStateObject): date = OpenStateDatetime() actor = fields.Field() action = fields.Field() type = fields.Field() def __str__(self): return '%s: %s' % (self.actor, self.action)
class Term(OpenStateObject): start_year = fields.Field() end_year = fields.Field() name = fields.Field() sessions = fields.List(fields.Field()) def __str__(self): return self.name
class Document(CouchObject): id = fields.Field(api_name='_id') revision = fields.Field(api_name='_rev') def update_from_created_dict(self, data): self.id = data['id'] self.revision = data['rev']
class Sponsor(OpenStateObject): leg_id = fields.Field() name = fields.Field() type = fields.Field() chamber = fields.Field() def __str__(self): return self.name
class Change(RemoteObject): field_name = fields.Field() added = fields.Field() removed = fields.Field() def __repr__(self): return '<Change "%s": "%s" -> "%s">' % (self.field_name, self.removed, self.added)
class Status(RemoteObject): """A Twitter update. Statuses can be fetched from ``http://twitter.com/statuses/show/<id>.json``. """ created_at = fields.Field() id = fields.Field() text = fields.Field() source = fields.Field() truncated = fields.Field() in_reply_to_status_id = fields.Field() in_reply_to_user_id = fields.Field() in_reply_to_screen_name = fields.Field() favorited = fields.Field() user = fields.Object(User) @classmethod def get_status(cls, id, http=None): return cls.get(urljoin(Twitter.endpoint, "/statuses/show/%d.json" % int(id)), http=http) def __unicode__(self): return u"%s: %s" % (self.user.screen_name, self.text)
class ViewResult(CouchObject, ListObject): total_rows = fields.Field() offset = fields.Field() entries = fields.List(fields.Object(ListItem), api_name='rows') def filter(self, **kwargs): for k, v in kwargs.iteritems(): if isinstance(v, list) or isinstance(v, dict) or isinstance( v, bool): kwargs[k] = json.dumps(v) return super(ViewResult, self).filter(**kwargs)
class User(RemoteObject): """A Twitter account. A User can be retrieved from ``http://twitter.com/users/show.json`` with the appropriate ``id``, ``user_id``, or ``screen_name`` parameter. """ id = fields.Field() name = fields.Field() screen_name = fields.Field() location = fields.Field() description = fields.Field() profile_image_url = fields.Field() protected = fields.Field() followers_count = fields.Field() status = fields.Object('Status') @classmethod def get_user(cls, http=None, **kwargs): url = '/users/show' if 'id' in kwargs: url += '/%s.json' % quote_plus(kwargs['id']) else: url += '.json' query = urlencode( filter(lambda x: x in ('screen_name', 'user_id'), kwargs)) url = urlunsplit((None, None, url, query, None)) return cls.get(urljoin(Twitter.endpoint, url), http=http)
class User(RemoteObject): name = fields.Field() real_name = fields.Field() ref = fields.Field() def __repr__(self): return '<User "%s">' % self.real_name def __str__(self): return self.real_name or self.name def __hash__(self): if not self or not self.name: return 0 return self.name.__hash__()
class Comment(RemoteObject): id = fields.Field() creator = fields.Object('User') creation_time = Datetime(DATETIME_FORMAT_WITH_SECONDS) text = fields.Field() is_private = StringBoolean() def __repr__(self): return '<Comment by %s on %s>' % ( self.creator, self.creation_time.strftime(DATETIME_FORMAT)) def __str__(self): return self.text def __hash__(self): return self.id
class Flag(RemoteObject): id = fields.Field() name = fields.Field() setter = fields.Object('User') status = fields.Field() requestee = fields.Object('User') type_id = fields.Field() def __repr__(self): return '<Flag "%s">' % self.name def __str__(self): return self.name def __hash__(self): return self.id
class PageObject(SequenceProxy, PromiseObject): """A `RemoteObject` representing a set of other `RemoteObject` instances. Endpoints in APIs are often not objects themselves but lists of objects. As with regular `PromiseObject` instances, `PageObject` instances can be filtered by parameters that are then passed to your target API, such as a list of recent objects or a search. Filtering a `PageObject` instance by a parameter returns a new copy of that `PageObject` instance that includes the new parameter. The contents of regular `PageObject` instances will be decoded as with `Field` fields; that is, not decoded at all. To customize decoding of API contents, subclass `PageObject` and redefine the ``entries`` member with a `Field` instance that decodes the list content as necessary. As many API endpoints are sets of objects, to create a `PageObject` subclass for those endpoints, you can directly call its metaclass, `PageOf`, with the class reference you would use to construct an `Object` field. That is, these declarations are equivalent: >>> PageOfEntry = PageOf(Entry) >>> class PageOfEntry(PageObject): ... entries = fields.List(fields.Object(Entry)) For an ``Entry`` list you then fetch with the `PageOfEntry` class's `get()` method, all the entities in the list resource's `entries` member will be decoded into ``Entry`` instances. """ __metaclass__ = PageOf entries = fields.List(fields.Field()) def __getitem__(self, key): """Translates slice notation on a `ListObject` instance into ``limit`` and ``offset`` filter parameters.""" if isinstance(key, slice): args = dict() if key.start is not None: args['offset'] = key.start if key.stop is not None: args['limit'] = key.stop - key.start elif key.stop is not None: args['limit'] = key.stop return self.filter(**args) try: getitem = super(PageObject, self).__getitem__ except AttributeError: raise TypeError("'%s' object is unsubscriptable except by slices" % (type(self).__name__, )) else: return getitem(key)
class Label(GitHubRemoteObject): """A GitHub label. `GET /repos/:user/:repo/labels/:name` { "url": "https://api.github.com/repos/octocat/Hello-World/labels/bug", "name": "bug", "color": "f29513" } """ url = fields.Field() name = fields.Field() color = fields.Field() def __unicode__(self): return u"<Label %s>" % self.name
class Title(Flixject): api_url = fields.Field() title = fields.Field() link = fields.Field() thumb = fields.Field() #synopsis = fields.Link(...) decoder_ring = { 'title': lambda x: x.find('title').get('regular'), 'link': lambda x: [j for j in x.findall('link') if j.get('rel') == 'alternate'][0].get('href'), 'thumb': lambda x: x.find('box_art').get('large'), 'api_url': lambda x: x.find('id'), }
class Catalog(Flixject): results = fields.List(fields.Field()) total = fields.Field() offset = fields.Field() limit = fields.Field() decoder_ring = { 'results': lambda x: [ Title().update_from_tree(tree) for tree in x.findall('catalog_title') ], 'total': lambda x: int(x.find('number_of_results').text), 'offset': lambda x: int(x.find('start_index').text), 'limit': lambda x: int(x.find('results_per_page').text), }
class Role(OpenStateObject): state = fields.Field() type = fields.Field() term = fields.Field() chamber = fields.Field() district = fields.Field() committee = fields.Field() subcommittee = fields.Field() start_date = OpenStateDatetime() end_date = OpenStateDatetime() party = fields.Field() def __str__(self): return '%s %s %s district %s' % (self.state, self.chamber, self.term, self.district)
class Keyword(RemoteObject): name = fields.Field() def __repr__(self): return '<Keyword "%s">' % self.name def __str__(self): return self.name def __hash__(self): if not self or not self.name: return 0 return self.name.__hash__()
class Vote(OpenStateObject): date = OpenStateDatetime() chamber = fields.Field() committee = fields.Field() motion = fields.Field() yes_count = fields.Field() no_count = fields.Field() other_count = fields.Field() passed = fields.Field() type = fields.Field() yes_votes = fields.List(fields.Object(SpecificVote)) no_votes = fields.List(fields.Object(SpecificVote)) other_votes = fields.List(fields.Object(SpecificVote)) def __str__(self): return "Vote on '%s'" % self.motion
class Milestone(GitHubRemoteObject): """A GitHub milestone. `GET /repos/:user/:repo/milestones/:number` { "url": "https://api.github.com/repos/octocat/Hello-World/milestones/1", "number": 1, "state": "open", "title": "v1.0", "description": "", "creator": { "login": "******", "id": 1, "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "somehexcode", "url": "https://api.github.com/users/octocat" }, "open_issues": 4, "closed_issues": 8, "created_at": "2011-04-10T20:09:31Z", "due_on": null } """ url = fields.Field() number = fields.Field() state = fields.Field() title = fields.Field() description = fields.Field() creator = fields.Object(User) open_issues = fields.Field() closed_issues = fields.Field() created_at = fields.Field() due_on = fields.Field() def __unicode__(self): return u"<Milestone %s>" % self.title
class State(OpenStateObject): name = fields.Field() abbreviation = fields.Field() legislature_name = fields.Field() upper_chamber_name = fields.Field() lower_chamber_name = fields.Field() upper_chamber_term = fields.Field() lower_chamber_term = fields.Field() upper_chamber_title = fields.Field() lower_chamber_title = fields.Field() terms = fields.List(fields.Object(Term)) @classmethod def get(cls, abbrev): """ Get metadata about a state. :param abbrev: the state's two-letter abbreviation. """ return super(State, cls).get('metadata/%s' % abbrev) def __str__(self): return self.name
class GameResult(Bombject): status_code = fields.Field() error = fields.Field() total = fields.Field(api_name='number_of_total_results') count = fields.Field(api_name='number_of_page_results') limit = fields.Field() offset = fields.Field() results = fields.List(fields.Object(Game)) def update_from_dict(self, data): if not isinstance(data['results'], list): data = dict(data) data['results'] = [data['results']] super(GameResult, self).update_from_dict(data)
class Event(OpenStateObject): id = fields.Field() state = fields.Field() description = fields.Field() when = OpenStateDatetime() end = OpenStateDatetime() location = fields.Field() type = fields.Field() session = fields.Field() participants = fields.List(fields.Object(EventParticipant)) sources = fields.List(fields.Object(Source)) @classmethod def search(cls, **kwargs): return ListOf(cls).get('events', kwargs).entries
class Bill(OpenStateObject): title = fields.Field() state = fields.Field() session = fields.Field() chamber = fields.Field() bill_id = fields.Field() created_at = OpenStateDatetime() updated_at = OpenStateDatetime() alternate_titles = fields.List(fields.Field()) actions = fields.List(fields.Object(Action)) sponsors = fields.List(fields.Object(Sponsor)) votes = fields.List(fields.Object(Vote)) versions = fields.List(fields.Object(Version)) documents = fields.List(fields.Object(Document)) sources = fields.List(fields.Object(Source)) @classmethod def get(cls, state, session, chamber, bill_id): """ Get a specific bill. :param state: the two-letter abbreviation of the originating state :param session: the session identifier for the bill (see the state's metadata for legal values) :param chamber: which legislative chamber the bill originated in ('upper' or 'lower') :param bill_id: the bill's ID as assigned by the state """ func = "bills/%s/%s/%s/%s" % (state, session, chamber, bill_id) return super(Bill, cls).get(func) @classmethod def search(cls, query=None, **kwargs): """ Search bills. :param query: a query string which will be used to search bill titles Any additional keyword arguments will be used to further filter the results. """ if query: kwargs['q'] = query func = 'bills' return ListOf(cls).get(func, kwargs).entries def __str__(self): return '%s: %s' % (self.bill_id, self.title)
class DirectMessage(RemoteObject): """A Twitter direct message. The authenticated user's most recent direct messages are at ``http://twitter.com/direct_messages.json``. """ id = fields.Field() sender_id = fields.Field() text = fields.Field() recipient_id = fields.Field() created_at = fields.Field() sender_screen_name = fields.Field() recipient_screen_name = fields.Field() sender = fields.Object(User) recipient = fields.Object(User) def __unicode__(self): return u"%s: %s" % (self.sender.screen_name, self.text)
class Event(GitHubRemoteObject): """A GitHub event. `GET /events` { "type": "Event", "public": true, "payload": { }, "repo": { "id": 3, "name": "octocat/Hello-World", "url": "https://api.github.com/repos/octocat/Hello-World" }, "actor": { "login": "******", "id": 1, "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "somehexcode", "url": "https://api.github.com/users/octocat" }, "org": { "login": "******", "id": 1, "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "somehexcode", "url": "https://api.github.com/users/octocat" }, "created_at": "2011-09-06T17:26:27Z" } """ id = fields.Field() type = fields.Field() public = fields.Field() payload = fields.Field() repo = fields.Field() actor = fields.Object(User) org = fields.Object(User) created_at = fields.Field() def __unicode__(self): return u"<Event %s>" % self.id
class Game(Bombject): id = fields.Field() name = fields.Field() api_detail_url = fields.Field() site_detail_url = fields.Field() summary = fields.Field(api_name='deck') description = fields.Field() image = fields.Object(Image) published = fields.Datetime(dateformat='%Y-%m-%d %H:%M:%S', api_name='date_added') updated = fields.Datetime(dateformat='%Y-%m-%d %H:%M:%S', api_name='date_last_updated') characters = fields.Field() concepts = fields.Field() developers = fields.Field() platforms = fields.Field() publishers = fields.Field() @classmethod def get(cls, url, **kwargs): res = GameResult.get(url) res = res.filter() return res.results[0]