def post(self, uid): try: body = json.loads(self.request.body) pid = body.get('pin_id') content = body.get('content') image = body.get('image') title = body.get('title') caption = body.get('caption') private = body.get('private', False) if pid is None and content is None: raise KeyError except (KeyError, ValueError, TypeError): self.send_error(httplib.BAD_REQUEST) return try: pin = yield Pin.fetch(guid=pid, content=content) except KeyError: if not content: self.send_error(httplib.NOT_FOUND) return pin = Pin(content, image, title) yield pin.save() userpin = UserPin(uid, pin, caption, private) yield userpin.save() self.write(self.application.userpin_representation(userpin)) self.set_status(httplib.CREATED)
def get(self, pid): try: pin = yield Pin.fetch(guid=pid) except KeyError: self.send_error(httplib.NOT_FOUND) return self.write(self.application.pin_representation(pin))
def fetch(cls, user_id, pin_id): cursor = yield cls.db_pool().execute("SELECT caption, private, modified FROM userpin WHERE user_id=%s AND pin_id=%s", (user_id, pin_id)) if cursor.rowcount != 1: cursor.close() raise KeyError row = cursor.fetchone() cursor.close() pin = yield Pin.fetch(guid=pin_id) userpin = cls(user_id, pin, row[0], row[1], row[2]) userpin._stored = True raise gen.Return(userpin)
def list_for_user(cls, user_id, limit=None): userpins = [] # TODO: replace this with a join, but to do that need to know internals of pin table... cursor = yield cls.db_pool().execute("SELECT caption, private, modified, pin_id FROM userpin WHERE user_id=%s", (user_id,)) cursor.arraysize = min(cursor.rowcount, limit or cursor.rowcount) rows = cursor.fetchmany() for row in rows: pid = row[3] try: pin = yield Pin.fetch(guid=pid) except KeyError: Log.warning('Userpin record references Pin record that isn\'t in DB, user={}, pin={}'.format(user_id, pid)) continue userpins.append(cls(user_id, pin, row[0], row[1], row[2])) raise gen.Return(userpins)