从零开始搭建django先后端分离项目 系列二(项目搭建)

在开始项目以前,假设你已了解如下知识:webpack配置、vue.js、django。这里不会教你webpack的基本配置、热更新是什么,也不会告诉你如何开始一个django项目,有需求的请百度,相关的文章已经不少了。html

 下面开始一步一步构建完整的项目:前端

一、开发环境准备vue

win7 x64node

python 3.4python

Django 1.10.8webpack

node.js 4.4.3web

二、python相关包安装redis

建议建立python虚拟环境进行安装。vue-cli

pip install virtualenv
pip install virtualenvwrapper
pip install virtualenvwrapper-win  # Windows使用该命令npm

mkvirtualenv venv # 建立venv虚拟环境

推荐python相关的模块(包括Django)都使用python自带的pip安装器安装。

impyla的安装参照个人另外一篇博文 http://www.javashuo.com/article/p-ngyluwns-w.html

数据分析相关包pandas、numpy、scipy、matplotlib、sklearn的安装参照个人博文 http://www.javashuo.com/article/p-yvslrebr-q.html

注意:

celery建议选择celery3.x版本进行安装,结合django-celery模块。由于celery4.x版本的django-celery-beat在djang-admin后台添加task后系统不会对修改后的任务即时生效,而是须要重启celery-beat服务才能生效。我这个项目选择的celery 3.1.18+django-celery 3.2.2+redis 2.10.6。

三、建立工程

建立django后端项目

django-admin startproject myproject
python manage.py startapp app

 

python manage.py runserver 0.0.0.0:8000

修改settings.py文件

TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', # 'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'DIRS': [os.path.join(BASE_DIR, 'dist'),os.path.join(BASE_DIR, 'myproject/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', ], }, }, ]
os.path.join(BASE_DIR, 'dist')文件夹存放前端npm run build编译后的单页面文件

建立vue.js前端项目

利用vue-cli脚手架工具建立前端vue.js项目

 

dist文件夹为编译后的前端代码,编译成功后直接拷贝到django项目的os.path.join(BASE_DIR, 'dist')位置替换便可。

注意:

若是django后端和vue.js前端项目不在同一个域内,那么咱们请求的数据至关因而调用的第三方接口,那么会存在一个问题:跨域限制。

为解决跨域问题,咱们能够在webpack设置代理解决跨域问题,固然解决跨域问题的方法不少,不懂的请自行百度。

在config/index.js文件的dev: {   proxyTable: { }}写入要跨域代理的连接地址:

proxyTable: { '/app/**': { target: 'http://localhost:8000', secure: false, changeOrigin: true } }

这里本项目django与前端在同一台开发服务器上,django启动服务端口为8000,因此上面target的配置为 http://localhost:8000。

相关文章
相关标签/搜索