go-cache | memory key : value store | Key Value Database library
kandi X-RAY | go-cache Summary
Support
Quality
Security
License
Reuse
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here
go-cache Key Features
go-cache Examples and Code Snippets
Trending Discussions on go-cache
Trending Discussions on go-cache
QUESTION
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
- Buy Products
\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
\nUser name: \n
\nAdress: \n
\nMobile: \n
\nQty:
\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:37Since 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")
QUESTION
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:53Instead 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 .
QUESTION
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- 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.
- Have you downloaded Memcached and started it? Are you sure there's a Memcached instance listening?
QUESTION
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:02go conditional statements follows the following syntax
if something{
......
} else if something{
......
} else{
......
}
QUESTION
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:54With 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)
}
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install go-cache
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page