Source

pcs / backend / suggest.py

Full commit
import logging
import webapp2

from google.appengine.ext import db
from google.appengine.api.datastore import Key

from google.appengine.api import users

from backend.models import Person, Script


def user_id():
    user = users.get_current_user()
    if not user:
        return None
    return user.user_id()

def is_user(person):
    return person.key() == user_id()


class SuggestHandler(webapp2.RequestHandler):
    
    def get(self):
        o = self.response.out

        query = self.request.get('q')
        parts = filter(bool, query.split("/")) or [""]
        
        name = parts[0]
        if not parts:
            logging.info("all names")
            self.person_list("")
        elif len(parts) == 1 and (query == "/" or not query.endswith("/")):
            logging.info("search person " + name)
            self.person_list(name)
        else:
            query = "SELECT * FROM Person WHERE name = :1"
            person = db.GqlQuery(query, name).get()
            if not person:
                self.error(404)
                o.write("unknown user: %s" % name)
                return

            path = "/" + person.name + "/" + "/".join(parts[1:])
            self.script_list(person, path)
        
    def person_list(self, prefix):
        o = self.response.out

        def write_person(p):
            o.write("/" + p.name + "/\n")

        query = "SELECT * FROM Person WHERE name >= :1 AND name < :2 LIMIT 15"
        persons = db.GqlQuery(query, prefix, prefix + u"\ufffd")
        map(write_person, persons)
    
    def script_list(self, person, path):
        o = self.response.out

        query = "SELECT * FROM Script WHERE path >= :1 AND path < :2"
        if not self.request.get('nolimit'):
            query += " LIMIT 30"

        scripts = db.GqlQuery(query, path, path + u"\ufffd")

        for s in scripts:
            o.write(s.path + "\n")


app = webapp2.WSGIApplication([("/suggest/", SuggestHandler)], debug=True)