开发者

Is this the correct way of doing/handling url rewrite in App Engine/ Python?

I'm not sure if this is effective or not. It works, but sometimes i feel...weird about it. Can you please tell me if this is a good way or not?

I threw the code on pastebin, because i think it's a bit too much to put here: http://pastebin.com/662TiQLq

EDIT I edited the title to make it more objective.开发者_JAVA技巧


I'm just guessing that the questioner is asking about creating a dictionary of functions in the __ init __ function of the handlers, and then using this dict in the "get" function to look up specific functions. If this is the question, then IMHO a clearer approach would be to set up separate handlers for each different function. For example

class QuotesView(webapp.RequestHandler):
    """Super class for quotes that can accommodate common functionality"""
    pass

class QuotesViewSingle(QuotesView):
    def get(self):
        ...

class QuotesViewRandom(QuotesView):
    def get(self):
        ...

class QuotesViewAll(QuotesView):
    def get(self):
        ...

def main():
    application = webapp.WSGIApplication([('/quote/new',NewQuote),
                                          (r'/quotes/single',QuotesViewSingle),
                                          (r'/quotes/all',QuotesViewAll),
                                          (r'/quotes/random',QuotesViewRandom),
                                          ...
                                          ('/', MainHandler)],
                                         debug=True)

BTW. A lot of people use the regex in the WSGIApplication calls to parse out arguments for the get functions. There's nothing particularly wrong with it. I'm not a big fan of that feature, and prefer to parse the arguments in the get functions. But that's just me.

For completeness here's the original code:

class Quote(db.Model):
    author = db.StringProperty()
    string = db.StringProperty()


class MainHandler(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()


        quotes = Quote.all()
        path = os.path.join(os.path.dirname(__file__),'quotery.html')
        template_values = {'quotes':quotes,'user':user,'login_url':users.create_login_url('/')}
        self.response.out.write(template.render(path, template_values))


class QuoteHandler(webapp.RequestHandler):

    def __init__(self):
        self.actions = {'fetch':self.fetch, 'random':self.fetch_random}

        #Memcache the number of quotes in the datastore, to minimize datastore calls
        self.quote_count = memcache.get('quote_count')
        if not self.quote_count:
            self.quote_count = self.cache_quote_count()

    def cache_quote_count(self):
        count = Quote.all().count()
        memcache.add(key='quote_count', value=count, time=3600)
        return count


    def get(self, key):
        if key in self.actions:
            action = self.actions[key]
            action()




    def fetch(self):
        for quote in Quote.all():
            print 'Quote!'
            print 'Author: ',quote.author
            print 'String: ',quote.string
            print


    def fetch_random(self):
        max_offset = self.quote_count-1
        random_offset = random.randint(0,max_offset)
        '''self.response.out.write(max_offset)
        self.response.out.write('\n<br/>')
        self.response.out.write(random_offset)'''
        try:
            query = db.GqlQuery("SELECT * FROM Quote")
            quotes = query.fetch(1,random_offset)
            return quotes
            '''for quote in quotes:
                self.response.out.write(quote.author)
                self.response.out.write('\n')
                self.response.out.write(quote.string)'''
        except BaseException:
            raise


class NewQuote(webapp.RequestHandler):

    def post(self):
        author = self.request.get('quote_author')
        string = self.request.get('quote_string')

        if not author or not string:
            return False        
        quote = Quote()
        quote.author = author
        quote.string = string
        quote.put()
        QuoteHandler().cache_quote_count()
        self.redirect("/")
        #return True


class QuotesView(webapp.RequestHandler):

    def __init__(self):
        self.actions = {'all':self.view_all,'random':self.view_random,'get':self.view_single}

    def get(self, key):
        if not key or key not in self.actions:
            self.view_all()
        if key in self.actions:
            action = self.actions[key]
            action()

    def view_all(self):
        print 'view all'

    def view_random(self):
        quotes = QuoteHandler().fetch_random()
        template_data = {}

        for quote in quotes:
            template_data['quote'] = quote

        template_path = os.path.join(os.path.dirname(__file__),'base_view.html')
        self.response.out.write(template.render(template_path, template_data))


    def view_single(self):
        print 'view single'


def main():
    application = webapp.WSGIApplication([('/quote/new',NewQuote),(r'/quotes/(.*)',QuotesView),(r'/quote/(.*)',QuoteHandler),('/', MainHandler)],
                                         debug=True)
    util.run_wsgi_app(application)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜