Python前端开发Python

Django Vue.js搭建前后端分离项目超详细过程

2017-10-09  本文已影响8030人  leyu

环境:windows 7、django1.11、python3.6.3

1. 使用virtualenv创建python虚拟环境并设置pycharm

E:\pyvenv>virtualenv utester_env
E:\pyvenv>cd utester_env
E:\pyvenv>Scripts\activate.bat
(utester_env) E:\pyvenv>pip install django
(utester_env) E:\pyvenv\utester_env>pip install django
Requirement already satisfied: django in e:\pyvenv\utester_env\lib\site-packages

Requirement already satisfied: pytz in e:\pyvenv\utester_env\lib\site-packages (
from django)

注意:虚拟环境的目录不能带有中文,否则环境变量识别不了

2.创建Django项目

(utester_env) E:\projects>django-admin startproject utester
(utester_env) E:\projects>cd utester

#创建表
(utester_env) E:\projects\utester>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying sessions.0001_initial... OK

#创建管理员用户
(utester_env) E:\projects\utester>python manage.py createsuperuser
Username (leave blank to use 'zengzhihua'):
Email address: 1036181341@qq.com
Password:
Password (again):
This password is too short. It must contain at least 8 characters.
This password is too common.
This password is entirely numeric.
Password:
Password (again):
Superuser created successfully.

(utester_env) E:\projects\utester>python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
October 09, 2017 - 14:05:32
Django version 1.11.6, using settings 'utester.settings'
Starting development server at http://127.0.0.1:8000/

访问http://127.0.0.1:8000/admin/,输入刚刚创建的用户名和密码,如果一切顺利,就可以看到django的admin管理后台了。

3.创建vue项目

关于django、vue前后端分离,在github上有个模板hello-vue-django,源仓库地址hello-vue-django。但我看不惯python和js文件,想把vue项目代码单独放一个目录frontend。
在utester项目目录利用vue-cli新建vue的项目代码

(utester_env) E:\projects\utester>vue init webpack  frontend

  A newer version of vue-cli is available.

  latest:    2.9.1
  installed: 2.8.2

? Project name utester
? Project description A Vue.js project
? Author zengzhihua
? Vue build standalone
? Install vue-router? Yes
? Use ESLint to lint your code? No
? Setup unit tests with Karma + Mocha? No
? Setup e2e tests with Nightwatch? No

   vue-cli · Generated "frontend".

   To get started:

     cd frontend
     npm install
     npm run dev

   Documentation can be found at https://vuejs-templates.github.io/webpack

最终项目目录结构如下:

(utester_env) E:\projects\utester>tree /f
卷 NewDisk 的文件夹 PATH 列表
卷序列号为 6A28-026B
E:.
│  db.sqlite3
│  manage.py
│
├─frontend
│  │  .babelrc
│  │  .editorconfig
│  │  .gitignore
│  │  .postcssrc.js
│  │  index.html
│  │  package.json
│  │  README.md
│  │
│  ├─build
│  │      build.js
│  │      check-versions.js
│  │      dev-client.js
│  │      dev-server.js
│  │      utils.js
│  │      vue-loader.conf.js
│  │      webpack.base.conf.js
│  │      webpack.dev.conf.js
│  │      webpack.prod.conf.js
│  │
│  ├─config
│  │      dev.env.js
│  │      index.js
│  │      prod.env.js
│  │
│  ├─src
│  │  │  App.vue
│  │  │  main.js
│  │  │
│  │  ├─assets
│  │  │      logo.png
│  │  │
│  │  ├─components
│  │  │      HelloWorld.vue
│  │  │
│  │  └─router
│  │          index.js
│  │
│  └─static
│          .gitkeep
│
├─imonitor
│  │  admin.py
│  │  apps.py
│  │  models.py
│  │  tests.py
│  │  views.py
│  │  __init__.py
│  │
│  └─migrations
│          __init__.py
│
└─utester
    │  settings.py
    │  urls.py
    │  wsgi.py
    │  __init__.py
    │
    └─__pycache__
            settings.cpython-36.pyc
            urls.cpython-36.pyc
            wsgi.cpython-36.pyc
            __init__.cpython-36.pyc

4.配置django-webpack-loader

参考文章:用django-webpack-loader实现Django和Webpack的绑定django-webpack配置

(utester_env) E:\pyvenv\utester_env>Scripts\pip.exe  install django-webpack-load
er
Collecting django-webpack-loader
  Could not fetch URL https://pypi.python.org/simple/django-webpack-loader/: The
re was a problem confirming the ssl certificate: [SSL: CERTIFICATE_VERIFY_FAILED
] certificate verify failed (_ssl.c:749) - skipping
  Could not find a version that satisfies the requirement django-webpack-loader
(from versions: )

这个错误,时有时无的,也不清楚是怎么回事,import ssl是没有问题的。所以只能跳过ssl验证,命令如下:

pip install --index-url=http://pypi.python.org/simple/ --trusted-host pypi.python.org  django-webpack-loader

然后设置Django( settings.py ),把 webpack_loader 加到INSTALLED_APPS中,指定templates和static目录,新增WEBPACK_LOADER:

INSTALLED_APPS = [
    ...
    'webpack_loader',
]

STATIC_URL = '/static/'

#静态文件主目录
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'frontend/dist/static'),  
)
 
#针对Webpack的设置
WEBPACK_LOADER = {
    'DEFAULT': {
        'BUNDLE_DIR_NAME': 'dist/'
    }
}

很奇怪1.11版本为什么没有STATICFILES_DIRS 变量了。我自己加上去的,不知道会不会有问题

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates'), ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

新建templates目录以及index.html文件,文件内容如下:

<!DOCTYPE html>
{% load render_bundle from webpack_loader %}
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>hello-vue</title>
</head>
<body>
<div id="app"></div>
{% render_bundle 'app' %}
</body>
</html>
  1. 安装webpack-bundle-tracker
    安装前记得npm install一下,将其他vue的依赖都安装完,安装完后node_modules目录非常大,pycharm一直pycharm scanning files to index,导致电脑非常卡,一不小心就内存崩溃了。可以将该目录标记为不扫描,右键node_modules,mark directory as Exclude,这样
(utester_env) E:\projects\utester>npm install --save-dev webpack-bundle-tracker
npm WARN saveError ENOENT: no such file or directory, open 'E:\projects\utester\
package.json'
E:\projects\utester
`-- webpack-bundle-tracker@0.2.0
  +-- deep-extend@0.4.2
  +-- mkdirp@0.5.1
  | `-- minimist@0.0.8
  `-- strip-ansi@2.0.1
    `-- ansi-regex@1.1.1
  1. 更改webpack.dev.conf.js文件
    引入webpack-bundle-tracker
var BundleTracker = require('webpack-bundle-tracker');
#plugins数组增加如下,filename于settings里的WEBPACK_LOADER一致
new BundleTracker({filename: '../webpack-stats.json'}),

3.更改webpack的config/index.js

#增加两个变量
const dev_server_addr = 'localhost';
const dev_server_port = process.env.PORT || 8080
#修改以下两个变量
port: dev_server_port,
assetsPublicPath: 'http://' + dev_server_addr + ':' + dev_server_port + '/static/dist' + '/',

5.启动dev环境

(utester_env) E:\projects\utester>python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
October 09, 2017 - 21:13:05
Django version 1.11.6, using settings 'utester.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

(utester_env) E:\projects\utester\frontend>npm run dev

> frontend@1.0.0 dev E:\projects\utester\frontend
> node build/dev-server.js
> Starting dev server...
 DONE  Compiled successfully in 3188ms                                  20:54:11
> Listening at http://localhost:8080
image.png

到这里,留下一个问题,就是更改frontend里的内容,不会同步刷新页面,只能手动刷新才能看到效果,热加载功能失效了。看浏览器的network里,有一个404的资源http://127.0.0.1:8000/__webpack_hmr,看样子是端口错了,应该是访问vue开启的8080端口。还没找到解决方法

本文所有代码:django-vue-helloworld

参考文献:

github:https://github.com/zaxlct/hello-vue-django

image.png
上一篇下一篇

猜你喜欢

热点阅读