I have Django 1.4 cache enabled with Redis as backend.I would like to know which view belongs to my cache key?
:1:views.decorators.cache.cache_page.mysite.GET.077b0d695a2095e154185234de17ad3350.d669abb4a2a0575f43321342f66b.fr
I know it is a template:
In [2]: r = redis.StrictRedis(host='localhost', port=6379, db=1)
In [3]: dd = r.get('':1:views.decorators.cache.cache_page.mysite.GET.077b0d695a2095e154185234de17ad3350.d669abb4a2a0575f43321342f66b.fr'')
In [6]: obj = cPickle.loads(dd)
In [7]: obj
Out[7]: <django.template.response.TemplateResponse object at 0x2a47050>
Is there a way to render this template to see what's inside also?
I tried
obj.render()
print(obj.content)
but i got some strange characters.
You are probably using the Gzip middleware.
Either remove it or use the gzip module do unpack the content.
Related
I have a Flask web app where I need two use two existing databases. The first database (DB-A) is used only for reading data (not writing permissions). The second database (DB-B) I am allowed read/write.
I can read DB-A using automap extension
from sqlalchemy.ext.automap import automap_base
Base = automap_base()
Base.prepare(db.engine, reflect=True)
DB-A = Base.classes.visitors
Reading and writing in DB-B I do ti with sqlalchemy common ORM
SQLALCHEMY_DATABASE_URI = ""
db = SQLAlchemy(app)
According to the documentation SQLALCHEMY_BINDS should do the work, but I cannt find anything about, how can I tell my automap engine to read a specific database.
my question is, how can I use automap for reading DB-A along with NOT-automap for writing in DB-B?
Thanks
Have you seen this part of the documentation in Flask explaining how to bind multiple databases?
Quote from documentation:
SQLALCHEMY_DATABASE_URI = 'postgres://localhost/main'
SQLALCHEMY_BINDS = {
'users': 'mysqldb://localhost/users',
'appmeta': 'sqlite:////path/to/appmeta.db'
}
And when this is setup, you can use the following (also quote from documentation):
>>> db.create_all()
>>> db.create_all(bind=['users'])
>>> db.create_all(bind='appmeta')
>>> db.drop_all(bind=None)
I need to get original uri template with regex from resolve function in view or middleware. For example:
def view(request):
uri_path = resolve(request...)
# and uri_path must be equals something like 'articles/<int:year>/<int:month>/'
...
Is this possible? I didn't found information about this
You are probably looking for PATH_INFO from the request object.
Try this -
request.META['PATH_INFO']
You can look for other info present at request META -
meta = request.META
for k, v in meta.items():
print(f"{k}\t{v}")
To get the resolve path, try below -
from django.urls import resolve
r = resolve(request.META['PATH_INFO'])
print(r.route) # will print like /office/employee/<int:eid>
Doc
So, i've found what i've searching for - documentation. But the problem is that this API new in django 2.2, i have an older django
I have a series of caches which follow this pattern:
key_x_y = value
Like:
'key_1_3' = 'foo'
'key_2_5' = 'bar'
'key_1_7' = 'baz'
Now I'm wondering how can I iterate over all keys to match pattern like key_1_* to get foo and baz using the native django cache.get()?
(I know that there are way, particularly for redis, that allow using more extensive api like iterate, but I'd like to stick to vanilla django cache, if possible)
This is not possible using standard Django's cache wrapper. As the feature to search keys by pattern is a backend dependent operation and not supported by all the cache backends used by Django (e.g. memcached does not support it but Redis does). So you will have to use a custom cache wrapper with cache backend that supports this operation.
Edit:
If you are already using django-redis then you can do
from django.core.cache import cache
cache.keys("foo_*")
as explained here.
This will return list of keys matching the pattern then you can use cache.get_many() to get values for these keys.
cache.get_many(cache.keys("key_1_*"))
If the cache has following entries:
cache = {'key_1_3': 'foo', 'key_2_5': 'bar', 'key_1_7': 'baz'}
You can get all the entries which has key key_1_*:
x = {k: v for k, v in cache.items() if k.startswith('key_1')}
Based on the documentation from django-redis
You can list all the keys with a pattern:
>>> from django.core.cache import cache
>>> cache.keys("key_1_*")
# ["key_1_3", "key_1_7"]
once you have the keys you can get the values from this:
>>> [cache.get(k) for k in cache.keys("key_1_*")]
# ['foo', 'baz']
You can also use cache.iter_keys(pattern) for efficient implementation.
Or, as suggested by #Muhammad Tahir, you can use cache.get_many(cache.keys("key_1_*")) to get all the values in one go.
I saw several answers above mentioning django-redis.
Based on https://pypi.org/project/django-redis/
You can actually use delete_pattern() method
from django.core.cache import cache
cache.delete_pattern('key_1_*')
Can't find a direct, head on answer to this. Is there a way to access a tempfile in Django across 2 distinct views? Say I have the following code:
view#1(request):
temp = tempfile.NamedTemporaryFile()
write_book.save(temp_file)
temp_file_name = temp_file.name
print temp_file_name
request.session['output_file_name'] = temp_file_name
request.session.modified = True
return #something or other
view#2(request):
temp_file_name = request.session['output_file_name']
temp_file = open(str(temp_file_name))
#do something with 'temp_file' here
My problem comes in specifically on view#2, the 2nd line "open(temp_file_name)". Django complains this file/pathway doesn't exist, which is consistent of my understanding of the tempfile module (that the file is 'hidden' and only available to Django).
Is there a way for me to access this file? In case it matters, I ONLY need to read from it (technically serve it for download).
I'd think of this as how to access a NamedTemporaryFile across different requests, rather than different views. Looking at this documentation on NamedTemporaryFile, it says that the file can be opened across the same process, but not necessarily across multiple processes. Perhaps your other view is being called in a different Django process.
My suggestion would be to abandon the use of NamedTemporaryFile and instead just write it as a permanent file, then delete the file in the other view.
Thanks seddonym for attempting to answer. My partner clarified this for me...seddonym is correct for the Django version of NamedTemporaryFile. By calling the python version (sorry, don't have enough cred to post hyperlinks. Stupid rule) you CAN access across requests.
The trick is setting the delete=False parameter, and closing the file before 'returning' at the end of the request. Then, in the subsequent request, just open(file_name). Psuedo code below:
>>> import tempfile
>>> file = tempfile.NamedTemporaryFile(delete=False)
>>> file.name
'c:\\users\\(blah)\(blah)\(blah)\\temp\\tmp9drcz9'
>>> file.close()
>>> file
<closed file '<fdopen>', mode 'w+b' at 0x00EF5390>
>>> f = open(file.name)
>>> f
<open file 'c:\users\ymalik\appdata\local\temp\tmp9drcz9', mode 'r' at 0x0278C128>
This is, of course, done in the console, but it works in django as well.
How do I insert data in Django to a SQL table using the Django ORM?
If you need to insert a row of data, see the "Saving objects" documentation for the save method on the model.
FYI, you can perform a bulk insert. See the bulk_create method's documentation.
In fact it's mentioned in the first part of the "Writing your first Django app" tutorial.
As mention in the "Playing with API" section:
>>> from django.utils import timezone
>>> p = Poll(question="What's new?", pub_date=timezone.now())
# Save the object into the database. You have to call save() explicitly.
>>> p.save()
# Now it has an ID. Note that this might say "1L" instead of "1", depending
# on which database you're using. That's no biggie; it just means your
# database backend prefers to return integers as Python long integer
# objects.
>>> p.id
1
Part-4 of the tutorial explains how to use forms and how to save object using user submitted data.
If you don't want to call the save() method explicitly, you can create a record by using MyModel.objects.create(p1=v1, p2=v1, ...)
fruit = Fruit.objects.create(name='Apple')
# get fruit id
print(fruit.id)
See documentation