1. 程式人生 > 其它 >Luffy /2/ 後臺資料庫配置&前臺建立配置

Luffy /2/ 後臺資料庫配置&前臺建立配置

目錄

二次封裝Response

utils/reponse.py

from rest_framework.response import Response


class APIReponse(Response):
    # 將父類的status重名http_status
    def __init__(self, status=100, msg='成功', http_status=None, template_name=None, headers=None, exception=False,
                 content_type=None, **kwargs):
        data = {
            'status': status,
            'msg': msg
        }
        if kwargs:
            # kwags接收除了處初始化規定的引數以外的引數,也用於更新字典
            data.update(kwargs)
        super.__init__(data=data, status=http_status,
                       template_name=template_name, headers=headers,
                       exception=exception, content_type=content_type)

後臺資料庫配置

命令操作

# 建立資料庫
create database luffy default charset=utf8;

# 建立使用者並授權
## 檢視使用者
### 5.7之前版本
select user,host,password from mysql.user;
### 5.7往後的版本
select user,host,authentication_string from mysql.user;

## 建立使用者
### 授權賬號命令:grant 許可權(create, update) on 庫.表 to '賬號'@'host' identified by '密碼'
## 這裡授權所有許可權
grant all privileges on luffy.* to 'luffy'@'%' identified by '7410';
grant all privileges on luffy.* to 'luffy'@'localhost' identified by '7410';

## 重新整理許可權表
flush privileges;

pycharm連線

## 專案配置檔案加入
   'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'luffy', # 資料庫名字
        'USER': 'luffy', # 使用者名稱
        'PASSWORD': '7410',
        'HOST': '7410',
        'PORT': 3306
    }

然後再登入檢視資料庫只能檢視luffy庫

django操作mysql

方式一

模式使用MysqlDB來操作,MysqlDB在python3.x以後不存在了

方式二

使用pymysql替換,django2.0.7版本及以上,如果使用pymysql替換,需要改django原始碼

import pymysql
pymysql.install_as_MySQLdb()

不改報錯:AttributeError: 'str' object has no attribute 'decode'

query = query.decode(errors='replace')
# 改成
query = query.encode(errors='replace')

所以不推薦改原始碼這種形式

推薦使用mysqlclient模組,其實就是MysqlDB在python3.x以後使用的版本,只不過變成了mysqlclient,使用mysqlclient不需要寫兩句話,不用改原始碼

如果裝mysqlclient報以下錯,可參考:

【已解決】error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ - HammerZe - 部落格園 (cnblogs.com)

下載成功可以使用pycharm連線一下

user表設計

這裡基於auth的user表擴寫,千萬要注意,擴寫好之前不要先遷移資料庫,如果遷移了就不行了

如果你已經遷移了,刪除資料庫,刪除所有的migrations檔案,包含你自己的app,和auth和admin這兩個app

# 使用者板塊---》做成app
python ../../manage.py startapp user

# models.py
from django.db import models
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    mobile = models.CharField(max_length=11, unique=True)  # 唯一,長度11
    # 需要pillow包的支援 ImageField繼承自FileField
    icon = models.ImageField(upload_to='icon', default='icon/default.png')

    class Meta:
        db_table = 'luffy_user'
        verbose_name = '使用者表'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username

setting/dev.py

# 配置檔案---》登錄檔
INSTALLED_APPS = [
    'user',
]

# 自定義User表
AUTH_USER_MODEL = 'user.User'


## 配置media
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

安裝pillow模組

# 安裝pillow 
pip install pillow
'''
Pillow是PIL的一個派生分支,但如今已經發展成為比PIL本身更具活力的影象處理庫。pillow可以說已經取代了PIL,將其封裝成python的庫(pip即可安裝),且支援python2和python3,目前最新版本是3.0.0
'''

遷移

python manage.py makemigrations
python manage.py migrate

前臺建立及配置

我的是win平臺,建議使用管理員開啟cmd建立

# 建立專案
vue create luffycity

使用pycharm開啟配置

  1. 刪除components/HelloWorld.vueviews/AboutView.vue

  2. views/HomeView.vue

<template>
  <div class="home">
    <h1>首頁</h1>
  </div>
</template>

<script>

export default {
  name: 'HomeView',
  components: {
  }
}
</script>
  1. router/index.js
const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
]

// index.js種routes裡刪除下面的內容
{
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  }
  1. APP.vue
<template>
  <div id="app">
    <router-view/>
  </div>
</template>
  1. 整合elementui 、bootstrap、jquery、axios

    // elementui ,bootstrap,jquery,axios配置
    // axios
    npm install axios  -S
    // main.js
    import axios from 'axios'
    Vue.prototype.$axios = axios;
    
    //elementui
    npm install element-ui -S
    // main.js
    import ElementUI from 'element-ui';
    import 'element-ui/lib/theme-chalk/index.css';
    Vue.use(ElementUI);
    
    // bootstrap和jq
    npm install jquery -S
    npm install bootstrap@3 -S
    // vue.config.js
    const {defineConfig} = require('@vue/cli-service')
    const webpack = require("webpack");
    module.exports = defineConfig({
        transpileDependencies: true,
        configureWebpack: {
            plugins: [
                new webpack.ProvidePlugin({
                    $: "jquery",
                    jQuery: "jquery",
                    "window.jQuery": "jquery",
                    "window.$": "jquery",
                    Popper: ["popper.js", "default"]
                })
            ]
        },
    })
    
    // main.js,匯入
    import 'bootstrap'
    import 'bootstrap/dist/css/bootstrap.min.css'
    

全域性css樣式配置

assets/css/global.css

/* 宣告全域性樣式和專案的初始化樣式 */
body, h1, h2, h3, h4, h5, h6, p, table, tr, td, ul, li, a, form, input, select, option, textarea {
    margin: 0;
    padding: 0;
    font-size: 15px;
}

a {
    text-decoration: none;
    color: #333;
}

ul {
    list-style: none;
}

table {
    border-collapse: collapse; /* 合併邊框 */
}

main.js

// 把自己定義的global.css 引入
import './assets/css/global.css'

配置檔案配置

assets/js/settings.js

export default {
    base_url: "http://127.0.0.1:8000"
}

main.js

// 匯入自定義配置
import settings from './assets/js/settings'
Vue.prototype.$settings = settings;