go-cache | memory key : value store | Key Value Database library

 by   patrickmn Go Version: v2.1.0 License: MIT

kandi X-RAY | go-cache Summary

go-cache is a Go library typically used in Database, Key Value Database applications. go-cache has no bugs, it has no vulnerabilities, it has a Permissive License and it has medium support. You can download it from GitHub.
An in-memory key:value store/cache (similar to Memcached) library for Go, suitable for single-machine applications.
    Support
      Quality
        Security
          License
            Reuse
            Support
              Quality
                Security
                  License
                    Reuse

                      kandi-support Support

                        summary
                        go-cache has a medium active ecosystem.
                        summary
                        It has 6984 star(s) with 824 fork(s). There are 116 watchers for this library.
                        summary
                        It had no major release in the last 12 months.
                        summary
                        There are 32 open issues and 54 have been closed. On average issues are closed in 198 days. There are 37 open pull requests and 0 closed requests.
                        summary
                        It has a neutral sentiment in the developer community.
                        summary
                        The latest version of go-cache is v2.1.0
                        go-cache Support
                          Best in #Key Value Database
                            Average in #Key Value Database
                            go-cache Support
                              Best in #Key Value Database
                                Average in #Key Value Database

                                  kandi-Quality Quality

                                    summary
                                    go-cache has 0 bugs and 0 code smells.
                                    go-cache Quality
                                      Best in #Key Value Database
                                        Average in #Key Value Database
                                        go-cache Quality
                                          Best in #Key Value Database
                                            Average in #Key Value Database

                                              kandi-Security Security

                                                summary
                                                go-cache has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
                                                summary
                                                go-cache code analysis shows 0 unresolved vulnerabilities.
                                                summary
                                                There are 0 security hotspots that need review.
                                                go-cache Security
                                                  Best in #Key Value Database
                                                    Average in #Key Value Database
                                                    go-cache Security
                                                      Best in #Key Value Database
                                                        Average in #Key Value Database

                                                          kandi-License License

                                                            summary
                                                            go-cache is licensed under the MIT License. This license is Permissive.
                                                            summary
                                                            Permissive licenses have the least restrictions, and you can use them in most projects.
                                                            go-cache License
                                                              Best in #Key Value Database
                                                                Average in #Key Value Database
                                                                go-cache License
                                                                  Best in #Key Value Database
                                                                    Average in #Key Value Database

                                                                      kandi-Reuse Reuse

                                                                        summary
                                                                        go-cache releases are available to install and integrate.
                                                                        summary
                                                                        Installation instructions, examples and code snippets are available.
                                                                        summary
                                                                        It has 2759 lines of code, 178 functions and 4 files.
                                                                        summary
                                                                        It has high code complexity. Code complexity directly impacts maintainability of the code.
                                                                        go-cache Reuse
                                                                          Best in #Key Value Database
                                                                            Average in #Key Value Database
                                                                            go-cache Reuse
                                                                              Best in #Key Value Database
                                                                                Average in #Key Value Database
                                                                                  Top functions reviewed by kandi - BETA
                                                                                  kandi's functional review helps you automatically verify the functionalities of the libraries and avoid rework.
                                                                                  Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here
                                                                                  Get all kandi verified functions for this library.
                                                                                  Get all kandi verified functions for this library.

                                                                                  go-cache Key Features

                                                                                  An in-memory key:value store/cache (similar to Memcached) library for Go, suitable for single-machine applications.

                                                                                  go-cache Examples and Code Snippets

                                                                                  No Code Snippets are available at this moment for go-cache.
                                                                                  Community Discussions

                                                                                  Trending Discussions on go-cache

                                                                                  How to invalidate a view cache using django-cacheops
                                                                                  chevron right
                                                                                  Can't compile when using archive/tar
                                                                                  chevron right
                                                                                  Django MemcacheUnexpectedCloseError and [WinError 10061] No connection could be made because the target machine actively refused it
                                                                                  chevron right
                                                                                  Function won't work with if else statements
                                                                                  chevron right
                                                                                  Error trying to use an empty interface parameter for returning data
                                                                                  chevron right

                                                                                  QUESTION

                                                                                  How to invalidate a view cache using django-cacheops
                                                                                  Asked 2022-Mar-19 at 15:05

                                                                                  I have a view and I cached it in views.py using django-cacheops (https://github.com/Suor/django-cacheops):

                                                                                  @cached_view(timeout=60*15)
                                                                                  @csrf_exempt
                                                                                  def order(request, usr):
                                                                                      ...
                                                                                  

                                                                                  The regex for order view in urls.py:

                                                                                  url(r'^order/(?P\D+)$', views.order, name='ord')
                                                                                  # Example Url: http://127.0.0.1:8000/order/demo (demo is the user name)
                                                                                  

                                                                                  And I want to invalidate the cached view order inside the below view:

                                                                                  @login_required 
                                                                                  def available(request, pk, avail):
                                                                                      pk = int(pk)
                                                                                      avail = strtobool(avail)
                                                                                      if avail:
                                                                                          Product.objects.filter(id = pk).update(available = True)
                                                                                      else:
                                                                                          Product.objects.filter(id = pk).update(available = False)
                                                                                      return HttpResponseRedirect(reverse_lazy('yc')) 
                                                                                  

                                                                                  According to the docs, we can achieve this by doing:

                                                                                  @login_required 
                                                                                  def available(request, pk, avail):
                                                                                      pk = int(pk)
                                                                                      avail = strtobool(avail)
                                                                                      if avail:
                                                                                          Product.objects.filter(id = pk).update(available = True)
                                                                                          order.invalidate("http://127.0.0.1:8000/order/demo", "demo")
                                                                                          #it's a dummy url I've handled it dynamically in my code
                                                                                      else:
                                                                                          Product.objects.filter(id = pk).update(available = False)
                                                                                          order.invalidate("http://127.0.0.1:8000/order/demo", "demo")
                                                                                          #it's a dummy url I've handled it dynamically in my code
                                                                                      return HttpResponseRedirect(reverse_lazy('yc')) 
                                                                                  

                                                                                  But it's not working. Here are my logs using redis-cli monitor:

                                                                                  1647434341.849096 [1 [::1]:59650] "GET" "c:af687d461ec8bb3c48f6392010e54778"
                                                                                  1647434341.866966 [1 [::1]:59650] "SETEX" "c:af687d461ec8bb3c48f6392010e54778" "900" "\x80\x04\x95\xfa\b\x00\x00\x00\x00\x00\x00\x8c\x14django.http.response\x94\x8c\x0cHttpResponse\x94\x93\x94)\x81\x94}\x94(\x8c\b_headers\x94}\x94\x8c\x0ccontent-type\x94\x8c\x0cContent-Type\x94\x8c\x18text/html; charset=utf-8\x94\x86\x94s\x8c\x11_closable_objects\x94]\x94\x8c\x0e_handler_class\x94N\x8c\acookies\x94\x8c\x0chttp.cookies\x94\x8c\x0cSimpleCookie\x94\x93\x94)\x81\x94\x8c\x06closed\x94\x89\x8c\x0e_reason_phrase\x94N\x8c\b_charset\x94N\x8c\n_container\x94]\x94B\xed\a\x00\x00\n\n\n  \n    \n    Buy Products\n    \n    \n    \n  \n  \n      \n        \n          
                                                                                    
                                                                                    \n
                                                                                  1. Buy Products
                                                                                  2. \n
                                                                                  \n \n \n

                                                                                  Name: \n Product Name: Redmi note 5 \n MRP: 100000 \n Discounted Price: 45678 \n Description: It's good phone too\n\n Product Name: xiomi 2 \n MRP: 10000 \n Discounted Price: 200 \n Description: xyz\n\n Product Name: mouse \n MRP: 1400 \n Discounted Price: 200 \n Description: xyzat\n\n

                                                                                  \n

                                                                                  User name: \n

                                                                                  \n

                                                                                  Adress: \n

                                                                                  \n

                                                                                  Mobile: \n

                                                                                  \n

                                                                                  Qty:

                                                                                  \n Buy\n \n \n \n \n \n \n \n \n\n\x94aub." 1647434354.133804 [1 [::1]:59650] "DEL" "c:94c7a9e7f6c7a45ee645caa02f53d000"

                                                                                  It looks like it's deleting some other cache.

                                                                                  I've also raised the issue in the repo of django-cache, you can check it for more information: https://github.com/Suor/django-cacheops/issues/425

                                                                                  ANSWER

                                                                                  Answered 2022-Mar-19 at 14:37

                                                                                  Since you used a named group usr in your regex, Django passes it as a keyword argument:

                                                                                  url(r'^order/(?P\D+)$', views.order, name='ord')
                                                                                  

                                                                                  But you are trying to invalidate the cache with a positional argument:

                                                                                  order.invalidate("http://127.0.0.1:8000/order/demo", "demo")
                                                                                  

                                                                                  Instead, invalidate it with the corresponding keyword argument:

                                                                                  order.invalidate("http://127.0.0.1:8000/order/demo", usr="demo")
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/71510217

                                                                                  QUESTION

                                                                                  Can't compile when using archive/tar
                                                                                  Asked 2022-Jan-28 at 21:53

                                                                                  I am trying to use archive/tar within my Golang project. However, when I compile it, I get the following error:

                                                                                  /usr/local/go/pkg/tool/linux_amd64/link: /go-cache/10/1020ddd253c007d4f0bbed6c73d75297ac475bbc40d485e357efc1e7584bc24f-d(_go_.o): cannot use dynamic imports with -d flag
                                                                                  /usr/local/go/pkg/tool/linux_amd64/link: /go-cache/73/735aa16c44473681079e1f6b4a517de41fcac801aa803f5f84f6ebcb6436f3e6-d(_go_.o): cannot use dynamic imports with -d flag
                                                                                  

                                                                                  Here is how I am compiling my project, within an golang:1.17-alpine3.14 Docker container:

                                                                                  go build -ldflags "-d -X main.Something=$SOMETHING -X main.Another=$ANOTHER -linkmode external -extldflags -static" -tags netgo -o prog cmd/prog/*.go
                                                                                  

                                                                                  Without the import, everything compiles fine. All I need to do to trigger this is the following:

                                                                                  import (
                                                                                      archive/tar
                                                                                      ...
                                                                                  )
                                                                                  ...
                                                                                  
                                                                                  func someFunc() {
                                                                                      ...
                                                                                      tarWriter := tar.NewWriter(file)
                                                                                      defer tarWriter.Close()
                                                                                  }
                                                                                  
                                                                                  

                                                                                  Allowing this to be dynamically linked isn't something I can do, given requirements of the program. How can I get this to link statically?

                                                                                  ANSWER

                                                                                  Answered 2022-Jan-28 at 21:53

                                                                                  Instead of using -ldflags to avoid your program being dynamically linked, you can just disable it through the environment:

                                                                                  CGO_ENABLED=0 go build -ldflags "-X main.Something=$SOMETHING -X main.Another=$ANOTHER" -o prog $PACKAGE_PATH
                                                                                  

                                                                                  E.g, this minimal (panicking) program:

                                                                                  package main
                                                                                  
                                                                                  import (
                                                                                      "archive/tar"
                                                                                  )
                                                                                  
                                                                                  func main() {
                                                                                      tarWriter := tar.NewWriter(nil)
                                                                                      defer tarWriter.Close()
                                                                                  }
                                                                                  

                                                                                  compiles perfectly with:

                                                                                  CGO_ENABLED=0  go build -o prog .
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/70899991

                                                                                  QUESTION

                                                                                  Django MemcacheUnexpectedCloseError and [WinError 10061] No connection could be made because the target machine actively refused it
                                                                                  Asked 2021-Aug-02 at 11:11

                                                                                  Hi I am new at django and trying to use django-cache to speed up page load that will list out 100 companies and their details per page but I am constantly running into errors. When I use the IP and Port from the django doc 127.0.0.1:11211 I get this error:

                                                                                  Environment:
                                                                                  
                                                                                  
                                                                                  Request Method: GET
                                                                                  Request URL: http://127.0.0.1:8000/
                                                                                  
                                                                                  Django Version: 3.2.4
                                                                                  Python Version: 3.9.1
                                                                                  Installed Applications:
                                                                                  ('django.contrib.admin',
                                                                                   'django.contrib.auth',
                                                                                   'django.contrib.contenttypes',
                                                                                   'django.contrib.sessions',
                                                                                   'django.contrib.messages',
                                                                                   'django.contrib.staticfiles',
                                                                                   'debug_toolbar',
                                                                                   'mailer')
                                                                                  Installed Middleware:
                                                                                  ('django.contrib.sessions.middleware.SessionMiddleware',
                                                                                   'django.middleware.common.CommonMiddleware',
                                                                                   'django.middleware.csrf.CsrfViewMiddleware',
                                                                                   'django.contrib.auth.middleware.AuthenticationMiddleware',
                                                                                   'django.contrib.messages.middleware.MessageMiddleware',
                                                                                   'django.middleware.clickjacking.XFrameOptionsMiddleware',
                                                                                   'debug_toolbar.middleware.DebugToolbarMiddleware')
                                                                                  
                                                                                  
                                                                                  
                                                                                  Traceback (most recent call last):
                                                                                    File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
                                                                                      response = get_response(request)
                                                                                    File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
                                                                                      response = wrapped_callback(request, *callback_args, **callback_kwargs)
                                                                                    File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\decorators.py", line 122, in _wrapped_view
                                                                                      result = middleware.process_request(request)
                                                                                    File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\middleware\cache.py", line 145, in process_request
                                                                                      cache_key = get_cache_key(request, self.key_prefix, 'GET', cache=self.cache)
                                                                                    File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\cache.py", line 362, in get_cache_key
                                                                                      headerlist = cache.get(cache_key)
                                                                                    File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\cache\backends\memcached.py", line 77, in get
                                                                                      return self._cache.get(key, default)
                                                                                    File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\hash.py", line 361, in get
                                                                                      return self._run_cmd('get', key, None, *args, **kwargs)
                                                                                    File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\hash.py", line 334, in _run_cmd
                                                                                      return self._safely_run_func(
                                                                                    File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\hash.py", line 214, in _safely_run_func
                                                                                      result = func(*args, **kwargs)
                                                                                    File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\base.py", line 619, in get
                                                                                      return self._fetch_cmd(b'get', [key], False).get(key, default)
                                                                                    File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\base.py", line 1018, in _fetch_cmd
                                                                                      self._connect()
                                                                                    File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\base.py", line 420, in _connect
                                                                                      sock.connect(sockaddr)
                                                                                  
                                                                                  Exception Type: ConnectionRefusedError at /
                                                                                  Exception Value: [WinError 10061] No connection could be made because the target machine actively refused it
                                                                                  

                                                                                  And if I use IP and Port given in web browser 127.0.0.1:8000 I get this error:

                                                                                  Environment:
                                                                                  
                                                                                  
                                                                                  Request Method: GET
                                                                                  Request URL: http://127.0.0.1:8000/
                                                                                  
                                                                                  Django Version: 3.2.4
                                                                                  Python Version: 3.9.1
                                                                                  Installed Applications:
                                                                                  ('django.contrib.admin',
                                                                                   'django.contrib.auth',
                                                                                   'django.contrib.contenttypes',
                                                                                   'django.contrib.sessions',
                                                                                   'django.contrib.messages',
                                                                                   'django.contrib.staticfiles',
                                                                                   'debug_toolbar',
                                                                                   'mailer')
                                                                                  Installed Middleware:
                                                                                  ('django.contrib.sessions.middleware.SessionMiddleware',
                                                                                   'django.middleware.common.CommonMiddleware',
                                                                                   'django.middleware.csrf.CsrfViewMiddleware',
                                                                                   'django.contrib.auth.middleware.AuthenticationMiddleware',
                                                                                   'django.contrib.messages.middleware.MessageMiddleware',
                                                                                   'django.middleware.clickjacking.XFrameOptionsMiddleware',
                                                                                   'debug_toolbar.middleware.DebugToolbarMiddleware')
                                                                                  
                                                                                  
                                                                                  
                                                                                  Traceback (most recent call last):
                                                                                    File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
                                                                                      response = get_response(request)
                                                                                    File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
                                                                                      response = wrapped_callback(request, *callback_args, **callback_kwargs)
                                                                                    File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\decorators.py", line 122, in _wrapped_view
                                                                                      result = middleware.process_request(request)
                                                                                    File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\middleware\cache.py", line 145, in process_request
                                                                                      cache_key = get_cache_key(request, self.key_prefix, 'GET', cache=self.cache)
                                                                                    File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\cache.py", line 362, in get_cache_key
                                                                                      headerlist = cache.get(cache_key)
                                                                                    File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\cache\backends\memcached.py", line 77, in get
                                                                                      return self._cache.get(key, default)
                                                                                    File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\hash.py", line 361, in get
                                                                                      return self._run_cmd('get', key, None, *args, **kwargs)
                                                                                    File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\hash.py", line 334, in _run_cmd
                                                                                      return self._safely_run_func(
                                                                                    File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\hash.py", line 214, in _safely_run_func
                                                                                      result = func(*args, **kwargs)
                                                                                    File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\base.py", line 619, in get
                                                                                      return self._fetch_cmd(b'get', [key], False).get(key, default)
                                                                                    File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\base.py", line 1027, in _fetch_cmd
                                                                                      buf, line = _readline(self.sock, buf)
                                                                                    File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\base.py", line 1440, in _readline
                                                                                      raise MemcacheUnexpectedCloseError()
                                                                                  
                                                                                  Exception Type: MemcacheUnexpectedCloseError at /
                                                                                  Exception Value:
                                                                                  

                                                                                  I just cant figure out whats wrong please help. Here are some of my python files:

                                                                                  views.py

                                                                                  from django.views.generic import ListView
                                                                                  
                                                                                  from mailer.models import Company
                                                                                  
                                                                                  
                                                                                  class IndexView(ListView):
                                                                                      template_name = "mailer/index.html"
                                                                                      model = Company
                                                                                      paginate_by = 100
                                                                                  

                                                                                  settings.py

                                                                                  
                                                                                  
                                                                                  # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
                                                                                  import os
                                                                                  from pathlib import Path
                                                                                  
                                                                                  
                                                                                  # Build paths inside the project like this: BASE_DIR / 'subdir'.
                                                                                  BASE_DIR = Path(__file__).resolve().parent.parent
                                                                                  
                                                                                  SECRET_KEY = someKey
                                                                                  
                                                                                  DEBUG = True
                                                                                  TEMPLATE_DEBUG = True
                                                                                  ALLOWED_HOSTS = []
                                                                                  INTERNAL_IPS = ['127.0.0.1', '0.0.0.0']
                                                                                  
                                                                                  INSTALLED_APPS = (
                                                                                      'django.contrib.admin',
                                                                                      'django.contrib.auth',
                                                                                      'django.contrib.contenttypes',
                                                                                      'django.contrib.sessions',
                                                                                      'django.contrib.messages',
                                                                                      'django.contrib.staticfiles',
                                                                                      'debug_toolbar',
                                                                                      'mailer',
                                                                                      #'mailer.management.commands.datafeeder',
                                                                                  )
                                                                                  
                                                                                  MIDDLEWARE = (
                                                                                      'django.contrib.sessions.middleware.SessionMiddleware',
                                                                                      'django.middleware.common.CommonMiddleware',
                                                                                      'django.middleware.csrf.CsrfViewMiddleware',
                                                                                      'django.contrib.auth.middleware.AuthenticationMiddleware',
                                                                                      'django.contrib.messages.middleware.MessageMiddleware',
                                                                                      'django.middleware.clickjacking.XFrameOptionsMiddleware',
                                                                                      'debug_toolbar.middleware.DebugToolbarMiddleware',
                                                                                      # 'django.middleware.cache.UpdateCacheMiddleware',
                                                                                      # 'django.middleware.common.CommonMiddleware',
                                                                                      # 'django.middleware.cache.FetchFromCacheMiddleware',
                                                                                  )
                                                                                  
                                                                                  ROOT_URLCONF = 'djangochallenge.urls'
                                                                                  
                                                                                  TEMPLATES = [
                                                                                      {
                                                                                          'BACKEND': 'django.template.backends.django.DjangoTemplates',
                                                                                          'DIRS': [],
                                                                                          'APP_DIRS': True,
                                                                                          'OPTIONS': {
                                                                                              'context_processors': [
                                                                                                  'django.template.context_processors.debug',
                                                                                                  'django.template.context_processors.request',
                                                                                                  'django.contrib.auth.context_processors.auth',
                                                                                                  'django.contrib.messages.context_processors.messages',
                                                                                              ],
                                                                                          },
                                                                                      },
                                                                                  ]
                                                                                  
                                                                                  WSGI_APPLICATION = 'djangochallenge.wsgi.application'
                                                                                  
                                                                                  DATABASES = {
                                                                                      'default': {
                                                                                          'ENGINE': 'django.db.backends.sqlite3',
                                                                                          'NAME': BASE_DIR / 'db.sqlite3',
                                                                                      }
                                                                                  }
                                                                                  
                                                                                  AUTH_PASSWORD_VALIDATORS = [
                                                                                      {
                                                                                          'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
                                                                                      },
                                                                                      {
                                                                                          'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
                                                                                      },
                                                                                      {
                                                                                          'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
                                                                                      },
                                                                                      {
                                                                                          'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
                                                                                      },
                                                                                  ]
                                                                                  
                                                                                  
                                                                                  STATIC_URL = '/static/'
                                                                                  LANGUAGE_CODE = 'en-us'
                                                                                  TIME_ZONE = 'UTC'
                                                                                  USE_I18N = True
                                                                                  USE_L10N = True
                                                                                  USE_TZ = True
                                                                                  
                                                                                  STATIC_URL = '/static/'
                                                                                  
                                                                                  DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
                                                                                  
                                                                                  
                                                                                  CACHES = {
                                                                                      'default': {
                                                                                          'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache',
                                                                                          'LOCATION': '127.0.0.1:8000',
                                                                                      }
                                                                                  }
                                                                                  

                                                                                  urls.py

                                                                                  
                                                                                  from django.conf.urls import include, url
                                                                                  from django.views.decorators.cache import cache_page
                                                                                  from mailer.views import IndexView
                                                                                  
                                                                                  app_name = 'mailer'
                                                                                  
                                                                                  urlpatterns = [
                                                                                      url(r'^$', cache_page(60*60)(IndexView.as_view()), name="index"),
                                                                                  ]
                                                                                  
                                                                                  

                                                                                  Please let me know if anything more is required to answer this question.

                                                                                  ANSWER

                                                                                  Answered 2021-Aug-02 at 11:11
                                                                                  1. You've configured your cache backend to use a Memcached server at 127.0.0.1:8000. That's likely a misconfiguration, since your Django development server would run at 127.0.0.1:8000 by default. The default port for Memcached is 11211 – you might want 127.0.0.1:11211.
                                                                                  2. Have you downloaded Memcached and started it? Are you sure there's a Memcached instance listening?

                                                                                  Source https://stackoverflow.com/questions/68620512

                                                                                  QUESTION

                                                                                  Function won't work with if else statements
                                                                                  Asked 2021-Jan-15 at 12:02

                                                                                  I'm trying to build a basic cache system with Go as a tutorial.

                                                                                  For some reason when I run this, the if else statement leads to a error.

                                                                                  package datasource
                                                                                  
                                                                                  import (
                                                                                      "fmt"
                                                                                      "github.com/patrickmn/go-cache"
                                                                                      "time"
                                                                                  )
                                                                                  
                                                                                  type DataSource interface {
                                                                                      Value(key string) (interface{}, error)
                                                                                  
                                                                                  }
                                                                                  
                                                                                  // DataSourceStr type, implements the DataSource interface
                                                                                  type DataSourceStr struct {
                                                                                      data map[string]string
                                                                                  }
                                                                                  
                                                                                  
                                                                                  var cache = cache.New(5*time.Minute, 5*time.Minute)
                                                                                  
                                                                                  
                                                                                  func (n *DataSourceStr) Value(key string) (interface{}, error) {
                                                                                          /* 
                                                                                      1. Compute a cache key
                                                                                      2. Search cache key
                                                                                      3. If hit return value
                                                                                      4. If miss, do datasource
                                                                                      5. Cache and return slow thing.
                                                                                      */
                                                                                      
                                                                                      cached, found := cache.Value(key)
                                                                                      if found {
                                                                                          return cached, nil
                                                                                      }
                                                                                  
                                                                                      else if _, ok := n.data[key]; ok 
                                                                                      {
                                                                                          //measure how often a key gets called.
                                                                                          cache.Set(key, n.data[key], cache.DefaultExpiration)
                                                                                          return n.data[key], nil
                                                                                      } else {
                                                                                          return nil, fmt.Errorf("key not found %v", ok)
                                                                                      }
                                                                                  }
                                                                                  
                                                                                  
                                                                                  
                                                                                  
                                                                                  func getFromDS(datasource DataSource, key string) (string, error) {
                                                                                  
                                                                                      
                                                                                      v, err := datasource.Value(key)
                                                                                      
                                                                                      //create a map that decays based on time.
                                                                                  
                                                                                      if err != nil {
                                                                                          return "", nil
                                                                                      }
                                                                                  
                                                                                      return fmt.Sprint(v), nil
                                                                                  }
                                                                                  

                                                                                  What am I doing wrong? I am trying to have a key entered, then return the value from either the cache or the database. Not sure what I've done wrong with the syntax!

                                                                                  ANSWER

                                                                                  Answered 2021-Jan-15 at 12:02

                                                                                  go conditional statements follows the following syntax

                                                                                     if something{
                                                                                        ......
                                                                                  
                                                                                     } else if something{
                                                                                        ......
                                                                                  
                                                                                     } else{
                                                                                        ......
                                                                                     }
                                                                                  
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/65732111

                                                                                  QUESTION

                                                                                  Error trying to use an empty interface parameter for returning data
                                                                                  Asked 2021-Jan-02 at 10:08

                                                                                  I'm trying to write a wrap around a function that uses an interface{} parameter to return data, by adding cache.

                                                                                  My problem is that once I have a valid interface{} I don't know how to assign it to be returned in the parameter. The wrapped call is (github.Client) .Do in github API client and the problem hit me when I tried to add caching with go-cache

                                                                                  This somewhat my function

                                                                                  func (c *cachedClient) requestAPI(url string, v interface{}) error {
                                                                                      x, found := c.cache.Get(url)
                                                                                      if found {                        // Found in cache code
                                                                                          log.Printf("cached: %v", x)
                                                                                          v = x // HERE: this do not work. x contains a valid copy of what I want but how do I store it in v?
                                                                                          return nil
                                                                                      }
                                                                                      req, _ := c.githubClient.NewRequest("GET", url, nil)    // not found I cache, request it
                                                                                      res, err := c.githubClient.Do(*c.context, req, v)
                                                                                      if err != nil {
                                                                                          return err
                                                                                      }
                                                                                      if res.StatusCode != 200 {
                                                                                          return fmt.Errorf("Error Getting %v: %v", url, res.Status)
                                                                                      }
                                                                                      c.cache.Add(url, v, cache.DefaultExpiration)   // store in cache
                                                                                      return nil    // once here v works as expected and contain a valid item
                                                                                  }
                                                                                  

                                                                                  It fails when has to return a cached value when I try to use it like this:

                                                                                  // Some init code c is a cachedClient 
                                                                                  i := new(github.Issue)
                                                                                  
                                                                                  c.requestAPI(anAPIValidURLforAnIssue, i)
                                                                                  log.Printf("%+v", i)    // var i correctly contains an issue from the github api
                                                                                  
                                                                                  o := new(github.Issue)
                                                                                  c.requestAPI(anAPIValidURLforAnIssue, o)
                                                                                  log.Printf("%+v", o)  // var o should have been get from the cache but here is empty
                                                                                  

                                                                                  So basically my problem is that when I correctly recover a cached item it is good but I can not store it in the parameter meant to be used to store it. I can not work with subclasses because the call I'm wrapping is using an interface{} already. And I can not move it to return values because you can't return a generic interface. How do I make the interface{} x be stored in v to have it available outside?

                                                                                  ANSWER

                                                                                  Answered 2021-Jan-01 at 04:54

                                                                                  With certain assumptions like you are storing json data in your cache below is how I will try. Errors not handled.

                                                                                  package main
                                                                                  
                                                                                  import (
                                                                                      "encoding/json"
                                                                                      "fmt"
                                                                                  )
                                                                                  
                                                                                  type Data struct {
                                                                                      Name string
                                                                                  }
                                                                                  
                                                                                  func main() {
                                                                                      var d Data
                                                                                      requestAPI(&d)
                                                                                      fmt.Println(d)
                                                                                  }
                                                                                  
                                                                                  func requestAPI(v interface{}) {
                                                                                      var cache_res interface{} = []byte("{\"Name\":\"CCC\"}")
                                                                                      //assume you got cache_res from cache
                                                                                      x, _ := cache_res.([]byte)
                                                                                      _ = json.Unmarshal(x, &v)
                                                                                  }
                                                                                  

                                                                                  Actually above is what githubClient.Do is also doing. It checks whether v satisfies io.Writer interface, if yes write data to v. If not then it unmarshals json into v as shown above. So same can be done from cache.

                                                                                  Check here: https://github.com/google/go-github/blob/v32.1.0/github/github.go#L586

                                                                                  If the cache object is specific then below can be used. You don't deal with empty interface{} because you should be able to pass your specific type to c.githubClient.Do as v. Since it uses json package, it will detect the type information and accordingly fill the values into it. Lets say you store type Data struct

                                                                                  In below code other details eliminated like condition checking whether to cache & error handling

                                                                                  package main
                                                                                  
                                                                                  import (
                                                                                      "fmt"
                                                                                  )
                                                                                  
                                                                                  type Data struct {
                                                                                      Name string
                                                                                  }
                                                                                  
                                                                                  func main() {
                                                                                      var d Data
                                                                                      requestAPI(&d)
                                                                                      fmt.Println(d)
                                                                                  }
                                                                                  
                                                                                  func requestAPI(v *Data) {
                                                                                      var cache_res interface{} = Data{"CCC"}
                                                                                      //assume you got cache_res from cache
                                                                                      x, _ := cache_res.(Data)
                                                                                      *v = x
                                                                                  
                                                                                      //in case you did not find it in cache then githubClient.Do should unmarshal
                                                                                      //contents of response body into v *Data if Data fields match that of json
                                                                                      //res, err := c.githubClient.Do(*c.context, req, v)
                                                                                  }
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/65520910

                                                                                  Community Discussions, Code Snippets contain sources that include Stack Exchange Network

                                                                                  Vulnerabilities

                                                                                  No vulnerabilities reported

                                                                                  Install go-cache

                                                                                  You can download it from GitHub.

                                                                                  Support

                                                                                  For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .
                                                                                  Find more information at:
                                                                                  Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
                                                                                  Find more libraries
                                                                                  Explore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
                                                                                  Save this library and start creating your kit
                                                                                  CLONE
                                                                                • HTTPS

                                                                                  https://github.com/patrickmn/go-cache.git

                                                                                • CLI

                                                                                  gh repo clone patrickmn/go-cache

                                                                                • sshUrl

                                                                                  git@github.com:patrickmn/go-cache.git

                                                                                • Share this Page

                                                                                  share link

                                                                                  Explore Related Topics

                                                                                  Reuse Pre-built Kits with go-cache

                                                                                  Consider Popular Key Value Database Libraries

                                                                                  etcd

                                                                                  by etcd-io

                                                                                  leveldb

                                                                                  by google

                                                                                  bolt

                                                                                  by boltdb

                                                                                  ssdb

                                                                                  by ideawu

                                                                                  go-cache

                                                                                  by patrickmn

                                                                                  Try Top Libraries by patrickmn

                                                                                  cpuburn

                                                                                  by patrickmnGo

                                                                                  sortutil

                                                                                  by patrickmnGo

                                                                                  osg

                                                                                  by patrickmnGo

                                                                                  ocp

                                                                                  by patrickmnGo

                                                                                  go-bloom

                                                                                  by patrickmnGo

                                                                                  Compare Key Value Database Libraries with Highest Support

                                                                                  Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
                                                                                  Find more libraries
                                                                                  Explore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
                                                                                  Save this library and start creating your kit