def write_error(self, status_code, **kwargs): import traceback if gae_utils.Debug(): exc_info = kwargs["exc_info"] trace_info = ''.join([ "%s<br/>" % line for line in traceback.format_exception(*exc_info) ]) request_info = ''.join([ "<strong>%s</strong>: %s<br/>" % (k, self.request.__dict__[k]) for k in self.request.__dict__.keys() ]) error = exc_info[1] self.context['error'] = error self.set_header('Content-Type', 'text/html') self.finish("""<html> <title>%s</title> <body> <h2>Error</h2> <p>%s</p> <h2>Traceback</h2> <p>%s</p> <h2>Request Info</h2> <p>%s</p> </body> </html>""" % (error, error, trace_info, request_info))
def __init__(self, *args, **kwargs): logging.info('instantiating request handler: %s' % self.__class__.__name__) self.include_host = True self.user = None self.is_admin = None # requires @is_admin decorator to check self.admin_user = None #from main import settings self._settings = settings.get_settings() self.context = { 'current_user': None, 'error': {}, 'base_url': gae_utils.base_url(), 'user_agent': gae_utils.GetUserAgent(), "handler_name": self.__class__.__name__, "handler": self, 'token': None, "debug": gae_utils.Debug(), "ip_address": str(os.environ.get('REMOTE_ADDR', '')), "settings": self._settings, "getattr": getattr } super(BaseHandler, self).__init__(*args, **kwargs)
def get_settings(): from utils import gae as gae_utils _settings = SETTINGS.copy() if gae_utils.Debug(): _settings.update(DEBUG_SETTINGS) if gae_utils.Staging(): _settings.update(STAGING_SETTINGS) else: _settings.update(PROD_SETTINGS) _settings['website'] = _settings['protocol'] + _settings['domain'] return _settings
def render_string(self, template_name, **kwargs): # Let the templates access the users module to generate login URLs kwargs['settings'] = self._settings kwargs['ip_address'] = str(os.environ.get('REMOTE_ADDR', '')) kwargs['error'] = self.error kwargs['arguments'] = getattr(self.request, 'arguments', {}) kwargs['debug'] = gae_utils.Debug() return tornado.web.RequestHandler.render_string(self, template_name, users=users, **kwargs)
def render(self, template_file, get_current_user=False, **kwargs): kwargs['settings'] = self._settings if get_current_user: # forces the get kwargs['current_user'] = self.get_current_user() else: kwargs['current_user'] = self.user kwargs['ip_address'] = str(os.environ.get('REMOTE_ADDR', '')) kwargs['error'] = self.error kwargs['debug'] = gae_utils.Debug() if self.error: logging.warning('returning error: %s' % self.error) return super(BaseHandler, self).render(template_file, **kwargs)
def send(self): if not getattr(self, 'message', None): return logging.error('unable to send message') logging.info('sending email message') logging.info('message sender %s' % self.message.sender) logging.info('message to %s' % self.message.to) if gae_utils.Staging(): self.message.subject = '(STAGING) %s' % self.message.subject logging.info('message subject %s' % self.message.subject) logging.info('message context %s' % self.context) #logging.info('message body %s' % self.message.body) if gae_utils.Debug( ) and 'gmail.com' not in self.message.to and self.message.to not in settings.SETTINGS[ 'admin_emails']: # for viewing logging.info( 'Staging or development - not sending email to %s: %s' % (self.message.to, self.message.subject)) from google.appengine.api import memcache debug_email = memcache.get('debug_email') if not debug_email: debug_email = [] debug_email.insert(0, self.message) memcache.set('debug_email', debug_email) else: if self.message.to in ['*****@*****.**']: logging.info('not sending email to %s' % self.message.to) return if self.order and self.order.disable_emails: logging.info( 'order %s has disable_emails set. not sending email to %s' % (self.order.order_id, self.message.to)) return try: logging.info('sending email to %s' % self.message.to) self.message.send() except mail.InvalidSenderError: logging.critical( 'InvalidSenderError for sender %s. Not sending email' % self.message.sender)
def send_error(self, *args, **kwargs): self.set_status(500) # always 500? from utils.gae import error_msg error, err_msg = error_msg() logging.error('%s - %s' % (error, err_msg)) if gae_utils.Debug(): logging.info('debug server, not sending admin error report') return super(BaseHandler, self).send_error(*args, **kwargs) else: for bot_agent in [ 'google', 'appengine', 'alexa', 'yahoo', 'bot', 'bing' ]: if bot_agent in gae_utils.GetUserAgent().lower(): return # self.error_output(error, err_msg) if '405: Method Not Allowed' in err_msg: return self.error_output(error, err_msg) # TODO: include info about user and session # TODO: print out 500 page. And also do the same for 400 page. user = self.get_current_user() if user: user = user.key().name() deferred.defer(send_admin_email, subject='Error - %s' % error, message='Error Traceback - %s' % err_msg, user=user, user_agent=gae_utils.GetUserAgent(), ip=gae_utils.IPAddress(), url=gae_utils.GetUrl()) self._finished = False if getattr(self, 'server_error', ''): self.server_error() # TODO: Ajax/API views should have their own error output else: self.error_output(error, err_msg) self._finished = True return
def send_info(self): from google.appengine.api import urlfetch if gae_utils.Debug(): fetch_url = 'http://0.0.0.0:5000' else: fetch_url = 'http://passtiche.herokuapp.com' logging.info('sending to heroku: %s' % self.pass_json) response = urlfetch.fetch( fetch_url, payload=json.dumps(self.pass_json), method='POST', headers={'Content-Type': 'application/json;charset=UTF-8'}, deadline=60) if response.status_code != 200: logging.error(response.content) from backend.admin import send_admin_email send_admin_email(subject='Heroku Error', message=response.content, user_agent=gae_utils.GetUserAgent(), ip=gae_utils.IPAddress(), url=gae_utils.GetUrl()) raise ValueError('heroku error') logging.info('heroku response: %s' % len(response.content)) self.pass_file = response.content
def redirect(self, target): super(BaseHandler, self).redirect(target) raise errors.Redirect(target) def humanized_date(self, val, **kwargs): """ optional 'now' datetime argument """ from utils.time import normal_date, humanized_date dt = normal_date(val) return humanized_date(dt, **kwargs) def render_string(filename, context): template = jinja_environment.get_template('%s.html' % filename) return template.render(context) @cache(reset=gae_utils.Debug()) def get_template_file(template_file_name): path = os.path.join(os.path.dirname(__file__), '../templates/%s.html' % template_file_name) template_file = open(path) compiled_template = template.Template(template_file.read()) template_file.close() return compiled_template class MockRequest(object): def get(self, *args): if args and len(args) > 1: return args[1]