做用:鏈接mysql數據庫html
下載:pip install pymysqlpython
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', #改爲mysql默認是sqlite3 'NAME': 'luffy', #本身建立的數據庫名字 'HOST': '127.0.0.1', #數據庫的ip地址,本地ip能夠是'127.0.0.1'或者'localhost' 'PORT': 3306, #mysql數據庫端口號3306 'USER': 'luffy_user', #登錄數據庫的用戶名 'PASSWORD': 'luffy' #登錄用戶的密碼 } }
import pymysql pymysql.install_as_MySQLdb()
在pycharm打開Terminal(在界面底部能夠找到),在不一樣app下的models.py來建立模型類,而後依次執行python manage.py makemigrations和python manage.py migrate兩條命令就能夠在將模型類同步到數據庫。mysql
做用:後端代碼寫接口使用git
下載:pip install djangorestframeworkgithub
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', #註冊rest_framework模塊,而後就能夠在視圖函數經過import使用 ]
做用:解決CORS跨域問題ajax
下載:pip install django-cors-headersredis
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', #django-cors-headers模塊註冊 'rest_framework', #djangorestframework模塊註冊 ]
MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', #必須放在第一位 ... ]
# CORS組的配置信息 CORS_ORIGIN_WHITELIST = ( 'www.luffycity.cn:8080',#白名單的url ) CORS_ALLOW_CREDENTIALS = False # 容許ajax跨域請求時攜帶cookie
做用:圖片處理模塊sql
下載:pip install pillow數據庫
# 項目中存儲上傳文件的根目錄[暫時配置],注意,uploads目錄須要手動建立不然上傳文件時報錯 MEDIA_ROOT=os.path.join(BASE_DIR,"uploads") # 訪問上傳文件的url地址前綴 MEDIA_URL ="/media/"
from django.urls import re_path from django.conf import settings from django.views.static import serve urlpatterns = [ ... re_path(r'media/(?P<path>.*)', serve, {"document_root": settings.MEDIA_ROOT}), ]
做用:登錄模塊django
下載:pip install https://codeload.github.com/sshwsfc/xadmin/zip/django2 -i https://pypi.douban.com/simple/ (#該命令是安裝經過豆瓣源安裝最新版xadmin)
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', #django-cors-headers模塊註冊 'rest_framework', #djangorestframework模塊註冊 #新增xadmin註冊 'xadmin', 'crispy_forms', 'reversion', ]
因爲xadmin模塊中有本身的數據庫模型類,因此在使用以前須要進行數據庫遷移
import xadmin xadmin.autodiscover() # version模塊自動註冊須要版本控制的 Model from xadmin.plugins import xversion xversion.register_models() urlpatterns = [ path(r'xadmin/', xadmin.site.urls), ]
在app下的新建adminx.py文件,在該文件寫基本站點配置信息類,經過xadmin.site.register來註冊功能,如:
import xadmin from xadmin import views class BaseSetting(object): """xadmin的基本配置""" enable_themes = True # 開啓主題切換功能 use_bootswatch = True xadmin.site.register(views.BaseAdminView, BaseSetting) class GlobalSettings(object): """xadmin的全局配置""" site_title = "路飛學城" # 設置站點標題 site_footer = "路飛學城有限公司" # 設置站點的頁腳 menu_style = "accordion" # 設置菜單摺疊 xadmin.site.register(views.CommAdminView, GlobalSettings)
from .models import BannerInfo class BannerInfoModelAdmin(object): list_display=["title","orders","is_show"]
# BannerInfo是自定義模型類 xadmin.site.register(BannerInfo, BannerInfoModelAdmin)
做用:用戶記錄用戶用戶登錄狀態,能夠實現分佈式站點單點登錄
下載:pip install djangorestframework-jwt
在配置文件中添加如下代碼
REST_FRAMEWORK = { #用戶發送信息檢測信息,添加第一行是JWT驗證 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), } import datetime JWT_AUTH = { #JWT有效期設置 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1), }
手動生成JWT驗證(當用戶註冊後能夠手動生成JWT返回給用戶,這樣就能夠省去登錄)
from rest_framework_jwt.settings import api_settings jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER #user是用戶表的一條數據 payload = jwt_payload_handler(user) token = jwt_encode_handler(payload)
from rest_framework_jwt.views import obtain_jwt_token urlpatterns = [ path(r'authorizations/', obtain_jwt_token, name='authorizations'), ]
因爲登錄使用jwt認證,系統會默認返回token值不返回其餘值,須要自定義則新建文件,
def jwt_response_payload_handler(token, user=None, request=None): """ 自定義jwt認證成功返回數據 """ return { 'token': token, 'id': user.id, 'username': user.username }
在配置文件中添加配置
# JWT JWT_AUTH = { 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1), 'JWT_RESPONSE_PAYLOAD_HANDLER': 'users.utils.jwt_response_payload_handler', }
做用:在django項目中使用redis數據庫
下載:pip install django-redis
在django中提供了對緩存的配置:CACHES
# 設置redis緩存 CACHES = { # 默認緩存 "default": { "BACKEND": "django_redis.cache.RedisCache", # 項目上線時,須要調整這裏的路徑 "LOCATION": "redis://127.0.0.1:6379/0", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } }, # 提供給xadmin或者admin的session存儲 "session": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } }, # 提供存儲短信驗證碼 "sms_code":{ "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/2", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } # 設置xadmin用戶登陸時,登陸信息session保存到redis SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "session"
1.在須要對redis數據庫操做給文件導入文件:from djagno_redis improt get_redis_connection
2.實例化對象,而後經過對象.方法的方式能夠操做數據庫,具體方法:http://django-redis-chs.readthedocs.io/zh_CN/latest/
做用:在django項目中用與過濾字段
下載:pip install django-filter
INSTALLED_APPS = [ ... 'django_filters', # 須要註冊應用, ]
在視圖類中添加字段,filter_backends和filter_fields兩個字段,這兩個字段都是能夠有多個,因此放在元組或者列表裏面。
filter_backends:是用與過濾的類,這個類能夠從django_filters.rest_framework中導入
filter_fields:要過濾的字段名,這個字段必須是要在須要過濾的模型類中的字段
例子:
from .serializers import CourseModelSerializer #自定義序列化器 from django_filters.rest_framework import DjangoFilterBackend #django-filter提供的類 class CourseAPIView(ListAPIView): '''自定義視圖類''' queryset = Course.objects.filter(is_delete=False, is_show=True).order_by("orders") serializer_class = CourseModelSerializer # 新增過濾使用的字段 filter_backends = [DjangoFilterBackend, ] filter_fields = ('course_category',)
下載:pip install django-ckeditor
INSTALLED_APPS = [ ... 'ckeditor', # 富文本編輯器 'ckeditor_uploader', # 富文本編輯器上傳圖片模塊 ... ]
# 富文本編輯器ckeditor配置 CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', # 工具條功能 'height': 300, # 編輯器高度 # 'width': 300, # 編輯器寬 }, } CKEDITOR_UPLOAD_PATH = '' # 上傳圖片保存路徑,留空則調用django的文件上傳功能
path(r'^ckeditor/', include('ckeditor_uploader.urls')),
from ckeditor_uploader.fields import RichTextUploadingField class Course(models.Model): """ 專題課程 """ ... brief = RichTextUploadingField(max_length=2048, verbose_name="課程概述", null=True, blank=True)
富文本編輯器內還能夠自定義編輯顯示的界面,能夠參考https://github.com/django-ckeditor/django-ckeditor
from rest_framework_extensions.cache.decorators import cacha_response from rest_framework.views import APIView class MyAPIView(APIView): @cacha_response(timeout=24*60*60, cache="sms_code" ) def get(self,request): pass
此外,能夠將裝飾器的兩個參數放到配置文件中(默認settings.py),如
REST_FRAMEWORK_EXTENSIONS = { # 緩存時間 'DEFAULT_CACHE_RESPONSE_TIMEOUT':24 * 60 * 60, # 緩存存儲 'DEFAULT_USE_CACHE': 'sms_code', }
ListCacheResponseMixin:用與緩存返回列表數據的視圖,與ListModelMixin擴展類配置實用
RetrieveCacheResponseMixin:用與緩存返回單一數據的視圖,與RetrieveModelMixin擴展類配置實用
CacheResponseMixin:能夠理解爲ListCacheResponseMixin和RetrieveCacheResponseMixin兩個類的合集,實際上該類就是繼承上面兩個類,且沒有任何寫任何邏輯方法和屬性
from rest_framework_extensions.cache.mixins import ListCacheResponseMixin, RetrieveCacheResponseMixin, \ CacheResponseMixinfrom rest_framework.mixins import ListModelMixin, RetrieveModelMixinclass One(ListCacheResponseMixin, ListModelMixin): passclass Two(RetrieveCacheResponseMixin, RetrieveModelMixin): passclass Three(CacheResponseMixin, ListModelMixin, RetrieveModelMixin): pass