Exemple #1
0
def jsonResponse(request, json):
    """Returns a response in json format.
  """

    context = {'json': json}
    template = 'soc/json.html'

    # allow for easy debugging of json responses by setting &plain=1
    no_plain = not (system.isLocal() and request.GET.get('plain'))

    response_args = {'mimetype': 'application/json'} if no_plain else {}
    response = respond(request, template, context, response_args)

    # if the browser supports HTTP/1.1
    # post-check and pre-check and no-store for IE7
    response['Cache-Control'] = 'no-store, no-cache, must-revalidate, ' \
                                'post-check=0, pre-check=0',  # HTTP/1.1, IE7

    if no_plain:
        response['Content-Type'] = 'application/json'

    # if the browser supports HTTP/1.0
    response['Pragma'] = 'no-cache'

    return response
Exemple #2
0
def sendMail(context, parent=None, run=True, transactional=True):
    """Sends out an email using context to supply the needed information.

  Args:
    context: The context supplied to the email message (dictionary)
    parent: The parent entity to use for when this mail is to be sent in a
            transaction.
    run: If true the mail will be sent otherwise the function that can sent
         the mail will be returned.
    transactional: Whether the task should be created transactionally.

  Raises:
    Error that corresponds with the first problem it finds iff the message
    is not properly initialized.

    List of all possible errors:
      http://code.google.com/appengine/docs/mail/exceptions.html
  """
    # construct the EmailMessage from the given context
    message = mail.EmailMessage(**context)
    message.check_initialized()

    # don't send out emails in non-local debug mode
    if not system.isLocal() and system.isDebug():
        return

    txn = mailer.getSpawnMailTaskTxn(context=context, parent=parent, transactional=transactional)
    if run:
        return db.RunInTransaction(txn)
    else:
        return txn
def sendMail(context):
  """Sends out an email using context to supply the needed information.

  Args:
    context : The context supplied to the email message (dictionary)

  Raises:
    Error that corresponds with the first problem it finds iff the message
    is not properly initialized.

    List of all possible errors:
      http://code.google.com/appengine/docs/mail/exceptions.html
  """

  # construct the EmailMessage from the given context
  message = mail.EmailMessage(**context)
  message.check_initialized()

  # don't send out emails in non-local debug mode
  if not system.isLocal() and system.isDebug():
    return

  try:
    # send the message
    message.send()
  except (mail.Error, OverQuotaError), exception:
    import logging
    logging.info(context)
    logging.exception(exception)
Exemple #4
0
  def render(self, context):
    """Renders the page using the specified context.

    The page is rendered using the template specified in self.templatePath()
    and is written to the response object.

    The context object is extended with the following values:
      app_version: the current version of the application, used e.g. in URL
                   patterns to avoid JS caching issues.
      is_local: Whether the application is running locally.
      posted: Whether render is called after a POST is request.
      xsrf_token: The xsrf token for the current user.

    Args:
      context: the context that should be used
    """

    context['app_version'] = os.environ.get('CURRENT_VERSION_ID', '').split('.')[0]
    context['is_local'] = system.isLocal()
    context['posted'] = self.posted
    xsrf_secret_key = site.getXsrfSecretKey(self.data.site)
    context['xsrf_token'] = xsrfutil.getGeneratedTokenForCurrentUser(xsrf_secret_key)
    context['ga_tracking_num'] = self.data.site.ga_tracking_num
    if system.isSecondaryHostname(self.request):
      context['google_api_key'] = self.data.site.secondary_google_api_key
    else:
      context['google_api_key'] = self.data.site.google_api_key

    rendered = loader.render_to_string(self.templatePath(), dictionary=context)
    self.response.write(rendered)
Exemple #5
0
def getUniversalContext(request):
  """Constructs a template context dict will many common variables defined.
  
  Args:
    request: the Django HTTP request object

  Returns:
    a new context dict containing:
    
    {
      'request': the Django HTTP request object passed in by the caller
      'account': the logged-in Google Account if there is one
      'user': the User entity corresponding to the Google Account in
        context['account']
      'is_admin': True if users.is_current_user_admin() is True
      'is_debug': True if system.isDebug() is True
      'sign_in': a Google Account login URL
      'sign_out': a Google Account logout URL
      'sidebar_menu_html': an HTML string that renders the sidebar menu
    }
  """

  account = accounts.getCurrentAccount()
  user = None
  is_admin = False

  context = {}
  context['request'] = request

  if account:
    user = user_logic.getForAccount(account)
    is_admin = user_logic.isDeveloper(account=account, user=user)

  context['account'] = account
  context['user'] = user
  context['is_admin'] = is_admin

  context['is_local'] = system.isLocal()
  context['is_debug'] = system.isDebug()
  context['sign_in'] = users.create_login_url(request.path)
  context['sign_out'] = users.create_logout_url(request.path)

  context['sidebar_menu_items'] = callback.getCore().getSidebar(account, user)

  context['gae_version'] = system.getAppVersion()
  context['soc_release'] = system.getMelangeVersion()

  settings = site.logic.getSingleton()

  context['ga_tracking_num'] = settings.ga_tracking_num
  context['gmaps_api_key'] = settings.gmaps_api_key
  context['site_name'] = settings.site_name
  context['site_notice'] = settings.site_notice
  context['tos_link'] = redirects.getToSRedirect(settings)
  context['in_maintenance'] = timeline.isActivePeriod(site, 'maintenance')
 
  return context
Exemple #6
0
  def _fullUrl(self, url, full, secure):
    """Returns the full version of the url iff full.

    The full version starts with http:// and includes getHostname().
    """
    if (not full) and (system.isLocal() or not secure):
      return url

    if secure:
      protocol = 'https'
      hostname = system.getSecureHostname()
    else:
      protocol = 'http'
      hostname = system.getHostname(self._data)

    return '%s://%s%s' % (protocol, hostname, url)
Exemple #7
0
def default(data):
  """Returns a context dictionary with default values set.

  The following values are available:
      app_version: the current version string of the application
      is_local: whether we are running locally
      posted: if this was a post/redirect-after-post request
      xsrf_token: the xstrf_token for this request
      google_api_key: the google api key for this website
      ga_tracking_num: the google tracking number for this website
      ds_write_disabled: if datastore writes are disabled
      css_path: part of the path to the css files to distinguish modules  
  """
  posted = data.request.POST or 'validated' in data.request.GET

  xsrf_secret_key = site.xsrfSecretKey(data.site)
  xsrf_token = xsrfutil.getGeneratedTokenForCurrentUser(xsrf_secret_key)

  if system.isSecondaryHostname(data):
    google_api_key = data.site.secondary_google_api_key
  else:
    google_api_key = data.site.google_api_key

  if data.user and oauth_helper.getAccessToken(data.user):
    gdata_is_logged_in = 'true'
  else:
    gdata_is_logged_in = 'false'

  css_path = '/'.join([
      'soc', 'content', system.getMelangeVersion(), 'css', 'v2',
      data.css_path])

  return {
      'app_version': system.getMelangeVersion(),
      'is_local': system.isLocal(),
      'posted': posted,
      'xsrf_token': xsrf_token,
      'google_api_key': google_api_key,
      'ga_tracking_num': data.site.ga_tracking_num,
      'ds_write_disabled': data.ds_write_disabled,
      'gdata_is_logged_in': gdata_is_logged_in,
      'css_path': css_path
  }
def sendMail(context):
    """Sends out an email using context to supply the needed information.

  Args:
    context : The context supplied to the email message (dictionary)

  Raises:
    Error that corresponds with the first problem it finds iff the message
    is not properly initialized.

    List of all possible errors:
      http://code.google.com/appengine/docs/mail/exceptions.html
  """
    # construct the EmailMessage from the given context
    message = mail.EmailMessage(**context)
    message.check_initialized()

    # don't send out emails in non-local debug mode
    if not system.isLocal() and system.isDebug():
        return

    mailer.spawnMailTask(context)
Exemple #9
0
 def testIsLocal(self):
   """Tests if the current Melange application is running locally.
   """
   self.assertTrue(system.isLocal())
Exemple #10
0
def getUniversalContext(request):
    """Constructs a template context dict will many common variables defined.

  Args:
    request: the Django HTTP request object

  Returns:
    a new context dict containing:

    {
      'request': the Django HTTP request object passed in by the caller
      'account': the logged-in Google Account if there is one
      'user': the User entity corresponding to the Google Account in
        context['account']
      'is_admin': True if users.is_current_user_admin() is True
      'is_debug': True if system.isDebug() is True
      'sign_in': a Google Account login URL
      'sign_out': a Google Account logout URL
      'sidebar_menu_html': an HTML string that renders the sidebar menu
    }
  """

    core = callback.getCore()

    context = core.getRequestValue('context', {})

    if context:
        return context

    account = accounts.getCurrentAccount()
    user = None
    is_admin = False

    context['request'] = request

    if account:
        user = user_logic.getForAccount(account)
        is_admin = user_logic.isDeveloper(account=account, user=user)

    context['account'] = account
    context['user'] = user
    context['is_admin'] = is_admin

    context['is_local'] = system.isLocal()
    context['is_debug'] = system.isDebug()
    context['sign_in'] = users.create_login_url(request.path)
    context['sign_out'] = users.create_logout_url(request.path)

    context['sidebar_menu_items'] = core.getSidebar(account, user)

    context['gae_version'] = system.getAppVersion()
    context['soc_release'] = system.getMelangeVersion()

    settings = site.logic.getSingleton()

    context['ga_tracking_num'] = settings.ga_tracking_num
    context['gmaps_api_key'] = settings.gmaps_api_key
    context['site_name'] = settings.site_name
    context['site_notice'] = settings.site_notice
    context['tos_link'] = redirects.getToSRedirect(settings)
    context['in_maintenance'] = timeline.isActivePeriod(
        settings, 'maintenance')

    # Only one xsrf_token is generated per request.
    xsrf_secret_key = site.logic.getXsrfSecretKey(settings)
    context['xsrf_token'] = xsrfutil.getGeneratedTokenForCurrentUser(
        xsrf_secret_key)

    core.setRequestValue('context', context)

    return context