• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

vue项目集成到flask和django项目展示

武飞扬头像
langy1990
帮助1

vue项目配置

1.vue.config.js或者webpack.conf.js配置实例

const config = require('./src/config/env');

const { resolve } = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const url = require('url')

//publicPath需要根据线上环境来具体修改
// /表示网站的根目录 线上环境可能是/static/
const publicPath = '/static/'

module.exports = (options = {}) => ({
  //webpack-dev-server -d --inline --hot --env.dev
  //options.dev 是在执行npm run dev调用webpack命令的时候传递过来的
  entry: {
    // vendor: './src/vendor',
    index: './src/main.js'
  },
  output: {
    //__dirname表示项目的根目录
    path: resolve(__dirname, 'dist'),
    filename: options.dev ? '[name].js' : '[name].js?[chunkhash]',
    chunkFilename: '[id].js?[chunkhash]',
    //src="https://blog.51cto.com/yxh1990/..../index.js?be5
    //publicPath的作用是在编译后的html中引入资源文件时候在最前面添加的路径
    publicPath: options.dev ? '/assets/' : publicPath
  },
  module: {
    rules: [{
        test: /\.vue$/,
        use: ['vue-loader']
      },
      {
        test: /\.js$/,
        use: ['babel-loader'],
        exclude: /node_modules/
      },
      {
        test: /\.html$/,
        use: [{
          loader: 'html-loader',
          options: {
            root: resolve(__dirname, 'src'),
            attrs: ['img:src', 'link:href']
          }
        }]
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader', 'postcss-loader']
      },
      {
        test: /favicon\.png$/,
        use: [{
          loader: 'file-loader',
          options: {
            name: '[name].[ext]?[hash]'
          }
        }]
      },
      {
        test: /\.(png|jpg|jpeg|gif|eot|ttf|woff|woff2|svg|svgz)(\?. )?$/,
        exclude: /favicon\.png$/,
        use: [{
          loader: 'url-loader',
          options: {
            limit: 10000
          }
        }]
      }
    ]
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      //被多次引用的模块自动提取并生成指定名称的文件
      names: ['vendor', 'manifest']
    }),
    new HtmlWebpackPlugin({
      //把编译后的js文件引入到template指定的html文件中
      template: 'src/index.html'
    })
  ],
  resolve: {
    alias: {
      '~': resolve(__dirname, 'src')
    }
  },
  //shift 右键 => 快速在当前目录打开cmd窗口
  //webpack-dev-server -d --inline --hot --env.dev
  devServer: {
    host: '0.0.0.0',  //webpack启动的服务器IP
    port: 8090,       //webpack启动web服务占用的端口
    proxy: {
      '/api/': {  
       //把js中请求url中字符串到/api/结尾的字符串替换成http://127.0.0.1:3000
        target: config.apiServer,
        changeOrigin: true
        // pathRewrite: {
        //   '^/api': ''
        // }
        //要不要pathRewrite需要根据后台项目设置的接口地址来确定
      }
    },
    historyApiFallback: {
      index: url.parse(options.dev ? '/assets/' : publicPath).pathname
    }
  },
  devtool: options.dev ? '#eval-source-map' : '#source-map'
})

View Code

2.配置两个重要的参数publicPath和devServer 这两个参数的配置都需要根据具体环境来配置

const publicPath = '/static/' 
    devServer: {
      host: '0.0.0.0',
      port: 8080,
      proxy: {
        '/api/': {
              target: config.apiServer,
              changeOrigin: true
              // pathRewrite: {
                 //   '^/api': ' '
            // }
          }
     }

  1.http://127.0.0.1:8080/api/account/users/login/   通过proxy后实际被转发的地址为http://127.0.0.1:3000/api/account/users/login/

学新通

 publicPath的作用是在编译后的html中引入其他静态资源文件时候在最前面添加的路径 查看编译后的index.html

学新通

3. 编译前端项目

    执行npm run build会在前端项目中生成一个dist目录 里面包含所有编译好的文件

    到此前端项目所有的操作完毕

    

学新通

 flask项目配置

     1.在flask项目的根目录下创建一个static目录 把dist目录下的所有文件拷贝到static目录下

     

学新通

    2.处理项目的根路由 如果请求flask的根路由就返回static目录下的index.html即可

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import config


app = Flask(__name__)

@app.route("/")
def index():
    return app.send_static_file('index.html')

app.config.from_object(config)
db = SQLAlchemy(app)

View Code

   3.处理api鉴权问题 如果请求的资源是static目录下的 则不需要进行鉴权 直接把资源返回给客户端

def auth_middleware():
    if request.path == '/api/account/users/login/' or request.path.startswith('/api/apis/configs/') \
            or request.path.startswith('/api/apis/files/') or "static" in request.path or "favicon.ico" in request.path or "/" == request.path:
        return None
    token = request.headers.get('X-TOKEN')
    if token and len(token) == 32:
        g.user = User.query.filter_by(access_token=token).first()
        if g.user and g.user.is_active and g.user.token_expired >= time.time():
            g.user.token_expired = time.time()   8 * 60 * 60
            g.user.save()
            return None
    return json_response(message='Auth fail, please login'), 401

View Code

   4.最终效果

学新通

django项目配置

   1.修改django的settings.py文件

STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
LOGIN_URL = '/portals/login/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")

View Code

  2.找到LOGIN_URL对应的view处理函数

urlpatterns = [
    # portal login
    path('register/', user.register, name='register'),
    path('login/', user.login, name='login')
]

urls.py

def login(request):

    ok = check_if_initailized()
    if not ok:
        initial_platform_env()

    if request.user.is_authenticated:
        return HttpResponseRedirect('/')

    if request.method == "GET":
        form = JadeLoginForm(request)
        return render(request, 'portals/index.html', locals())

views-handler

3.把vue编译后的文件存放到指定目录

  1.把编译后的index.html存放到templates/portals目录下

  2.把编译后的除了index.html以外的文件全部拷贝到static下的dist目录(具体拷贝到哪个目录需要根据实际情况)

  3.static目录和templates目录默认都是在项目的根目录下 是属于项目的第一级子目录

学新通

 4.打开浏览器访问 实现如下效果

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhibgekk
系列文章
更多 icon
同类精品
更多 icon
继续加载