Django环境准备
1、下载django执行命令 pip install django
2、新建django项目执行命令 djangoadmin startproject mytest项目名称),以上命令会在当前目录创建一个名为mytest的Django项目
3、运行django项目执行命令 python manage.py runserver
4、下载ninja,执行命令pip install django-ninja

Django跨域配置
1、执行命令 pip install djangocorsheaders
2、在settings.py
(1)INSTALLED_APPS里添加corsheaders
(2)MIDDLEWARE里添加corsheaders.middleware.CorsMiddleware
(3)增加CORS_ORIGIN_ALLOW_ALL=True

Vue环境准备
1、下载安装node.js,下载地址 https://nodejs.org/en
2、创建vue项目执行npm init vue@latest,可参考 https://cn.vuejs.org/guide/quickstart.html#creating-a-vueapplication

3、下载elementplusnpm install elementplussave
4、下载vuerouternpm install vuerouter

Vue代码
1、App.vue文件

<template>
  <a-config-provider :locale="locale">
    <div>
      <router-view></router-view>
    </div>
  </a-config-provider>
</template>

<script setup>
</script>

<style>
#app {
  background-color: #f1f4f9;
  min-height: 100vh;
}
</style>

2、index.html文件

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <link rel="icon" href="/favicon.ico">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vite App</title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.js"></script>
  </body>
</html>

3、main.js文件

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";

import axios from "axios";
import { message } from "ant-design-vue";
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'

// 全局配置
axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL;
message.config({ duration: 2, top: "50px", maxCount: 3 });

const app = createApp(App)
app.use(ElementPlus)
app.use(router).mount("#app");

4、index.js文件配置路由请求地址http://ip:port/#/test

import { createRouter, createWebHashHistory } from "vue-router";

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    { path: "/test", component: () => import("../views/TestView.vue") },
  ],
});

export default router;

5TestView.vue

<template>
  <div class="site-main">
    <el-form-item>
      <el-button type="primary" @click="getNum()">获取随机数</el-button>
      <el-input type='text' style="width: 200px;" placeholder="随机数" v-model="num"></el-input>
      <el-input-number v-model="numNo" :min="1" :max="5" />
    </el-form-item>
  </div>
</template>

<script>
import axios from "axios";

export default {

  data() {
    return {
      num: '',
      numNo: 1,
    }
  },
  methods: {
    // 生成随机数
    getNum() {
      axios.post("/getRandom",{ "numNo": this.numNo}).then(({ res, data }) => {
        this.num = data.data
      })
    }
  }
}

</script>

<style scoped>
.site-main {
  background: #fff;
  padding: 24px;
  height: 100vh;
  width: 100%;
}
</style>

python代码
1、获取n个随机数实现方法

import random

def createRandom(numNo):
    numList=[]
    for i in range(0,numNo):
        num = random.randint(10, 99)
        numList.append(num)
    return numList

# if __name__ == "__main__":
#     a=createRandom(2)
#     print(a)

2、与前端交互请求url获取请求参数返回结果

import json
from django.http import JsonResponse
from ninja import Router
from impl.createTest import createRandom

router = Router()

@router.post("/getRandom")
def getRandom(request):
    numNo = json.loads(request.body).get("numNo")
    numList=createRandom(numNo)
    return JsonResponse({'code': 200, 'data': numList}, charset="utf-8")

 3、urlpatterns配置

"""proinit URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from ninja import NinjaAPI
from viewpackage import viewTest

app = NinjaAPI()
app.add_router('', viewTest.router)
urlpatterns = [
    # path('admin/', admin.site.urls),
    path('', app.urls)
]

页面显示
1、启动后端服务python manage.py runserver
2、启动前端服务npm run dev
3、请求http://ip:port/#/test启动前端服务是会显示ip:port

原文地址:https://blog.csdn.net/m0_38080921/article/details/131413192

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_24662.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注