在配置之前,先介绍一个实用的工具:
当我们进入虚拟环境,在shell中进行操作的时候,往往要导入django的各种配置文件:
from django.x import xxxx
这时我们可以借助django_extensions工具
1、安装
(newblog-ES3JapFS) E:PycharmProjectsmywebsite>pip install django_extensions
2、在settings中配置'django_extensions'
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', ]
3、在shell中使用:python manage.py shell_plus
结果如下:
(newblog-ES3JapFS) E:PycharmProjectsmywebsite>python manage.py shell_plus # Shell Plus Model Imports from django.contrib.admin.models import LogEntry from django.contrib.auth.models import Group, Permission from django.contrib.contenttypes.models import ContentType from django.contrib.sessions.models import Session from myweb.models import Ad, Article, Category, Comment, Links, Tag, User # Shell Plus Django Imports from django.core.cache import cache from django.conf import settings from django.contrib.auth import get_user_model from django.db import transaction from django.db.models import Avg, Case, Count, F, Max, Min, Prefetch, Q, Sum, When, Exists, OuterRef, Subquery from django.utils import timezone from django.urls import reverse Python 3.6.6 (v3.6.6:4cf1f54eb7, Jun 27 2018, 03:37:03) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>>
Bingo!成功地导入!
现在我们来操作吧:
>>> from django.core.cache import caches >>> cache['default'] Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: 'DefaultCacheProxy' object is not subscriptable >>> caches['default'] <django.core.cache.backends.locmem.LocMemCache object at 0x00000186B3102B00> >>> from django.core.cache import cache >>> cache.get('test') >>> cache.set('mykey','hello',30) >>> cache.get('mykey') 'hello' >>> cache.get('mykey') 'hello' >>> cache.get('mykey') 'hello' # 30s之后缓存结束了,已经得不到返回值。 >>> cache.get('mykey') >>> cache.get('mykey')