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

The following are code examples for showing how to use google.appengine.api.memcache.flush_all(). 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: Utmost_Bot   Author: jiachen247   File: main.py    GNU General Public License v3.0 6 votes vote down vote up
def get(self):
        logging.debug("Caching devos for today.")
        memcache.flush_all()

        status = "Status : "

        try:
            # cache only today and tmr
            for delta in range(0, 2):
                for version in range(V.get_size()):
                    logging.debug("how many times {}".format(version))
                    get_devo(delta=delta, version=V.get_version_letters(version))
        except Exception as e:
            status += "Cache Failed - " + str(e)

        else:
            status += "Cache Passed: "
        finally:
            send_message(CREATOR_ID, status)
            self.response.write("Success...")

        return 
Example 2
Project: bbq   Author: ocadotechnology   File: test_cached_decorator.py    Apache License 2.0 6 votes vote down vote up
def test_that_cached_function_will_be_executed_after_invalidating_cache(
            self, do_big_computation):
        test_class = TestCachedDecorator.TestClass()

        # when
        result1 = test_class.return_important_string()
        result2 = test_class.return_important_string()
        result3 = test_class.return_important_string()

        memcache.flush_all()

        result4 = test_class.return_important_string()

        # then
        do_big_computation.assert_has_calls([call(), call()])
        self.assertEquals(RETURNED_VALUE, result1)
        self.assertEquals(RETURNED_VALUE, result2)
        self.assertEquals(RETURNED_VALUE, result3)
        self.assertEquals(RETURNED_VALUE, result4) 
Example 3
Project: deb-python-oauth2client   Author: openstack   File: test_appengine.py    Apache License 2.0 6 votes vote down vote up
def test_delete_db_ndb_mixed(self):
        # Start empty
        storage_ndb = appengine.StorageByKeyName(
            appengine.CredentialsNDBModel, 'foo', 'credentials')
        storage = appengine.StorageByKeyName(
            appengine.CredentialsModel, 'foo', 'credentials')

        # First DB, then NDB
        self.assertEqual(None, storage.get())
        storage.put(self.credentials)
        self.assertNotEqual(None, storage.get())

        storage_ndb.delete()
        self.assertEqual(None, storage.get())

        # First NDB, then DB
        self.assertEqual(None, storage_ndb.get())
        storage_ndb.put(self.credentials)

        storage.delete()
        self.assertNotEqual(None, storage_ndb.get())
        # NDB uses memcache and an instance cache (Context)
        ndb.get_context().clear_cache()
        memcache.flush_all()
        self.assertEqual(None, storage_ndb.get()) 
Example 4
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: datastore_viewer.py    Apache License 2.0 6 votes vote down vote up
def post(self):
    """Handle modifying actions and redirect to a GET page."""
    super(DatastoreRequestHandler, self).post()
    if self.request.get('action:flush_memcache'):
      if memcache.flush_all():
        message = 'Cache flushed, all keys dropped.'
      else:
        message = 'Flushing the cache failed. Please try again.'
      self.redirect(self._construct_url(remove=['action:flush_memcache'],
                                        add={'message': message}))
    elif self.request.get('action:delete_entities'):
      entity_keys = self.request.params.getall('entity_key')
      db.delete(entity_keys)
      self.redirect(self._construct_url(
          remove=['action:delete_entities'],
          add={'message': '%d entities deleted' % len(entity_keys)}))
    else:
      self.error(404) 
Example 5
Project: cloud-playground   Author: googlearchive   File: model.py    Apache License 2.0 6 votes vote down vote up
def DeleteReposAndTemplateProjects():
  """Delete repos and related template projects."""
  user = GetPublicTemplateOwner()

  # delete template projects
  keys = user.projects
  ndb.delete_multi(keys)

  # delete ANONYMOUS user
  user.key.delete()

  # delete code repositories
  query = Repo.query(namespace=settings.PLAYGROUND_NAMESPACE)
  keys = query.fetch(keys_only=True)
  ndb.delete_multi(keys)

  # delete repo collections
  query = RepoCollection.query(ancestor=GetGlobalRootEntity().key)
  keys = query.fetch(keys_only=True)
  ndb.delete_multi(keys)

  # flush memcache
  memcache.flush_all() 
Example 6
Project: mimic   Author: googlearchive   File: common_test.py    Apache License 2.0 5 votes vote down vote up
def testDatastore(self):
    common.SetPersistent('foo', '123')
    memcache.flush_all()  # wipe out memcache
    self.assertEquals('123', common.GetPersistent('foo')) 
Example 7
Project: loaner   Author: google   File: template_model_test.py    Apache License 2.0 5 votes vote down vote up
def test_templates(self):
    template = template_model.Template.create(
        'loaner_due', title=TEST_TITLE, body=TEST_BODY)
    self.assertEqual(template.name, 'loaner_due')

    template_model.Template.create('reminder_base', body=TEST_BASE)
    template_loader = template_model.TemplateLoader()

    due_date = datetime.datetime(2017, 10, 13, 9, 31, 0, 0)
    config_dict = {
        'user_email': loanertest.USER_EMAIL,
        'serial': '12345ABC',
        'day_of_week': due_date.strftime('%A'),
        'date': due_date.strftime('%A, %B %d'),
        'turtle_name': 'Grumpy'
    }
    rendered_title, rendered_body = template_loader.render(
        'loaner_due', config_dict)
    self.assertEqual(rendered_title, 'Your loaner is due on Friday')
    self.assertEqual(rendered_body, (
        '<html><body>'  # Includes the reminder_base template.
        'Hello, {}. Your loaner with serial number '
        '12345ABC is due on Friday, October 13. Return it by then if you ever '
        'want to see your pet turtle, Grumpy, again.'
        '</body></html>'.format(loanertest.USER_EMAIL)))

    # Without memcache
    memcache.flush_all()
    rendered_title, rendered_body = template_loader.render(
        'loaner_due', config_dict)
    self.assertEqual(rendered_title, 'Your loaner is due on Friday')
    self.assertEqual(rendered_body, (
        '<html><body>'
        'Hello, {}. Your loaner with serial number '
        '12345ABC is due on Friday, October 13. Return it by then if you ever '
        'want to see your pet turtle, Grumpy, again.'
        '</body></html>'.format(loanertest.USER_EMAIL))) 
Example 8
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 9
Project: kay-template   Author: yosukesuzuki   File: shell.py    MIT License 5 votes vote down vote up
def clear_datastore(appid=('a', ''), host=('h', ''), path=('p', ''),
                    kinds=('k', ''), clear_memcache=('c', False), secure=True):
  """Clear all the data on GAE environment using remote_api.
  """
  if not appid:
    appid = get_appid()
  if not host:
    host = "%s.appspot.com" % appid
  if not path:
    path = DEFAULT_REMOTE_API_PATH
  if not kinds:
    models = None
  else:
    models_dict = get_all_models_as_dict()
    models = []
    for kind in kinds.split(','):
      models.append(db.class_for_kind(kind))
      
  remote_api_stub.ConfigureRemoteApi(None, path, auth_func,
                                     host, secure=secure, save_cookies=True)
  remote_api_stub.MaybeInvokeAuthentication()
  delete_all_entities(models)
  if clear_memcache:
    from google.appengine.api import memcache
    memcache.flush_all()
    sys.stderr.write("Flushed memcache.\n") 
Example 10
Project: kay-template   Author: yosukesuzuki   File: ereporter_test.py    MIT License 5 votes vote down vote up
def test_ereporter(self):
    from kay.ext.ereporter.models import ExceptionRecord
    self.assertEqual(ExceptionRecord.all().count(), 0, "ExceptionRecord objects already exist!")

    response = self.client.get(url_for('ereporter_testapp/index'))
    self.assertEqual(response.status_code, 500, "Expected 500 error code.")
    self.assertEqual(ExceptionRecord.all().count(), 1)

    # Simulate the key expiring.
    memcache.flush_all();

    response = self.client.get(url_for('ereporter_testapp/index'))
    self.assertEqual(response.status_code, 500, "Expected 500 error code.")
    self.assertEqual(ExceptionRecord.all().count(), 1, "More than one ExceptionRecord object was created!")
    self.assertEqual(ExceptionRecord.all()[0].count, 2, "ExceptionRecord count not incremented!") 
Example 11
Project: kay-template   Author: yosukesuzuki   File: live_settings_test.py    MIT License 5 votes vote down vote up
def setUp(self):
    from google.appengine.api import memcache
    memcache.flush_all()
    s = LazySettings(settings_module='kay.tests.live_settings_settings')
    app = get_application(settings=s)
    self.client = Client(app, BaseResponse)

    live_settings.set("setting.1", "on")
    live_settings.set("setting.2", "off") 
Example 12
Project: kay-template   Author: yosukesuzuki   File: appstats_test.py    MIT License 5 votes vote down vote up
def setUp(self):
    from google.appengine.api import memcache
    memcache.flush_all()
    s = LazySettings(settings_module='kay.tests.appstats_settings')
    app = get_application(settings=s)
    self.client = Client(app, BaseResponse) 
Example 13
Project: kay-template   Author: yosukesuzuki   File: tests.py    MIT License 5 votes vote down vote up
def setUp(self):
    s = LazySettings(settings_module='kay.tests.cache_test.settings')
    self.app = get_application(settings=s)
    self.client = Client(self.app, BaseResponse)
    memcache.flush_all() 
Example 14
Project: mlab-ns   Author: m-lab   File: testutil.py    Apache License 2.0 5 votes vote down vote up
def setup_for_testing(require_indexes=True, define_queues=[]):
  """Sets up the stubs for testing.

  Args:
    require_indexes: True if indexes should be required for all indexes.
    define_queues: Additional queues that should be available.
  """
  from google.appengine.api import apiproxy_stub_map
  from google.appengine.api import memcache
  from google.appengine.api import queueinfo
  from google.appengine.tools import dev_appserver
  from google.appengine.tools import dev_appserver_index
  before_level = logging.getLogger().getEffectiveLevel()
  try:
    logging.getLogger().setLevel(100)
    root_path = os.path.realpath(os.path.dirname(__file__))
    dev_appserver.SetupStubs(
        TEST_APP_ID,
        root_path=root_path,
        login_url='',
        datastore_path=tempfile.mktemp(suffix='datastore_stub'),
        history_path=tempfile.mktemp(suffix='datastore_history'),
        blobstore_path=tempfile.mktemp(suffix='blobstore_stub'),
        require_indexes=require_indexes,
        clear_datastore=False)
    dev_appserver_index.SetupIndexes(TEST_APP_ID, root_path)
    # Actually need to flush, even though we've reallocated. Maybe because the
    # memcache stub's cache is at the module level, not the API stub?
    memcache.flush_all()
  finally:
    logging.getLogger().setLevel(before_level)

  taskqueue_stub = apiproxy_stub_map.apiproxy.GetStub('taskqueue')
  taskqueue_stub.queue_yaml_parser = (
      lambda x: queueinfo.LoadSingleQueue(
          'queue:\n- name: default\n  rate: 1/s\n' +
          '\n'.join('- name: %s\n  rate: 1/s' % name
                    for name in define_queues))) 
Example 15
Project: luci-py   Author: luci   File: handlers_endpoints_v1_test.py    Apache License 2.0 5 votes vote down vote up
def test_retrieve_db_ok(self):
    """Assert that content retrieval works for non-memcached DB entities."""
    content = 'Isabella, or the Pot of Basil'
    namespace = 'default'
    request = self.store_request(namespace, content)
    embedded = validate(
        request.upload_ticket, handlers_endpoints_v1.UPLOAD_MESSAGES[0])
    self.call_api('store_inline', message_to_dict(request), 200)
    retrieve_request = handlers_endpoints_v1.RetrieveRequest(
        digest=embedded['d'], namespace=handlers_endpoints_v1.Namespace())
    memcache.flush_all()
    response = self.call_api('retrieve', message_to_dict(retrieve_request), 200)
    retrieved = response.json
    self.assertEqual(content, base64.b64decode(retrieved[u'content'])) 
Example 16
Project: cocoslive   Author: ricardoquesada   File: utility.py    GNU General Public License v3.0 5 votes vote down vote up
def clear_memcache():
  """Flushes the memcache when an entry is edited."""
  if not memcache.flush_all():  # pylint: disable-msg=E1101
    logging.error('Failed to clear the cache!') 
Example 17
Project: cocoslive   Author: ricardoquesada   File: admin.py    GNU General Public License v3.0 5 votes vote down vote up
def get(self):
        status = memcache.flush_all()
        self.redirect('/admin/memcache' )
# 
#
# '/admin/list-devs' handler
# 
Example 18
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def post(self):
    """Handle POST."""
    if self.request.get('flush_memcache'):
      if memcache.flush_all():
        message = 'Cache flushed, all keys dropped.'
      else:
        message = 'Flushing the cache failed.  Please try again.'
      self.redirect_with_message(message)
      return

    kind = self.request.get('kind')



    keys = []
    index = 0
    num_keys = int(self.request.get('numkeys'))
    for i in xrange(1, num_keys+1):
      key = self.request.get('key%d' % i)
      if key:
        keys.append(key)

    if self.request.get('action') == 'Delete':
      num_deleted = 0

      for key in keys:
        datastore.Delete(datastore.Key(key))
        num_deleted = num_deleted + 1
      message = '%d entit%s deleted. %s' % (
        num_deleted, ('ies', 'y')[num_deleted == 1], _DATASTORE_CACHING_WARNING)
      self.redirect_with_message(message)
      return


    self.error(404) 
Example 19
Project: cloud-playground   Author: googlearchive   File: templates.py    Apache License 2.0 5 votes vote down vote up
def ClearCache():
  # TODO: determine why the just deleting our keys is insufficient:
  # memcache.delete_multi(keys=[_MEMCACHE_KEY_REPO_COLLECTIONS,
  #                       _MEMCACHE_KEY_TEMPLATES])
  memcache.flush_all() 
Example 20
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: memcache_viewer.py    Apache License 2.0 4 votes vote down vote up
def post(self):
    """Handle modifying actions and/or redirect to GET page."""
    super(MemcacheViewerRequestHandler, self).post()
    next_param = {}

    if self.request.get('action:flush'):
      if memcache.flush_all():
        next_param['message'] = 'Cache flushed, all keys dropped.'
      else:
        next_param['message'] = 'Flushing the cache failed.  Please try again.'

    elif self.request.get('action:display'):
      next_param['key'] = self.request.get('key')

    elif self.request.get('action:edit'):
      next_param['edit'] = self.request.get('key')

    elif self.request.get('action:delete'):
      key = self.request.get('key')
      result = memcache.delete(key)
      if result == memcache.DELETE_NETWORK_FAILURE:
        next_param['message'] = ('ERROR: Network failure, key "%s" not deleted.'
                                 % key)
      elif result == memcache.DELETE_ITEM_MISSING:
        next_param['message'] = 'Key "%s" not in cache.' % key
      elif result == memcache.DELETE_SUCCESSFUL:
        next_param['message'] = 'Key "%s" deleted.' % key
      else:
        next_param['message'] = ('Unknown return value.  Key "%s" might still '
                                 'exist.' % key)

    elif self.request.get('action:save'):
      key = self.request.get('key')
      value = self.request.get('value')
      type_ = self.request.get('type')
      next_param['key'] = key

      converter = self.FRIENDLY_TYPE_NAME_TO_CONVERTER[type_]
      try:
        memcache_value = converter.to_cache(value)
      except ValueError as e:
        next_param['message'] = 'ERROR: Failed to save key "%s": %s.' % (key, e)
      else:
        if self._set_memcache_value(key,
                                    memcache_value,
                                    converter.memcache_type):
          next_param['message'] = 'Key "%s" saved.' % key
        else:
          next_param['message'] = 'ERROR: Failed to save key "%s".' % key
    elif self.request.get('action:cancel'):
      next_param['key'] = self.request.get('key')
    else:
      next_param['message'] = 'Unknown action.'

    next = self.request.path_url
    if next_param:
      next = '%s?%s' % (next, self._urlencode(next_param))
    self.redirect(next) 
Example 21
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: __init__.py    Apache License 2.0 4 votes vote down vote up
def post(self):
    """Handle modifying actions and/or redirect to GET page."""
    next_param = {}

    if self.request.get('action:flush'):
      if memcache.flush_all():
        next_param['message'] = 'Cache flushed, all keys dropped.'
      else:
        next_param['message'] = 'Flushing the cache failed.  Please try again.'

    elif self.request.get('action:display'):
      next_param['key'] = self.request.get('key')

    elif self.request.get('action:edit'):
      next_param['edit'] = self.request.get('key')

    elif self.request.get('action:delete'):
      key = self.request.get('key')
      result = memcache.delete(key)
      if result == memcache.DELETE_NETWORK_FAILURE:
        next_param['message'] = ('ERROR: Network failure, key "%s" not deleted.'
                                 % key)
      elif result == memcache.DELETE_ITEM_MISSING:
        next_param['message'] = 'Key "%s" not in cache.' % key
      elif result == memcache.DELETE_SUCCESSFUL:
        next_param['message'] = 'Key "%s" deleted.' % key
      else:
        next_param['message'] = ('Unknown return value.  Key "%s" might still '
                                 'exist.' % key)

    elif self.request.get('action:save'):
      key = self.request.get('key')
      value = self.request.get('value')
      type_ = self.request.get('type')
      next_param['key'] = key
      try:
        if self._SetValue(key, type_, value):
          next_param['message'] = 'Key "%s" saved.' % key
        else:
          next_param['message'] = 'ERROR: Failed to save key "%s".' % key
      except ValueError, e:
        next_param['message'] = 'ERROR: Unable to encode value: %s' % e