路飛專案環境搭建
阿新 • • 發佈:2020-07-17
目錄
路飛專案環境搭建
1 pip換源
%APPDATA% 來到C:\Users\oldboy\AppData\Roaming 建立一個pip資料夾 新建一個檔案pip.ini 寫入 [global] index-url = http://pypi.douban.com/simple [install] use-mirrors =true mirrors =http://pypi.douban.com/simple/ trusted-host =pypi.douban.com
2 python虛擬環境搭建
1 不同的專案依賴不同的模組版本,不能共用一套環境,所以每個專案都應該使用各自的虛擬環境 2 在系統的python環境中安裝2個模組 pip3 install virtualenv pip3 install virtualenvwrapper-win -修改環境變數: WORKON_HOME: D:\Virtualenvs -在python安裝路徑內的scripts檔案中執行virtualenvwrapper.bat檔案 3 使用: 命令列輸入以下指令可以檢視所有的虛擬環境或使用對應的虛擬環境 -mkvirtualenv -p python3 luffy # 建立虛擬環境 -workon #列出有的虛擬環境(aaa) -workon aaa #使用名為aaa的虛擬環境 -rmvirtualenv 虛擬環境名字 # 刪除虛擬環境 4 安裝django環境 在使用workon aaa後會在命令列最左邊出現一個(aaa) 此時安裝的第三方包都會安裝到該虛擬環境 如:pip install django==2.2.2 5 基於虛擬環境建立專案(pycharm選擇已存在的環境)
3 路飛後臺建立,配置修改,目錄變更
# 在控制檯直接指向專案 python manage.py runserver --->manage.py需要修改settings路徑 os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'luffyapi.settings.dev') # 專案上線,走的不是wsgi.py--->而是uwsgi.py,需要修改settings路徑 os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'luffyapi.settings.dev') # 國際化 將部分文字修改成中文 LANGUAGE_CODE = 'zh-hans' TIME_ZONE = 'Asia/shanghai' USE_I18N = True USE_L10N = True USE_TZ = False # 建立app: startapp的執行位置,就是app的建立位置 python ../../manage.py startapp home # 註冊app 在settings中配置 sys.path.insert(0, BASE_DIR) sys.path.insert(1, os.path.join(BASE_DIR, 'apps')) 右鍵apps資料夾,選擇mark directory,設定為sources root # 最終效果 ├── luffyapi ├── logs/ # 專案執行時/開發時日誌目錄 - 包 ├── manage.py # 指令碼檔案 ├── luffyapi/ # 專案主應用,開發時的程式碼儲存 - 包 ├── apps/ # 開發者的程式碼儲存目錄,以模組[子應用]為目錄儲存 - 包 ├── libs/ # 第三方類庫的儲存目錄[第三方元件、模組] - 包 ├── settings/ # 配置目錄 - 包 ├── dev.py # 專案開發時的本地配置 └── prod.py # 專案上線時的執行配置 ├── urls.py # 總路由 └── utils/ # 多個模組[子應用]的公共函式類庫[自己開發的元件] └── scripts/ # 儲存專案運營時的指令碼檔案 - 資料夾
4 資料庫配置
# 建立專案依賴的資料庫,luffyapi
-create database luffyapi;
# 建立資料庫使用者,並且授予luffyapi該庫的許可權
-grant all privileges on luffyapi.* to 'luffyapi'@'%' identified by 'Luffy123?';
-grant all privileges on luffyapi.* to 'luffyapi'@'localhost' identified by 'Luffy123?';
-flush privileges;
# 專案連線
-setting中配置
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'luffyapi',
'USER':'luffyapi',
'PASSWORD':'Luffy123?',
'HOST':'127.0.0.1',
'PORT':3306
}
}
import pymysql
pymysql.install_as_MySQLdb()
-用pymysql連線資料庫
-django超過:2.0.7
-需要改原始碼,兩個地方
5 User表配置
# 使用者要基於auth的user表,必須在資料庫遷移命令之前操作好,後期如果再做,會出錯
-把所有app下的遷移檔案,全刪除
-admin,auth 兩個app下的遷移檔案刪除
/Lib/site-packages/django/contrib/auth/migrations
\Lib\site-packages\django\contrib\admin\migrations
-刪庫(資料一定要匯出來),重新遷移
# 繼承AbstractUser,增加兩個欄位,telephone,icon(使用image欄位必須安裝pillow)
# 在setting中配置
MEDIA_URL='/media/'
MEDIA_ROOT=os.path.join(BASE_DIR,'media')
# BASEDIR是luffyapi下的luffyapi
AUTH_USER_MODEL='user.user'
# 配置路由,開放media資料夾
re_path('media/(?P<path>.*)', serve,{'document_root':settings.MEDIA_ROOT}),
6 路飛前臺搭建
#1 安裝node,官網下載,一路下一步
node -v
v10.16.3
#2 換源
npm install -g cnpm --registry=https://registry.npm.taobao.org
#3 安裝模組
npm install 模組名 #npm比較慢,用淘寶的cnpm來替換npm
#4 建立vue的工程(需要一個vue腳手架)
cnpm install -g @vue/cli
#5 如果出問題執行如下,重新走3,4
npm cache clean --force
#5 命令列下敲
vue 就會有提示
# 6 建立vue專案
vue create luffycity
選Manually
#7 用pycharm開啟
在terminal下敲:npm run serve
#8 配置pycharm可用綠色箭頭開啟
綠色箭頭旁的下拉框,選擇edit configrations,輸入serve
7 目錄介紹
public
-favicon.ico # 圖示
-index.html #整個專案的單頁面
src
-assets #靜態檔案,js,css,img
-components # 小元件,頭部元件,尾部元件
-router # 路由相關
-store # vuex相關,狀態管理器,臨時儲存資料的地方
-views # 頁面元件
-App.vue # 根元件
-main.js # 配置檔案(跟django的setting一樣)
#任何一個元件都有三部分
<template>
#html相關
</template>
<style>
# css相關
</style>
<script>
# js相關
</script>
8 Response、異常和日誌的封裝
response
# utils/response
from rest_framework.response import Response
class APIResponse(Response):
def __init__(self,code=1,msg='成功',result=None,status=None,headers=None,**kwargs):
dic={'code':code,'msg':msg}
if result:
dic['result']=result
dic.update(kwargs)
super().__init__(data=dic,status=status,headers=headers)
exception
#utils/exceptions.py
from rest_framework.views import exception_handler
from .response import APIResponse
from .logger import log
def common_exception_handler(exc, context):
log.error('view是:%s ,錯誤是%s'%(context['view'].__class__.__name__,str(exc)))
#context['view'] 是TextView物件,取出它的類名
print(context['view'].__class__.__name__)
ret=exception_handler(exc, context) # 是Response物件,它內部有個data
if not ret:
# drf內建的異常處理方法處理不了的異常,會返回空
# 可以通過類的判斷,更具體的捕獲異常
if isinstance(exc,KeyError):
return APIResponse(code=0, msg='key error')
return APIResponse(code=0,msg='error',result=str(exc))
else:
return APIResponse(code=0,msg='error',result=ret.data)
logger
# 封裝logger
# setting.py中配置日誌
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(lineno)d %(message)s'
},
'simple': {
'format': '%(levelname)s %(module)s %(lineno)d %(message)s'
},
},
'filters': {
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue',
},
},
'handlers': {
'console': {
# 實際開發建議使用WARNING
'level': 'DEBUG',
'filters': ['require_debug_true'],
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
'file': {
# 實際開發建議使用ERROR
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
# 日誌位置,日誌檔名,日誌儲存目錄必須手動建立,注:這裡的檔案路徑要注意BASE_DIR代表的是小luffyapi
'filename': os.path.join(os.path.dirname(BASE_DIR), "logs", "luffy.log"),
# 日誌檔案的最大值,這裡我們設定300M
'maxBytes': 300 * 1024 * 1024,
# 日誌檔案的數量,設定最大日誌數量為10
'backupCount': 100,
# 日誌格式:詳細格式
'formatter': 'verbose',
# 檔案內容編碼
'encoding': 'utf-8'
},
},
# 日誌物件
'loggers': {
'django': {
'handlers': ['console', 'file'],
'propagate': True, # 是否讓日誌資訊繼續冒泡給其他的日誌處理系統
},
}
}
#utils/logger
import logging
# log=logging.getLogger('名字') # 跟配置檔案中loggers日誌物件下的名字對應
log=logging.getLogger('django')
# 後續使用:匯入直接用
from luffyapi.utils.logger import log
log.info('xxxxxx') # 不要寫print
9 跨域問題及解決
# xss:跨站指令碼攻擊,cors:跨域資源共享,csrf:跨站請求偽造
# 同源策略是瀏覽器進行的攔截,伺服器並未阻止響應
# 1 同源策略:請求的url地址,必須與瀏覽器上的url地址同源,也就是域名(ip),埠(port),協議(http,https)相同.
# 2 CORS:跨域資源共享,允許不同域的請求訪問伺服器拿資料
# 3 CORS請求分成兩類:簡單請求(simple request)和非簡單請求(not-so-simple request)
只要同時滿足以下兩大條件,就屬於簡單請求
(1) 請求方法是以下三種方法之一:
HEAD
GET
POST
(2)HTTP的頭資訊不超出以下幾種欄位:
Accept
Accept-Language
Content-Language
Last-Event-ID
Content-Type:只限於三個值application/x-www-form-urlencoded、multipart/form-data、text/plain
# 非簡單請求會發兩次請求,一次是OPTIONS請求,一次是真正的請求
9.1 自己寫中介軟體實現
# 1 後端處理,開啟cors,跨域資源共享(在中介軟體中寫)
class MyMiddle(MiddlewareMixin):
def process_response(self, request, response):
response['Access-Control-Allow-Origin'] = '*'
if request.method == "OPTIONS": # 可以加*
response["Access-Control-Allow-Headers"] = "Content-Type"
response["Access-Control-Allow-Headers"] = "authorization"
return response
# 2 在setting的中介軟體中配置
9.2 用第三方模組實現
使用第三方,django-cors-headers
-pip install django-cors-headers
-註冊app:'corsheaders',
-配置中介軟體:corsheaders.middleware.CorsMiddleware
-setting中配置:
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)
CORS_ALLOW_HEADERS = (
'authorization',
'content-type',
)
10 前後臺打通
#1 前臺可以傳送ajax的請求,axios
#2 cnpm install axios
#3 配置在main.js中
import axios from 'axios' //匯入安裝的axios
//相當於把axios這個物件放到了vue物件中,以後用 vue物件.$axios
Vue.prototype.$axios = axios;
#4 使用(某個函式中)
this.$axios.get('http://127.0.0.1:8000/home/home/'). //向某個地址傳送get請求
then(function (response) { //如果請求成功,返回的資料再response中
console.log(response)
}).catch(function (error) {
console.log(error)
})
#5 es6的箭頭函式
function (response) {console.log(response)}
response=>{ console.log(response)}
11 xadmin後臺管理
# 1 安裝 pip install https://codeload.github.com/sshwsfc/xadmin/zip/django2
# 2 在settings中註冊3個app
'xadmin', # xadmin主體模組
'crispy_forms', # 渲染表格模組
'reversion', # 為模型通過版本控制,可以回滾資料
# 3 資料遷移
python manage.py makemigrations
python manage.py migrate
# 4 主路由替換掉admin:主urls.py
# xadmin的依賴
import xadmin
xadmin.autodiscover()
# xversion模組自動註冊需要版本控制的 Model
from xadmin.plugins import xversion
xversion.register_models()
urlpatterns = [
path(r'xadmin/', xadmin.site.urls),
]
# 5 # 在專案根目錄下的終端
python manage.py createsuperuser
# 賬號密碼設定:admin | Admin123