Python google.appengine.api.memcache.get() Examples

The following are code examples for showing how to use google.appengine.api.memcache.get(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: splunk-google-drive   Author: LukeMurphey   File: appengine.py    Apache License 2.0 6 votes vote down vote up
def xsrf_secret_key():
    """Return the secret key for use for XSRF protection.

    If the Site entity does not have a secret key, this method will also create
    one and persist it.

    Returns:
        The secret key.
    """
    secret = memcache.get(XSRF_MEMCACHE_ID, namespace=OAUTH2CLIENT_NAMESPACE)
    if not secret:
        # Load the one and only instance of SiteXsrfSecretKey.
        model = SiteXsrfSecretKey.get_or_insert(key_name='site')
        if not model.secret:
            model.secret = _generate_new_xsrf_secret_key()
            model.put()
        secret = model.secret
        memcache.add(XSRF_MEMCACHE_ID, secret,
                     namespace=OAUTH2CLIENT_NAMESPACE)

    return str(secret) 
Example 2
Project: splunk-google-drive   Author: LukeMurphey   File: appengine.py    Apache License 2.0 6 votes vote down vote up
def __init__(self, scope, **kwargs):
        """Constructor for AppAssertionCredentials

        Args:
            scope: string or iterable of strings, scope(s) of the credentials
                   being requested.
            **kwargs: optional keyword args, including:
            service_account_id: service account id of the application. If None
                                or unspecified, the default service account for
                                the app is used.
        """
        self.scope = _helpers.scopes_to_string(scope)
        self._kwargs = kwargs
        self.service_account_id = kwargs.get('service_account_id', None)
        self._service_account_email = None

        # Assertion type is no longer used, but still in the
        # parent class signature.
        super(AppAssertionCredentials, self).__init__(None) 
Example 3
Project: splunk-google-drive   Author: LukeMurphey   File: appengine.py    Apache License 2.0 6 votes vote down vote up
def locked_get(self):
        """Retrieve Credential from datastore.

        Returns:
            oauth2client.Credentials
        """
        credentials = None
        if self._cache:
            json = self._cache.get(self._key_name)
            if json:
                credentials = client.Credentials.new_from_json(json)
        if credentials is None:
            entity = self._get_entity()
            if entity is not None:
                credentials = getattr(entity, self._property_name)
                if self._cache:
                    self._cache.set(self._key_name, credentials.to_json())

        if credentials and hasattr(credentials, 'set_store'):
            credentials.set_store(self)
        return credentials 
Example 4
Project: splunk-google-drive   Author: LukeMurphey   File: appengine.py    Apache License 2.0 6 votes vote down vote up
def oauth2decorator_from_clientsecrets(filename, scope,
                                       message=None, cache=None):
    """Creates an OAuth2Decorator populated from a clientsecrets file.

    Args:
        filename: string, File name of client secrets.
        scope: string or list of strings, scope(s) of the credentials being
               requested.
        message: string, A friendly string to display to the user if the
                 clientsecrets file is missing or invalid. The message may
                 contain HTML and will be presented on the web interface for
                 any method that uses the decorator.
        cache: An optional cache service client that implements get() and set()
               methods. See clientsecrets.loadfile() for details.

    Returns: An OAuth2Decorator
    """
    return OAuth2DecoratorFromClientSecrets(filename, scope,
                                            message=message, cache=cache) 
Example 5
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 6 votes vote down vote up
def cached(time=1200):
  """
  Decorator that caches the result of a method for the specified time in seconds.
  
  Use it as:
    
    @cached(time=1200)
    def functionToCache(arguments):
      ...
    
  """
  def decorator(function):
    @functools.wraps(function)
    def wrapper(*args, **kwargs):
      key = '%s%s%s' % (function.__name__, str(args), str(kwargs))
      value = memcache.get(key)
      logging.debug('Cache lookup for %s, found? %s', key, value != None)
      if not value:
        value = function(*args, **kwargs)
        memcache.set(key, value, time=time)
      return value
    return wrapper
  return decorator 
Example 6
Project: ithz   Author: ergoithz   File: db_log.py    MIT License 6 votes vote down vote up
def db_log(model, call, details=''):
  """Call this method whenever the database is invoked.
  
  Args:
    model: the model name (aka kind) that the operation is on
    call: the kind of operation (Get/Put/...)
    details: any text that should be added to the detailed log entry.
  """
  
  # First, let's update memcache
  if model:
    stats = memcache.get('DB_TMP_STATS')
    if stats is None: stats = {}
    key = '%s_%s' % (call, model)
    stats[key] = stats.get(key, 0) + 1
    memcache.set('DB_TMP_STATS', stats)
  
  # Next, let's log for some more detailed analysis
  logging.debug('DB_LOG: %s @ %s (%s)', call, model, details) 
Example 7
Project: livremarketplace   Author: salomax   File: models.py    Apache License 2.0 6 votes vote down vote up
def put(email, name, user_key=None):
    """ Save a marketplace in the Datastore.
    """

    if user_key is None:
        user_key = user.user_key(email)

    marketplaceModel = MarketplaceModel.query(ancestor=user_key).get()

    if marketplaceModel is None:
        marketplaceModel = MarketplaceModel(parent=user_key)

    marketplaceModel.name = name

    marketplaceModel.put()

    logging.debug(
        ' Created successfuly marketplace to user %s', email)

    return marketplaceModel 
Example 8
Project: gae-bbs   Author: ego008   File: view.py    Apache License 2.0 6 votes vote down vote up
def get(self, name):
        name = name.lower()
        m_obj = Member.get_by_key_name(name)
        if m_obj:
            self.echo('member.html', {
                'title': m_obj.name,
                'm_obj': m_obj,
                'mi_obj': MemberInfo.get_by_key_name(name),
                'newest_node': Node.get_newest(),
                #'recent_node': Node.get_recent_node(),
                'hot_node': Node.get_hot_node(),
                'recent_topic_objs': KeyStrValue.get_topic_key_title('recent-topic-home'),
                'reply_topic_objs': KeyStrValue.get_topic_key_title('recent-reply-topic'),            
            }, layout='_layout.html')
        else:
            self.error(404)
            self.echo('error.html', {
                'page': '404',
                'title': "Can't find out this URL",
                'h2': 'Oh, my god!',
                'msg': 'Something seems to be lost...'
            })
            return 
Example 9
Project: gae-bbs   Author: ego008   File: view.py    Apache License 2.0 6 votes vote down vote up
def get(self, node_id):
        n_obj = Node.get_by_id(int(node_id))
        if n_obj:
            
            urlstr = """<url><loc>%s</loc><changefreq>%s</changefreq><priority>%s</priority></url>\n """
            urllist = []
            urllist.append('<?xml version="1.0" encoding="UTF-8"?>\n')
            urllist.append('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n')
            
            urllist.append(urlstr%("%s/n-%s" % (BASE_URL, str(node_id)), 'weekly', '0.6'))
            
            max_id = n_obj.count
            to_id = max_id - 40000
            if to_id<0:
                to_id = 0
            for i in xrange(max_id, to_id,-1):
                urllist.append(urlstr%("%s/t-%s-%d" % (BASE_URL, str(node_id), i), 'weekly', '0.5'))
            
            urllist.append('</urlset>')
            
            self.header['Content-Type'] = "text/xml"
            self.write(''.join(urllist))
        else:
            self.write('') 
Example 10
Project: gae-bbs   Author: ego008   File: view.py    Apache License 2.0 6 votes vote down vote up
def get(self, nodeid='1'):
        if self.cur_user and self.cur_user.flag>1:
            n_obj = Node.get_by_id(int(nodeid))
            if not n_obj:
                self.error(404)
                self.echo('error.html', {
                    'page': '404',
                    'title': "Can't find out this URL",
                    'h2': 'Oh, my god!',
                    'msg': 'Something seems to be lost...'
                })
                return
            self.echo('newpost.html', {
                'title': "发新帖子",
                'errors':[],
                'n_obj': n_obj,
                't_obj': Topic(),
                'newest_node': Node.get_newest(),
            }, layout='_layout.html')
        else:
            self.error(403)
            self.write('403:forbidden') 
Example 11
Project: gae-bbs   Author: ego008   File: view.py    Apache License 2.0 6 votes vote down vote up
def get(self):
        if self.cur_user and self.cur_user.flag==99:
            n_id = self.request.get('id')
            if n_id:
                n_obj = Node.get_by_id(int(n_id))
            else:
                n_obj = Node()
                
            if n_obj:
                title = "修改分类"
            else:
                n_obj = Node()
                title = "添加分类"
                
            self.echo('addnode.html', {
                'title': title,
                'n_obj': n_obj,
                'newest_node': Node.get_newest(),
            }, layout='_layout.html')
        else:
            self.error(403)
            self.write('403:forbidden') 
Example 12
Project: gae-bbs   Author: ego008   File: view.py    Apache License 2.0 6 votes vote down vote up
def post(self):
        if self.cur_user and self.cur_user.flag==99:
            m_name = self.request.get('name')
            flag = self.request.get('flag')
            m_obj = None
            if m_name and flag:
                m_obj = Member.get_by_key_name(m_name)
                if m_obj:
                    m_obj.flag = int(flag)
                    m_obj.put()
                else:
                    self.redirect('/set-user-flag')
                    return
            
            self.redirect('/set-user-flag?name=%s'%str(m_name))
        else:
            self.error(403)
            self.write('403:forbidden') 
Example 13
Project: gae-bbs   Author: ego008   File: view.py    Apache License 2.0 6 votes vote down vote up
def post(self):
        if self.cur_user and self.cur_user.flag==99:
            t_key = self.request.get('key')
            title = self.POST['title']
            content = self.POST['content']
            
            if t_key and title and content:
                t_obj = Topic.get_by_key_name(t_key)
                if t_obj:
                    t_obj.title = title
                    t_obj.con = textilize(content)
                    db.run_in_transaction(obj_runput, t_obj)
                
            self.redirect('/edit-post?key=%s'%str(t_key))
        else:
            self.error(403)
            self.write('403:forbidden') 
Example 14
Project: gae-bbs   Author: ego008   File: view.py    Apache License 2.0 6 votes vote down vote up
def post(self):
        if self.cur_user and self.cur_user.flag==99:
            t_key = self.request.get('key')
            content = self.POST['content']
            if t_key and content:
                t_obj = Comment.get_by_key_name(t_key)
                if t_obj:
                    t_obj.con = textilize(content)
                    db.run_in_transaction(obj_runput, t_obj)
            
            self.redirect('/edit-comment?key=%s'%str(t_key))
            
        else:
            self.error(403)
            self.write('403:forbidden')        

### 
Example 15
Project: mimic   Author: googlearchive   File: mimic_test.py    Apache License 2.0 5 votes vote down vote up
def _CheckResponse(self, status, content_type):
    expected_status = '{} {}'.format(status, httplib.responses[status])
    self.assertEquals(expected_status, self._status)
    self.assertEquals(content_type, self._headers.get('Content-Type')) 
Example 16
Project: mimic   Author: googlearchive   File: mimic_test.py    Apache License 2.0 5 votes vote down vote up
def assertResponseExpiration(self, seconds):
    expected_cache_control = 'public, max-age={0}'.format(seconds)
    self.assertEquals(expected_cache_control,
                      self._headers.get('Cache-Control')) 
Example 17
Project: mimic   Author: googlearchive   File: mimic_test.py    Apache License 2.0 5 votes vote down vote up
def testAppYamlNoImplicitDefaultExpiration(self):
    self._AddFile('app.yaml', MakeAppYaml())
    self._AddFile('static/foo.txt', '123')
    self._CallMimic('/foo.txt')
    self._CheckResponse(httplib.OK, 'text/plain; charset=utf-8')
    self.assertEquals('123', self._body)
    self.assertEquals(None, self._headers.get('Cache-Control')) 
Example 18
Project: mimic   Author: googlearchive   File: mimic_test.py    Apache License 2.0 5 votes vote down vote up
def testGetProjectIdFromCurrentQueryParam(self):
    self.assertEquals(None, mimic._dev_appserver_state.get('project_id'))
    self.assertEquals('_mimic_project', common.config.PROJECT_ID_QUERY_PARAM)
    self.assertEquals(None, mimic.GetProjectIdFromQueryParam(os.environ))
    self.CheckProjectIdFromQueryString('proj42', '_mimic_project=proj42')
    self.assertEquals(None, mimic._dev_appserver_state.get('project_id'))
    self.CheckProjectIdFromQueryString(None, '')
    self.assertEquals(None, mimic._dev_appserver_state.get('project_id'))
    self.CheckProjectIdFromQueryString(None, '_mimic_project=')
    self.assertEquals(None, mimic._dev_appserver_state.get('project_id')) 
Example 19
Project: mimic   Author: googlearchive   File: mimic_test.py    Apache License 2.0 5 votes vote down vote up
def testGetProjectIdFromRecentQueryParam(self):
    self.assertEquals(None, mimic._dev_appserver_state.get('project_id'))
    self.assertEquals('_mimic_project', common.config.PROJECT_ID_QUERY_PARAM)
    self.assertEquals(None, mimic.GetProjectIdFromQueryParam(os.environ))
    self.CheckProjectIdFromQueryString('proj42', '_mimic_project=proj42', True)
    self.assertEquals('proj42', mimic._dev_appserver_state.get('project_id'))
    self.CheckProjectIdFromQueryString('proj42', '', True)
    self.assertEquals('proj42', mimic._dev_appserver_state.get('project_id'))
    self.CheckProjectIdFromQueryString('proj42', '_mimic_project=', True)
    self.assertEquals('proj42', mimic._dev_appserver_state.get('project_id')) 
Example 20
Project: mimic   Author: googlearchive   File: mimic_test.py    Apache License 2.0 5 votes vote down vote up
def testDBNamespacingSameProjectDifferentBranch(self):
    """Tests that different branches of the same project see the same data."""
    self.SetupDBNamespacing()
    self._CallMimic('/get.py', http_host='proj1.your-app-id.appspot.com')
    self.assertEquals('name: JohnDoe, namespace: "proj1"\n', self._body) 
Example 21
Project: mimic   Author: googlearchive   File: mimic_test.py    Apache License 2.0 5 votes vote down vote up
def testDBNamespacingDifferentProjectNoData(self):
    """Tests that different projects don't see other projects' data."""
    self.SetupDBNamespacing()
    # different project should'nt see any data
    self._CallMimic('/get.py', http_host='proj3.your-app-id.appspot.com')
    self.assertEquals('None\n', self._body) 
Example 22
Project: Utmost_Bot   Author: jiachen247   File: utmost.py    GNU General Public License v3.0 5 votes vote down vote up
def get_material(name):
    key = db.Key.from_path('Material', str(name))
    material = db.get(key)
    if material is None:
        material = Material(key_name=str(name))
        material.put()
    return material 
Example 23
Project: Utmost_Bot   Author: jiachen247   File: utmost.py    GNU General Public License v3.0 5 votes vote down vote up
def __init(self):
        # date object storing date for
        self.date = None
        self.heading = None
        self.verse_reference = None
        self.bible_in_a_year = None
        self.verse_concise = None
        self.verse_full = None
        self.post = None

        # write get and set

        # link to get full verse
        self.link_to_full_verse_bgw = None
        self.link_to_full_verse_yv = None 
Example 24
Project: Utmost_Bot   Author: jiachen247   File: utmost.py    GNU General Public License v3.0 5 votes vote down vote up
def __parse_utmost_org(self, html, today_date):

        logging.debug("Starting to parse utmost.org::")
        try:
            soup = BeautifulSoup(html, 'lxml')

            date = today_date.strftime('%b %d, %Y ({})').format(today_date.strftime('%a').upper())
            heading = soup.select_one('.entry-title').text.strip()
            verse_consise = soup.select_one('#key-verse-box > p').text
            demarc = verse_consise.index("—".decode("utf-8"))
            verse_consise = verse_consise[:demarc]
            verse_reference = soup.select_one('#key-verse-box > p > a').text
            post = self.strip_markdown(soup.select_one('.post-content').text.replace("\n", "\n\n"))
            link_to_verse = soup.select_one('#key-verse-box > p > a').get("href").strip()

            bible_in_a_year = soup.select_one('#bible-in-a-year-box > a').get("href").strip()
            bible_in_a_year_text = "[" + soup.select_one('#bible-in-a-year-box > a').text.replace("; ",
                                                                                                  "\n") + "](" + bible_in_a_year + ")"

            self.devo_object.date = date
            self.devo_object.heading = heading
            self.devo_object.verse_concise = verse_consise
            self.devo_object.verse_reference = verse_reference
            self.devo_object.post = post
            self.devo_object.bible_in_a_year = bible_in_a_year_text
            # IMPT - wont carry on without setting this
            self.devo_object.link_to_full_verse_bgw = link_to_verse

        except Exception as e:
            logging.warning('Error parsing utmost devo:\n' + str(e))
            return False

        finally:
            return True 
Example 25
Project: hackernewsbot   Author: phil-r   File: main.py    MIT License 5 votes vote down vote up
def story_redirect(short_id):
  """Redirect to story url"""
  try:
    story_id = str(shortener.decode(short_id))
  except:
    return abort(400)
  redirect_url = memcache.get(story_id)
  if not redirect_url:
    story = ndb.Key(StoryPost, story_id).get()
    if not story:
      return make_response('<h1>Service Unavailable</h1><p>Try again later</p>', 503, {'Retry-After': 5})
    story.add_memcache()
    redirect_url = story.url
  return redirect(redirect_url) 
Example 26
Project: hackernewsbot   Author: phil-r   File: main.py    MIT License 5 votes vote down vote up
def task(stories):
  def check_story(rpc):
    try:
      result = rpc.get_result()
      story = json.loads(result.content)
      if story and story.get('score') >= 100:
        StoryPost.add(story)
      elif story and story.get('score'):
        # api returned a comment once (issue with id 21447853)
        logging.info('STOP: {id} has low score ({score})'.format(**story))
      elif story:
        logging.info('STOP: {id} has no score'.format(**story))
      else:
        logging.info("STOP: story was probably deleted/flagged")
    except urlfetch.DownloadError as ex:
      logging.exception(ex)
    except ValueError as ex:
      logging.info(result.content)
      logging.exception(ex)


  # stringify ids for use in memcache and convert to set for later
  ids = set(str(story_id) for story_id in stories)
  logging.info('checking stories: {}'.format(ids))
  # get stories that we already posted to reduce the number of requests
  cached_stories = set(memcache.get_multi(ids).keys())
  logging.info('cached stories: {}'.format(cached_stories))
  # remove stories we know about from stories that we need to check
  stories_to_check = ids.difference(cached_stories)
  rpcs = map(lambda id: item_async(id, check_story), stories_to_check)
  for rpc in rpcs:
    rpc.wait() 
Example 27
Project: loaner   Author: google   File: template_model.py    Apache License 2.0 5 votes vote down vote up
def _get_subtemplate(self, sub_name):
    """Gets a template from memcache or datastore for the Jinja2 environment.

    This gets either a sub-component of a Template entity (title or body).

    Args:
      sub_name: str, the name of the subcomponent of the Template (e.g.,
          'template:title:device_due' for the title property of the device_due
          template. If the sub_name is 'base' it gets the body of the base
          template, which has no title.

    Returns:
      The pre-rendered Jinja2-formatted template string.

    Raises:
      NoTemplateError: if the template with that sub-name does not exist.
    """
    if not self.templates_cached:
      self._cache_all_templates()
    if sub_name.endswith('_base'):
      sub_name = _CACHED_BODY_NAME % sub_name
    cached_template = memcache.get(sub_name)
    if cached_template:
      return cached_template
    else:
      match = _NAME_RE.match(sub_name)
      template_name = match.group(2)  # Stripped template name.
      stored_template = Template.get_by_id(template_name)
      if not stored_template:
        raise NoTemplateError(
            'Template named {} does not exist.'.format(sub_name))
      self._cache_template(stored_template)
      return getattr(stored_template, match.group(1))  # 'title' or 'body'. 
Example 28
Project: loaner   Author: google   File: config_model_test.py    Apache License 2.0 5 votes vote down vote up
def test_get_from_datastore(self, test_config):
    config = config_model.Config.get(test_config[0])
    self.assertEqual(config, test_config[1]) 
Example 29
Project: loaner   Author: google   File: config_model_test.py    Apache License 2.0 5 votes vote down vote up
def test_get_from_memcache(self):
    config = 'string_config'
    config_value = 'this should be read.'
    memcache.set(config, config_value)
    reference_datastore_config = config_model.Config.get_by_id(config)
    config_memcache = config_model.Config.get(config)

    self.assertEqual(config_memcache, config_value)
    self.assertEqual(reference_datastore_config.string_value, 'config value 1') 
Example 30
Project: loaner   Author: google   File: config_model_test.py    Apache License 2.0 5 votes vote down vote up
def test_get_from_default(
      self, mock_get_by_id, mock_memcache_get, mock_config_model_set):
    config = 'test_config'
    expected_value = 'test_value'
    config_datastore = config_model.Config.get(config)
    mock_config_model_set.assert_called_once_with(config, expected_value)
    self.assertEqual(config_datastore, expected_value) 
Example 31
Project: loaner   Author: google   File: config_model_test.py    Apache License 2.0 5 votes vote down vote up
def test_get_identifier_with_use_asset(self):
    config_model.Config.set('use_asset_tags', True)
    config_datastore = config_model.Config.get('device_identifier_mode')
    self.assertEqual(config_datastore,
                     config_model.DeviceIdentifierMode.BOTH_REQUIRED) 
Example 32
Project: loaner   Author: google   File: config_model_test.py    Apache License 2.0 5 votes vote down vote up
def test_get_nonexistent(self):
    with self.assertRaisesRegexp(KeyError, config_model._CONFIG_NOT_FOUND_MSG):
      config_model.Config.get('does_not_exist') 
Example 33
Project: loaner   Author: google   File: config_model_test.py    Apache License 2.0 5 votes vote down vote up
def test_set(self, test_config):
    config_model.Config.set(test_config[0], test_config[1])
    memcache_config = memcache.get(test_config[0])
    config = config_model.Config.get(test_config[0])

    self.assertEqual(memcache_config, test_config[1])
    self.assertEqual(config, test_config[1]) 
Example 34
Project: loaner   Author: google   File: config_model_test.py    Apache License 2.0 5 votes vote down vote up
def test_set_no_validation(self):
    fake_key = 'fake_int'
    fake_value = 23
    config_model.Config.set(fake_key, fake_value, False)
    result = config_model.Config.get(fake_key)
    self.assertEqual(result, fake_value) 
Example 35
Project: analyzer-website   Author: santiagolizardo   File: index.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def get( self ):
		html = memcache.get( 'page-index' )
		if html is None:
			html = self.generate_html()
			memcache.set( 'page-index', html, time = 3600 )

		self.writeResponse( html ) 
Example 36
Project: analyzer-website   Author: santiagolizardo   File: staticReport.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def get( self, domainUrl ):
		cache_key = 'page_' + domainUrl
		pageHtml = memcache.get( cache_key )
		if pageHtml is None:
			pageHtml = self.generate_static_report( domainUrl )
			memcache.set( key = cache_key, value = pageHtml, time = 86400 )

		self.writeResponse( pageHtml ) 
Example 37
Project: analyzer-website   Author: santiagolizardo   File: staticReport.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def set_twitter_card( self, domainUrl ):	
		self.pageMetas.append({ 'name': 'twitter:card', 'content': 'summary' })
		self.pageMetas.append({ 'name': 'twitter:site', 'content': '@' + twitter_config['username'] })
		self.pageMetas.append({ 'name': 'twitter:title', 'content': '%s SEO and SEM performace metrics' % domainUrl })
		self.pageMetas.append({ 'name': 'twitter:description', 'content': 'Detailed report for %s Website with all major metrics and improvement points' % domainUrl })
		self.pageMetas.append({ 'name': 'twitter:creator', 'content': '@' + twitter_config['username'] })

		screenshotReport = TaskReport.all().filter( 'url =', domainUrl ).filter( 'name = ', 'screenshot' ).get()
		if screenshotReport:
		    screenshot = json.loads( screenshotReport.messageEncoded )
		    if screenshot is not None:
			    self.pageMetas.append({ 'name': 'twitter:image:src', 'content': screenshot }) 
Example 38
Project: bbq   Author: ocadotechnology   File: cached.py    Apache License 2.0 5 votes vote down vote up
def cached(time=1200):
    """
    Decorator that caches the result of a method for the specified time in
    seconds.

    IMPORTANT: If function returns None value, result will not be cached.
    In that case decorated function will be called each time,
    unless return something else than None.

    WARNING: this uses name of the function and passed parameters as a cache
    key.
    'self' param and another ones depends on given __str__ implementations.
    Be aware if you annotate functions used in different context,
    ensure that both of them generate different key.


    Usage:
      @cached(time=1200)
      def functionToCache(arguments):
        ...

    """

    def decorator(function):
        @functools.wraps(function)
        def wrapper(*args, **kwargs):
            key = '%s%s%s' % (function.__name__, str(args), str(kwargs))
            value = memcache.get(key)
            logging.debug('Memcache: key %s %s found', key,
                          'not' if value is None else '')
            if value is None:
                value = function(*args, **kwargs)
                memcache.set(key, value, time=time)
            return value

        return wrapper

    return decorator 
Example 39
Project: bbq   Author: ocadotechnology   File: backup_process.py    Apache License 2.0 5 votes vote down vote up
def __ensure_dataset_for_backups_exists(self):
        location = self.big_query_table_metadata.get_location()
        target_dataset_name = DatasetIdCreator.create(
            datetime.datetime.utcnow(), location, self.project_id)
        dataset_not_exists_in_cache = memcache.get(target_dataset_name) is None

        if dataset_not_exists_in_cache:
            destination_project_id = configuration.backup_project_id
            self.big_query.create_dataset(destination_project_id,
                                          target_dataset_name, location)
            memcache.add(target_dataset_name, 'exist') 
Example 40
Project: pyaedj   Author: google   File: cache.py    Apache License 2.0 5 votes vote down vote up
def memcache_get(key):
  return memcache.get(key, namespace=config.ENV.namespace) 
Example 41
Project: splunk-google-drive   Author: LukeMurphey   File: appengine.py    Apache License 2.0 5 votes vote down vote up
def get_value_for_datastore(self, model_instance):
        logger.info("get: Got type " + str(type(model_instance)))
        cred = super(CredentialsProperty, self).get_value_for_datastore(
            model_instance)
        if cred is None:
            cred = ''
        else:
            cred = cred.to_json()
        return db.Blob(cred)

    # For reading from datastore. 
Example 42
Project: splunk-google-drive   Author: LukeMurphey   File: appengine.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, filename, scope, message=None, cache=None, **kwargs):
        """Constructor

        Args:
            filename: string, File name of client secrets.
            scope: string or iterable of strings, scope(s) of the credentials
                   being requested.
            message: string, A friendly string to display to the user if the
                     clientsecrets file is missing or invalid. The message may
                     contain HTML and will be presented on the web interface
                     for any method that uses the decorator.
            cache: An optional cache service client that implements get() and
                   set()
            methods. See clientsecrets.loadfile() for details.
            **kwargs: dict, Keyword arguments are passed along as kwargs to
                      the OAuth2WebServerFlow constructor.
        """
        client_type, client_info = clientsecrets.loadfile(filename,
                                                          cache=cache)
        if client_type not in (clientsecrets.TYPE_WEB,
                               clientsecrets.TYPE_INSTALLED):
            raise clientsecrets.InvalidClientSecretsError(
                "OAuth2Decorator doesn't support this OAuth 2.0 flow.")

        constructor_kwargs = dict(kwargs)
        constructor_kwargs.update({
            'auth_uri': client_info['auth_uri'],
            'token_uri': client_info['token_uri'],
            'message': message,
        })
        revoke_uri = client_info.get('revoke_uri')
        if revoke_uri is not None:
            constructor_kwargs['revoke_uri'] = revoke_uri
        super(OAuth2DecoratorFromClientSecrets, self).__init__(
            client_info['client_id'], client_info['client_secret'],
            scope, **constructor_kwargs)
        if message is not None:
            self._message = message
        else:
            self._message = 'Please configure your application for OAuth 2.0.' 
Example 43
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def get(self):
		posts = memcache.get('all')
		if posts is None:
			logging.error("DB QUERY")
			posts = db.GqlQuery("SELECT * FROM Post ORDER BY created DESC")
			memcache.set('all', posts)
			memcache.set('last_queried', time())
		if self.request.url.endswith('.json'):
			self.response.headers['Content-Type'] = 'application/json'
			self.write(json.dumps([{'subject':post.title, 'content':post.body, 'created':strftime('%A, %B %c',post.created.timetuple())}
				for post in posts], {'Queried %s seconds ago.' % age}))
		else:
			self.render_html("front_template.html", posts = posts) 
Example 44
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def get_post(id):
	post = memcache.get(id)
	if post is None:
		logging.error("DB QUERY")
		key = db.Key.from_path('Post', int(id))
		post = db.get(key) 
		memcache.set(id, post)
		memcache.set('last_queried', time())
	return post
			

#id is passed from the RE that recognizes the url 
Example 45
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def get(self, id):
		post = get_post(id)
		comments = memcache.get(id + '_comments')
		if post:
			if comments is None:
				logging.error('COMMENT QUERY')
				comments = db.GqlQuery('select * from Comment where ancestor is :1 order by created asc', post)
				memcache.set(id + '_comments', comments)
			if self.request.url.endswith('.json'):
				self.response.headers['Content-Type'] = 'application/json'
				self.write(json.dumps({'subject':post.title, 'content':post.body, 'created':strftime('%A, %B %c',post.created.timetuple())}))
			else:
				self.render_html("permalink_template.html", post = post, comments = comments)
		else:
			self.render_html('404.html') 
Example 46
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def post(self, id):
		content = self.request.get("content")
		if content:
			post = get_post(id)
			author = self.user.username
			post.add_comment(author, content)
			self.redirect(self.request.get('path'))
		else:
			error = "you monster"
			self.render_form(content, error)
			
#---------------------------------------------- newpost -------------------------------------------------------------- 
Example 47
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def get(self):
		if self.user and self.user.post_permission == True:
			self.render_form()
		else:
			self.redirect('/login') 
Example 48
Project: ithz   Author: ergoithz   File: utils.py    MIT License 5 votes vote down vote up
def __memget__(self):
        try:
            cache = memcache.get(self.id)
        except:
            memcache.flush_all()
            cache=None
            
        if cache is not None:
            self.__vars = cache.copy() 
Example 49
Project: ithz   Author: ergoithz   File: utils.py    MIT License 5 votes vote down vote up
def __init__(self):
        c = memcache.get(self.__index)
        if c:
            self.__cached = c.split("#") 
Example 50
Project: ithz   Author: ergoithz   File: utils.py    MIT License 5 votes vote down vote up
def get_page(self, rel, section, level):
        id = self.__id(rel, section, level)
        if id in self.__cached:
            memcache.get(id) 
Example 51
Project: ithz   Author: ergoithz   File: data.py    MIT License 5 votes vote down vote up
def queryRSS(id=None):
    if id:
        return RssScheduledModel.gql("WHERE id = :1",id).get()
    else:
        return RssScheduledModel.fetch(100)

# Queries 
Example 52
Project: ithz   Author: ergoithz   File: data.py    MIT License 5 votes vote down vote up
def queryFirstSection(root,user):
    return SectionModel.gql("WHERE parentid = :1 AND visibility in :2 ORDER BY priority ASC LIMIT 1", root, user.getSectionVisible()).get() 
Example 53
Project: ithz   Author: ergoithz   File: data.py    MIT License 5 votes vote down vote up
def queryFile(id):
    return FileModel.gql("WHERE id = :1", id).get() 
Example 54
Project: ithz   Author: ergoithz   File: data.py    MIT License 5 votes vote down vote up
def queryUserFile(id):
    return UserFileModel.gql("WHERE id = :1", id).get() 
Example 55
Project: ithz   Author: ergoithz   File: data.py    MIT License 5 votes vote down vote up
def queryImageFile(id):
    return UserImageFileModel.gql("WHERE id = :1", id).get() 
Example 56
Project: ithz   Author: ergoithz   File: data.py    MIT License 5 votes vote down vote up
def getUserModel(user):
    return UserModel.gql("WHERE user = :1 LIMIT 1",user).get() 
Example 57
Project: ithz   Author: ergoithz   File: data.py    MIT License 5 votes vote down vote up
def __gfm(self,id):
        ''' Gets from datastore any entity with id '''
        return AuxCounterModel.gql("WHERE id = :1 LIMIT 1",id).get() 
Example 58
Project: ithz   Author: ergoithz   File: fetchrss.py    MIT License 5 votes vote down vote up
def getRSS(url):
    id = "getrss_cache/%s" % url
    a = memcache.get(id)
    if not a:
        #b = queryRSS(url)
        b = False
        if b:
            a = b.content
        else:
            a = parsefeed(url)
            if not a:
                return None
        memcache.set(id, a, 43200) # 43200 seconds is 12 hours
    return a 
Example 59
Project: ithz   Author: ergoithz   File: db_log.py    MIT License 5 votes vote down vote up
def main():
  """A very simple handler that will print the temporary statistics."""
  print 'Content-Type: text/plain'
  print ''
  print 'Mini stats'
  print '----------'
  stats = memcache.get('DB_TMP_STATS')
  if stats is None: stats = {}
  for name, count in sorted(stats.items(), key=operator.itemgetter(0)):
    print '%s : %s' % (name, count)
  print '----------' 
Example 60
Project: livremarketplace   Author: salomax   File: models.py    Apache License 2.0 5 votes vote down vote up
def get_marketplace():
    """ Get active user marketplace.
    """

    # Identificando usuário da requisição
    email = user.get_current_user().email()

    # Return user active marketplace by email
    return get(email) 
Example 61
Project: livremarketplace   Author: salomax   File: models.py    Apache License 2.0 5 votes vote down vote up
def get(email):
    """ Get marketplace model by user email.
    """

    # Set memcache key
    memcache_key = 'email.marktplace.%s' % email

    # Verify if user marktplace is cached
    marketplace_cached = memcache.get(memcache_key)

    # and return cached marketplace
    if marketplace_cached is not None:
        logging.debug("Marketplace cached for %s user. Return it.", email)
        return marketplace_cached

    # else, query or add new one...

    # Create user key as parent
    user_key = user.user_key(email)

    # Select user marketplace
    marketplaceModel = MarketplaceModel.query(ancestor=user_key).get()

    # If not present, create new one
    if marketplaceModel is None:
        marketplaceModel = put(email=email, name='Nova Loja', user_key=user_key)
        logging.debug("Marketplace create sucessfully for %s user", email)

    # Add to memcache
    memcache.add(key=memcache_key, value=marketplaceModel, time=3600 * 24)

    logging.debug("Marketplace cached for %s user", email)

    # Return marketplace
    return marketplaceModel 
Example 62
Project: gae-bbs   Author: ego008   File: view.py    Apache License 2.0 5 votes vote down vote up
def get(self):
        self.echo('home.html', {
            'title': "首页",
            'topic_objs': KeyStrValue.get_topic_objs('recent-topic-home'),
            'site_counts': Counter.get_site_counts(),
            'newest_node': Node.get_newest(),
            'recent_node': Node.get_recent_node(),
            'hot_node': Node.get_hot_node(),
            'reply_topic_objs': KeyStrValue.get_topic_key_title('recent-reply-topic'),
        }, layout='_layout.html') 
Example 63
Project: gae-bbs   Author: ego008   File: view.py    Apache License 2.0 5 votes vote down vote up
def get(self):
        req_user = self.request.user
        gu_obj = GoogleUser.get_or_insert(req_user.email())
        if gu_obj.name:
            self.redirect('/')
            return
        else:
            self.echo('setname.html', {
                'title': "设置名字",
                'errors':[],
                'name':req_user.nickname().split('@')[0],
                'newest_node': Node.get_newest(),
            }, layout='_layout.html') 
Example 64
Project: gae-bbs   Author: ego008   File: view.py    Apache License 2.0 5 votes vote down vote up
def get(self):
        if self.cur_user:
            self.echo('setavatar.html', {
                'title': "设置头像",
                'errors':[],
                'newest_node': Node.get_newest(),
            }, layout='_layout.html')
        else:
            self.redirect('/') 
Example 65
Project: gae-bbs   Author: ego008   File: view.py    Apache License 2.0 5 votes vote down vote up
def post(self):
        if self.cur_user:
            file_content = self.request.get('myfile','')
            errors = []
            if file_content:
                imgobj = images.Image(file_content)
                if imgobj.width <= 73 and imgobj.height <= 73:
                    img_large = file_content
                else:
                    imgobj.resize(73, 73)
                    imgobj.im_feeling_lucky()
                    img_large = imgobj.execute_transforms(output_encoding=images.JPEG, quality=95)
                
                u = UpYun(DOMAIN_NAME_AVATAR, UPYUN_USER, UPYUN_PW)
                file_path_name = '/avatar/%s.jpg'% self.cur_user.name
                avatar = u.writeFile( file_path_name, img_large, True)
                
                if avatar:
                    m_obj = Member.get_by_key_name(self.cur_user.name)
                    if m_obj:
                        if m_obj.flag ==1:
                            if m_obj.id == 1:
                                m_obj.flag = 99
                            else:
                                m_obj.flag = 2
                            db.run_in_transaction(obj_runput,m_obj, ['cur_user:'+self.request.user.email()])
                    
                    self.redirect('/setavatar')
                    return
                else:
                    errors.append('服务器出现意外错误,请稍后再试')
            else:
                self.echo('setavatar.html', {
                    'title': "设置头像",
                    'errors':errors,
                    'newest_node': Node.get_newest(),
                }, layout='_layout.html')
                
        else:
            self.redirect('/') 
Example 66
Project: gae-bbs   Author: ego008   File: view.py    Apache License 2.0 5 votes vote down vote up
def get(self, nodeid, topicid):
        topic_key = '%s-%s' % (nodeid, topicid)
        t_obj = Topic.get_by_key_name(topic_key)
        if not t_obj:
            self.error(404)
            self.echo('error.html', {
                'page': '404',
                'title': "Can't find out this URL",
                'h2': 'Oh, my god!',
                'msg': 'Something seems to be lost...'
            })
            return
        
        if t_obj.cnum:
            from_id = int(self.request.get('id', '1'))
            if from_id>1 and from_id%EACH_PAGE_COMMENT_NUM!=1:
                self.redirect('/t-'+topic_key)
                return
            to_id = from_id + EACH_PAGE_COMMENT_NUM - 1
            if to_id > t_obj.cnum:
                to_id = t_obj.cnum
            c_objs = Comment.get_comments(topic_key, from_id, to_id)
        else:
            c_objs = None
            from_id = to_id = cnum = 0
        
        self.echo('topicdetail.html', {
            'title': t_obj.title + ' - ' + t_obj.node.name,
            'description':'description',
            't_obj': t_obj,
            'c_objs': c_objs,
            'from_id': from_id,
            'to_id': to_id,
            'newest_node': Node.get_newest(),
            #'recent_node': Node.get_recent_node(),
            'hot_node': Node.get_hot_node(),
            'recent_topic_objs': KeyStrValue.get_topic_key_title('recent-topic-home'),
            'reply_topic_objs': KeyStrValue.get_topic_key_title('recent-reply-topic'),
        }, layout='_layout.html') 
Example 67
Project: gae-bbs   Author: ego008   File: view.py    Apache License 2.0 5 votes vote down vote up
def get(self):
        max_nid_obj = Counter.get_or_insert('node_auto_increment', name='node_auto_increment', value = 1)
        self.echo('robots.txt',{'ids':[x for x in range(1,max_nid_obj.value)]}) 
Example 68
Project: gae-bbs   Author: ego008   File: view.py    Apache License 2.0 5 votes vote down vote up
def get(self):
        self.header['Content-Type'] = "application/atom+xml"
        self.echo('index.xml', {
                    'posts':KeyStrValue.get_topic_objs('recent-topic-home')[:FEED_NUM],
                    'site_updated':int(time()),
        }) 
Example 69
Project: gae-bbs   Author: ego008   File: view.py    Apache License 2.0 5 votes vote down vote up
def get(self):
        if self.cur_user:
            self.echo('notifications.html', {
                'title': "站内提醒",
                'newest_node': Node.get_newest(),
                #'recent_node': Node.get_recent_node(),
                'hot_node': Node.get_hot_node(),
                'recent_topic_objs': KeyStrValue.get_topic_key_title('recent-topic-home'),
                'reply_topic_objs': KeyStrValue.get_topic_key_title('recent-reply-topic'),            
            }, layout='_layout.html')
            
        else:
            self.redirect('/') 
Example 70
Project: gae-bbs   Author: ego008   File: view.py    Apache License 2.0 5 votes vote down vote up
def get(self, t_key):
        t_key = str(t_key)
        cur_user = self.cur_user
        if cur_user.notic:
            klist = cur_user.notic.split(',')
            if t_key in klist:
                klist.remove(t_key)
                cur_user.notic = ','.join(klist)
                #cur_user.put()
                db.run_in_transaction(obj_runput,cur_user,['cur_user:'+self.request.user.email()])
        self.redirect('/t-'+t_key)

### admin 
Example 71
Project: gae-bbs   Author: ego008   File: view.py    Apache License 2.0 5 votes vote down vote up
def post(self):
        if self.cur_user and self.cur_user.flag==99:
            n_id = self.request.get('id')
            name = self.POST['name']
            imgurl = self.POST['imgurl']
            about = self.POST['about']
            
            if name:
                if n_id:
                    n_obj = Node.get_by_id(int(n_id))
                else:
                    n_obj = None
                    
                if n_obj:
                    n_obj.name = name
                    n_obj.imgurl = imgurl
                    n_obj.about = about
                    n_obj.put()
                else:
                    #get node id
                    nid_obj = Counter.get_or_insert('node_auto_increment', name='node_auto_increment', value = 1)
                    
                    n_obj = Node(key=db.Key.from_path('Node', nid_obj.value))
                    n_obj.name = name
                    n_obj.imgurl = imgurl
                    n_obj.about = about
                    n_obj.put()
                    
                    if n_obj.is_saved():
                        n_id = nid_obj.value
                        nid_obj.value += 1
                        db.run_in_transaction(obj_runput,nid_obj,['newest_add_node'])
            
            self.redirect('/add-node?id=%s'%str(n_id))
        else:
            self.error(403)
            self.write('403:forbidden') 
Example 72
Project: gae-bbs   Author: ego008   File: view.py    Apache License 2.0 5 votes vote down vote up
def post(self):
        if self.cur_user and self.cur_user.flag==99:
            self.header['Content-Type'] = "text/html"
            rspd = {'status': 201, 'msg':'ok'}
            
            n_id = self.request.get('id')
            if n_id:
                file_content = self.request.get('filetoupload','')
                if file_content:
                    imgobj = images.Image(file_content)
                    if imgobj.width <= 73 and imgobj.height <= 73:
                        img_large = file_content
                    else:
                        imgobj.resize(73, 73)
                        imgobj.im_feeling_lucky()
                        img_large = imgobj.execute_transforms(output_encoding=images.JPEG, quality=95)
                    
                    file_path_name = '/nodeimg/%s.jpg'%  n_id
                    u = UpYun(DOMAIN_NAME_UPLOAD, UPYUN_USER, UPYUN_PW)
                    uimg = u.writeFile( file_path_name, img_large, True)
                    
                    if uimg:
                        rspd['status'] = 200
                        rspd['msg'] = u'图片已成功上传'
                        rspd['url'] = UPLOAD_URL + file_path_name
                    else:
                        rspd['status'] = 500
                        rspd['msg'] = u'图片上传失败,可能是网络问题或图片太大,请刷新本页再上传'
                else:
                    rspd['msg'] = u'没有上传图片'
            else:
                rspd['msg'] = u'id 传入错误'
                
            self.write(json.dumps(rspd))
        else:
            self.error(403)
            self.write('403:forbidden') 
Example 73
Project: gae-bbs   Author: ego008   File: view.py    Apache License 2.0 5 votes vote down vote up
def get(self):
        if self.cur_user and self.cur_user.flag==99:
            t_key = self.request.get('key')
            if t_key:
                t_obj = Topic.get_by_key_name(t_key)
            else:
                t_obj = None
            self.echo('editpost.html', {
                'title': "修改帖子",
                't_obj': t_obj,
            }, layout='_layout.html')
        else:
            self.error(403)
            self.write('403:forbidden') 
Example 74
Project: gae-bbs   Author: ego008   File: view.py    Apache License 2.0 5 votes vote down vote up
def get(self):
        if self.cur_user and self.cur_user.flag==99:
            t_key = self.request.get('key')
            if t_key:
                t_obj = Comment.get_by_key_name(t_key)
            else:
                t_obj = None
            self.echo('editcomment.html', {
                'title': "修改评论",
                't_obj': t_obj,
            }, layout='_layout.html')
            
        else:
            self.error(403)
            self.write('403:forbidden') 
Example 75
Project: gae-bbs   Author: ego008   File: tenjin.py    Apache License 2.0 5 votes vote down vote up
def _add_args_declaration(self, buf, m):
        arr = (m.group(1) or '').split(',')
        args = [];  declares = []
        for s in arr:
            arg = s.strip()
            if not s: continue
            if not re.match('^[a-zA-Z_]\w*$', arg):
                raise ValueError("%r: invalid template argument." % arg)
            args.append(arg)
            declares.append("%s = _context.get('%s'); " % (arg, arg))
        self.args = args
        #nl = stmt[m.end():]
        #if nl: declares.append(nl)
        buf.append(''.join(declares) + "\n") 
Example 76
Project: mimic   Author: googlearchive   File: mimic_test.py    Apache License 2.0 4 votes vote down vote up
def testMemcacheNamespacing(self):
    """Tests that different projects see different memcaches."""

    put_script = """
from google.appengine.api import memcache
import os
value = os.environ['PATH_INFO'].split('?')[1]
memcache.add(key="my_key", value=value, time=3600)

print 'Content-type: text/plain; charset=utf-8'
print 'Status: 200 OK'
print ''
print 'value: ' + value
"""

    get_script = """
from google.appengine.api import memcache

value = memcache.get(key="my_key")

print 'Content-type: text/plain; charset=utf-8'
print 'Status: 200 OK'
print ''
print 'value: ' + value
"""

    self._AddFile('put.py', put_script)
    self._AddFile('get.py', get_script)
    self._AddFile('app.yaml', _GENERIC_APP_YAML)

    # put John and Jane using the same key
    self._CallMimic('/put.py?JohnDoe',
                    http_host='proj1.your-app-id.appspot.com')
    self.assertEquals('value: JohnDoe\n', self._body)
    self._CallMimic('/put.py?JaneDoe',
                    http_host='proj2.your-app-id.appspot.com')
    self.assertEquals('value: JaneDoe\n', self._body)

    self._CallMimic('/get.py', http_host='proj1.your-app-id.appspot.com')
    self.assertEquals('value: JohnDoe\n', self._body)

    self._CallMimic('/get.py', http_host='proj2.your-app-id.appspot.com')
    self.assertEquals('value: JaneDoe\n', self._body) 
Example 77
Project: loaner   Author: google   File: config_model.py    Apache License 2.0 4 votes vote down vote up
def get(cls, name):
    """Checks memcache for name, if not available, check datastore.

    Args:
      name: str, name of config name.

    Returns:
      The config value from memcache, datastore, or config file.

    Raises:
      KeyError: An error occurred when name does not exist.
    """
    memcache_config = memcache.get(name)
    cached_config = None
    if memcache_config:
      return memcache_config

    stored_config = cls.get_by_id(name, use_memcache=False)
    if stored_config:
      if stored_config.string_value:
        cached_config = stored_config.string_value
      elif stored_config.integer_value:
        cached_config = stored_config.integer_value
      elif stored_config.bool_value is not None:
        cached_config = stored_config.bool_value
      elif stored_config.list_value:
        cached_config = stored_config.list_value
    # Conversion from use_asset_tags to device_identifier_mode.
    if name == 'device_identifier_mode' and not cached_config:
      if cls.get('use_asset_tags'):
        cached_config = DeviceIdentifierMode.BOTH_REQUIRED
        cls.set(name, cached_config)
        memcache.set(name, cached_config)
    if cached_config is not None:
      memcache.set(name, cached_config)
      return cached_config
    config_defaults = utils.load_config_from_yaml()
    if name in config_defaults:
      value = config_defaults[name]
      cls.set(name, value)
      return value

    raise KeyError(_CONFIG_NOT_FOUND_MSG, name) 
Example 78
Project: splunk-google-drive   Author: LukeMurphey   File: appengine.py    Apache License 2.0 4 votes vote down vote up
def oauth_required(self, method):
        """Decorator that starts the OAuth 2.0 dance.

        Starts the OAuth dance for the logged in user if they haven't already
        granted access for this application.

        Args:
            method: callable, to be decorated method of a webapp.RequestHandler
                    instance.
        """

        def check_oauth(request_handler, *args, **kwargs):
            if self._in_error:
                self._display_error_message(request_handler)
                return

            user = users.get_current_user()
            # Don't use @login_decorator as this could be used in a
            # POST request.
            if not user:
                request_handler.redirect(users.create_login_url(
                    request_handler.request.uri))
                return

            self._create_flow(request_handler)

            # Store the request URI in 'state' so we can use it later
            self.flow.params['state'] = _build_state_value(
                request_handler, user)
            self.credentials = self._storage_class(
                self._credentials_class, None,
                self._credentials_property_name, user=user).get()

            if not self.has_credentials():
                return request_handler.redirect(self.authorize_url())
            try:
                resp = method(request_handler, *args, **kwargs)
            except client.AccessTokenRefreshError:
                return request_handler.redirect(self.authorize_url())
            finally:
                self.credentials = None
            return resp

        return check_oauth 
Example 79
Project: splunk-google-drive   Author: LukeMurphey   File: appengine.py    Apache License 2.0 4 votes vote down vote up
def callback_handler(self):
        """RequestHandler for the OAuth 2.0 redirect callback.

        Usage::

            app = webapp.WSGIApplication([
                ('/index', MyIndexHandler),
                ...,
                (decorator.callback_path, decorator.callback_handler())
            ])

        Returns:
            A webapp.RequestHandler that handles the redirect back from the
            server during the OAuth 2.0 dance.
        """
        decorator = self

        class OAuth2Handler(webapp.RequestHandler):
            """Handler for the redirect_uri of the OAuth 2.0 dance."""

            @login_required
            def get(self):
                error = self.request.get('error')
                if error:
                    errormsg = self.request.get('error_description', error)
                    self.response.out.write(
                        'The authorization request failed: {0}'.format(
                            _safe_html(errormsg)))
                else:
                    user = users.get_current_user()
                    decorator._create_flow(self)
                    credentials = decorator.flow.step2_exchange(
                        self.request.params)
                    decorator._storage_class(
                        decorator._credentials_class, None,
                        decorator._credentials_property_name,
                        user=user).put(credentials)
                    redirect_uri = _parse_state_value(
                        str(self.request.get('state')), user)
                    if redirect_uri is None:
                        self.response.out.write(
                            'The authorization request failed')
                        return

                    if (decorator._token_response_param and
                            credentials.token_response):
                        resp_json = json.dumps(credentials.token_response)
                        redirect_uri = _helpers._add_query_parameter(
                            redirect_uri, decorator._token_response_param,
                            resp_json)

                    self.redirect(redirect_uri)

        return OAuth2Handler 
Example 80
Project: gae-bbs   Author: ego008   File: tenjin.py    Apache License 2.0 4 votes vote down vote up
def render(self, context=None, globals=None, _buf=None):
        """Evaluate python code with context dictionary.
           If _buf is None then return the result of evaluation as str,
           else return None.

           context:dict (=None)
             Context object to evaluate. If None then new dict is created.
           globals:dict (=None)
             Global object. If None then globals() is used.
           _buf:list (=None)
             If None then new list is created.
        """
        if context is None:
            locals = context = {}
        elif self.args is None:
            locals = context.copy()
        else:
            locals = {}
            if '_engine' in context:
                context.get('_engine').hook_context(locals)
        locals['_context'] = context
        if globals is None:
            globals = sys._getframe(1).f_globals
        bufarg = _buf
        if _buf is None:
            _buf = []
        locals['_buf'] = _buf
        if not self.bytecode:
            self.compile()
        if self.trace:
            _buf.append("<!-- ***** begin: %s ***** -->\n" % self.filename)
            exec(self.bytecode, globals, locals)
            _buf.append("<!-- ***** end: %s ***** -->\n" % self.filename)
        else:
            exec(self.bytecode, globals, locals)
        if bufarg is not None:
            return bufarg
        elif not logger:
            return ''.join(_buf)
        else:
            try:
                return ''.join(_buf)
            except UnicodeDecodeError, ex:
                logger.error("[tenjin.Template] " + str(ex))
                logger.error("[tenjin.Template] (_buf=%r)" % (_buf, ))
                raise