self.response.out.write () - как правильно его использовать? - PullRequest
0 голосов
/ 09 ноября 2010

У меня есть класс, который не расширяется webapp.RequestHandler, и я не могу использовать self.response.out.write(), я получаю:

AttributeError: Экземпляр Fetcher не имеет атрибута «response»

Если я продлю webapp.RequestHandler (я думал, что это сработает), я получу:

AttributeError: у объекта 'Fetcher' нет атрибута 'response'

Как я могу правильно использовать этот метод? Иногда print тоже не работает; Я просто получаю пустой экран.

EDIT:

app.yaml:

application: fbapp-lotsofquotes
version: 1
runtime: python
api_version: 1

handlers:
- url: .*
  script: main.py

source (проблемная строка отмечена #<- HERE):

import random
import os

from google.appengine.api import users, memcache
from google.appengine.ext import webapp, db
from google.appengine.ext.webapp import util, template
from google.appengine.ext.webapp.util import run_wsgi_app

import facebook


class Quote(db.Model):
    author = db.StringProperty()
    string = db.StringProperty()
    categories = db.StringListProperty()
    #rating = db.RatingProperty()


class Fetcher(webapp.RequestHandler):
    '''
    Memcache keys: all_quotes
    '''

    def is_cached(self, key):
        self.fetched = memcache.get(key)
        if self.fetched:
            print 'ok'#return True
        else:
            print 'not ok'#return False


    #TODO: Use filters!
    def fetch_quotes(self):
        quotes = memcache.get('all_quotes')
        if not quotes:
            #Fetch and cache it, since it's not in the memcache.
            quotes = Quote.all()
            memcache.set('all_quotes',quotes,3600)
        return quotes

    def fetch_quote_by_id(self, id):
        self.response.out.write(id) #<---------- HERE


class MainHandler(webapp.RequestHandler):

    def get(self):
        quotes = Fetcher().fetch_quotes()
        template_data = {'quotes':quotes}
        template_path = 'many.html'
        self.response.out.write(template.render(template_path, template_data))


class ViewQuoteHandler(webapp.RequestHandler):

    def get(self, obj):
        self.response.out.write('viewing quote<br/>\n')
        if obj == 'all':
            quotes = Fetcher().fetch_quotes()
            self.render('view_many.html',quotes=quotes)
        else:
            quotes = Fetcher().fetch_quote_by_id(obj)
            '''for quote in quotes:
                print quote.author
                print quote.'''


    def render(self, type, **kwargs):
        if type == 'single':
            template_values = {'quote':kwargs['quote']}
            template_path = 'single_quote.html'
        elif type == 'many':
            print 'many'

        self.response.out.write(template.render(template_path, template_values))


'''
CREATORS
'''
class NewQuoteHandler(webapp.RequestHandler):

    def get(self, action):
        if action == 'compose':
            self.composer()
        elif action == 'do':
            print 'hi'

    def composer(self):
        template_path = 'quote_composer.html'
        template_values = ''
        self.response.out.write(template.render(template_path,template_values))

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

        if not author or not string:
            print 'REDIRECT'

        quote = Quote()
        quote.author = author
        quote.string = string
        quote.categories = []
        quote.put()


def main():
    application = webapp.WSGIApplication([('/', MainHandler),
                                          (r'/view/quote/(.*)',ViewQuoteHandler),
                                          (r'/new/quote/(.*)',NewQuoteHandler) ],
                                         debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()

1 Ответ

2 голосов
/ 09 ноября 2010

Вы не перенаправляете на Fetcher при инициализации WSGIApplication.Скорее вы создаете экземпляр вручную в других обработчиках.Таким образом, App Engine не будет инициализировать ваши свойства request и response.Вы можете сделать это вручную из обработчиков, на которые вы направляетесь, таких как MainHandler и ViewQuoteHandler.Например:

fetcher = Fetcher()
fetcher.initialize(self.request, self.response)
quotes = fetcher.fetch_quotes()

Обратите внимание, что сборщик действительно не должен быть RequestHandler.Это может быть отдельный класс или функция.Если у вас есть объекты запроса и ответа, вы можете передавать их по своему усмотрению.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...