vue.js python Django+Vue创建项目前后端分离 - location / {

📅 2026-11-30 👤 拼多多助力营销技巧 📂 拼多多助力网站平台 👁️ 444 次阅读

转载掘金文章详细介绍了如何搭建项目 https://juejin.cn/post/7028812676230807582

Django的TemplateView指向生成的前端dist文件即可.

1、 找到project目录的urls.py,使用通用视图创建最简单的模板控制器,访问 『/』时直接返回 index.html:

from django.conf.urls import url

from django.views.generic.base import TemplateView

from myApp import views as BookView

urlpatterns = [

path('admin/', admin.site.urls),

path('add_book/',BookView.add_book),

path('show_books/',BookView.show_books),

url(r'^$', TemplateView.as_view(template_name="index.html"), name="index"),

]

2、 上一步使用了Django的模板系统,所以需要配置一下模板使Django知道从哪里找到index.html。在project目录的settings.py下:

TEMPLATES = [

{

'BACKEND': 'django.template.backends.django.DjangoTemplates',

# 'DIRS': [],

'DIRS': ['template/dist'],

'APP_DIRS': True,

'OPTIONS': {

…………………

},

},

]

3、 我们还需要配置一下静态文件的搜索路径。同样是project目录的settings.py下:

STATICFILES_DIRS = [

os.path.join(BASE_DIR, "template/dist/static"),

]

4、 配置完成,我们在project目录下输入命令python manage.py runserver,就能够看到我们的前端页面在浏览器上展现。注意服务的端口已经是Django服务的8000而不是node服务的8080了。前端部分修改后,Django服务的8000页面不会实时更新,需要重新执行npm run build打包到dist目录下,Django的端口8000才会有变化。

vue + django 项目部署(部署前端代码 ---->>前端访问后端接口---->>到配置nginx—>>转发到uwsgi 返回数据展示)

前端vue

下载node二进制包,此包已经包含node,不需要再编译

wget https://nodejs.org/download/release/v8.6.0/node-v8.6.0-linux-x64.tar.gz

解压缩

tar -zxvf node-v8.6.0-linux-x64.tar.gz

进入node文件夹

[root@web02 opt]# cd node-v8.6.0-linux-x64/

[root@web02 node-v8.6.0-linux-x64]# ls

bin CHANGELOG.md etc include lib LICENSE README.md share

[root@web02 node-v8.6.0-linux-x64]# ls bin

node npm npx

[root@web02 node-v8.6.0-linux-x64]# ./bin/node -v

v8.6.0

[root@web02 node-v8.6.0-linux-x64]# ./bin/npm -v

5.3.0

将node命令,添加至linux环境变量,修改/etc/profile,写入

PATH=$PATH:/opt/node-v8.6.0-linux-x64/bin

读取文件,生效PATH

source /etc/profile

测试path

[root@web02 node-v8.6.0-linux-x64]# node -v

v8.6.0

[root@web02 node-v8.6.0-linux-x64]# npm -v

5.3.0

node环境有了,安装node模块,以及打包node项目

进入vue源码目录

cd 07-luffy_project_01/

安装vue模块,默认去装package.json的模块内容,如果出现模块安装失败,手动再装

npm install

此时注意,你本地写的vue代码,接口很可能连接的服务器地址有问题,注意Axios.POST提交的地址,一定得发送给django应用(如果用了nginx,就发送给nginx的入口端口)

超哥这里为了试验方便,将vue项目和django项目放在了一台服务器,通过nginx反向代理功能(8000端口),转发vue请求给django(9000)

准备编译打包vue项目,替换配置文件所有地址,改为服务器地址

sed -i 's/127.0.0.1/192.168.119.12/g' /opt/07-luffy_project_01/src/restful/api.js

确保vue的route模式是history

路径:opt/luffy/07-luffy_project_01/src/router/index.js

export default new Router({

linkActiveClass:'is-active',

mode: 'history',//改成history模式

此时打包vue项目,生成一个dist静态文件夹

npm run build

检查dist文件夹

[root@web02 07-luffy_project_01]# ls dist/

index.html static

nginx配置,找到vue的index.html首页文件即可

server { #用户访问域名或者ip,默认是nginx的80端口

listen 80;

server_name 192.168.119.12; #url匹配 / 也就是请求地址是192.168.119.12时,进入此location,返回vue的dist下index.html路飞学城首页

location / {

root /opt/07-luffy_project_01/dist;

index index.html;

}

}

配置后端代码,解决虚拟环境,保证项目干净隔离

[root@web02 opt]# cat requirements.txt

certifi==2018.11.29

chardet==3.0.4

crypto==1.4.1

Django==2.1.4

django-redis==4.10.0

django-rest-framework==0.1.0

djangorestframework==3.9.0

idna==2.8

Naked==0.1.31

pycrypto==2.6.1

pytz==2018.7

PyYAML==3.13

redis==3.0.1

requests==2.21.0

shellescape==3.4.1

urllib3==1.24.1

uWSGI==2.0.17.1

数据库用的是sqllite,不需要配置数据库了 购物车用都的是redis,因此要启动服务器的redis-server服务端

redis-server /etc/redis.conf

ps -ef|grep redis

redis-server *:6379

通过uwsgi启动项目

[uwsgi]

# Django-related settings

# the base directory (full path)

chdir = /opt/luffy_boy 拼多多帮助力入口

# Django's wsgi file

module = luffy_boy.wsgi

# the virtualenv (full path)

home = /opt/venv1

# process-related settings

# master

master = true

# maximum number of worker processes

processes = 1

# the socket (use the full path to be safe

socket = 0.0.0.0:9000

# clear environment on exit

vacuum = true

#后台运行uwsgi

daemonize=yes

(venv1) [root@web02 opt]# uwsgi --ini luffy_boy/uwsgi.ini

配置nginx

worker_processes 1;

events {

worker_connections 1024;

}

http {

include mime.types;

default_type application/octet-stream;

sendfile on;

keepalive_timeout 65;

server {

listen 80;

server_name 192.168.119.12;

location / {

root /opt/07-luffy_project_01/dist;

index index.html;

#这一条参数确保vue页面刷新时候,不会出现404页面

try_files $uri $uri/ /index.html;

}

error_page 500 502 503 504 /50x.html;

location = /50x.html {

root html;

}

}

server {

listen 8000;

server_name 192.168.119.12;

location / {

uwsgi_pass 0.0.0.0:9000;

include /opt/nginx/conf/uwsgi_params;

}

location /static {

alias /opt/static;

}

}

}

django+vue实现websocket即使通讯

Websocket 即时通讯 1.需求 即时通讯工具一定要保障的是即时性

基于现在的通讯协议HTTP要如何保障即时性呢?

2.短连接型 基于HTTP短连接如何保障数据的即时性

HTTP的特性就是无状态的短连接,即一次请求一次响应断开连接失忆,这样服务端就无法主动的去寻找客户端给客户端主动推送消息

1.轮询

即:客户端不断向服务器发起请求索取消息

优点:基本保障消息即时性

缺点:大量的请求导致客户端和服务端的压力倍增

2.长轮询

即:客户端向服务器发起请求,在HTTP最大超时时间内不断开请求获取消息,超时后重新发起请求

优点:基本保障消息即时性

缺点:长期占用客户端独立线程,长期占用服务端独立线程,服务器压力倍增

3.长连接型 基于socket长连接,由于长连接是双向且有状态的保持连接,所以服务端可以有效的主动的向客户端推送数据

1.socketio长连接协议

优点:消息即时,兼容性强

缺点:接入复杂度高,为保障兼容性冗余依赖过多较重

2.websocket长连接协议

优点:消息即时,轻量级,灵活适应多场景,机制更加成熟

缺点:相比socket兼容性较差

总体来说,Socketio紧紧只是为了解决通讯而存在的,而Websocket是为了解决更多更复杂的场景通讯而存在的

这里推荐Websocket的原因是因为,我们的Django框架甚至是Flask框架,都有成熟的第三方库

而且Tornado框架集成Websocket

4.Django实现Websocket 使用Django来实现Websocket服务的方法很多在这里我们推荐技术最新的Channels库来实现

4.1.安装DjangoChannels

pip3 install channels

views.py

import logging

from django.views.decorators.csrf import csrf_exempt

from spyne import Application, rpc, ServiceBase, Unicode, Iterable, String, Integer

from spyne.model.complex import ComplexModel

from spyne.protocol.soap import Soap11

from spyne.server.django import DjangoApplication

# 日志配置

logging.basicConfig(level=logging.DEBUG, filename='my_server.log')

logging.getLogger('server').setLevel(logging.DEBUG)

# 声明服务类,类的方法就是客户端访问的服务,直接访问方法名就行

# Unicode:参数类型,可有有多个参数,有几个写几个

# _returns:响应类型

class MyServer(ServiceBase):

# 返回字符类型

@rpc(Unicode, Unicode,_returns=Unicode)

def make_func(self, par1, par2):

print(par1)

#业务逻辑放这里

return "success"

# 返回数组类型

@rpc(Unicode, _returns=Iterable(Unicode))

def json_ret(self, params1):

ary = ["test", "111", "ceshi", "222"]

return ary

# 传入字典类型的参数,此User可以只传部分参数,或者一个都不传也可以,不能传没有的key,会报错

@rpc(User, _returns=Unicode)

def make_func(self, project):

print(User)

return "success"

# 传入字典类型的参数,需要声明一个类

class User(ComplexModel):

__namespace__ = 'User'

name = Unicode

phone = Unicode

address = Unicode

age = Integer

soap_app = Application([SServices],

'MyServer',

in_protocol=Soap11(validator="lxml"),

out_protocol=Soap11())

# DjangoApplication(django使用这个,还有其他好几几种,可以以脚本方式启动等等)

# 访问,urls.py中,映射server_app就可以了

server_app = csrf_exempt(DjangoApplication(soap_app))

测试test.py

from suds.client import Client

cilent=Client('http://ip:port/urls中的路由?wsdl')

# client.service.方法名 (调用格式)

ret = client.service.make_func()

还可以不使用django开发,脚本开发启动,直接运行文件即可访问

# Application is the glue between one or more service definitions, interface and protocol choices.

from spyne import Application

# @rpc decorator exposes methods as remote procedure calls

# and declares the data types it accepts and returns

from spyne import rpc

# spyne.service.ServiceBase is the base class for all service definitions.

from spyne import ServiceBase

# The names of the needed types for implementing this service should be self-explanatory.

from spyne import Iterable, Integer, Unicode

from spyne.protocol.soap import Soap11

# Our server is going to use HTTP as transport, It’s going to wrap the Application instance.

from spyne.server.wsgi import WsgiApplication

# step1

class HelloWorldService(ServiceBase):

@rpc(Unicode, Integer, _returns=Iterable(Unicode))

def say_hello(self, name, times):

for i in range(times):

yield u'Hello, %s' % name

# step2

soap_app = Application([HelloWorldService], 'hello',

in_protocol=Soap11(validator='lxml'),

out_protocol=Soap11())

# step3

wsgi_app = WsgiApplication(soap_app)

if __name__ == '__main__':

import logging

from wsgiref.simple_server import make_server

# configure the python logger to show debugging output

logging.basicConfig(level=logging.DEBUG)

logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG)

server = make_server('127.0.0.1', 8005, wsgi_app)

server.serve_forever()

离线创建Vue项目

从github上下载https://github.com/vuejs-templates/webpack 解压之后放到本地用户目录下的.vue-templates目录下,下载之后的压缩包为webpack-develop.zip,我们解压之后,需要更改目录名为webpack。用户目录下的目录为.vue-templates,注意文件夹名称前面的点(.)。这样,我们再进行vue init webpack vuedemo命令的时候,需要带上参数–offline表示离线初始化. 在运行 npm run dev

精彩链接

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧