使用Vue写前端页面;
使用Django处理后台逻辑,生成数据返给前端;
利用axios发送网络请求,包含get请求、post请求、携带参数的请求;
Django如何接收不同类型请求头对应的请求参数,例如表单数据、json数据;
解决Vue+Django的跨域问题;
解决Vue+Django发送post请求时的CSRF验证问题;
我会用几篇博客来完整地说一下项目的搭建过程
1. 查看python、django版本
windows下切换至cmd窗口
查看python版本C:\Users\HanMK\Desktop>python --version
Python 3.7.2查看django版本C:\Users\HanMK\Desktop>python -m django --version2.2.1
2. 创建项目
cd 到一个你想放置你代码的目录,然后运行以下命令
C:\Users\HanMK\Desktop>django-admin startproject mysite
将会在当前目录下创建一个mysite目录,结构如下
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
asgi.py
3. 启动服务
首先切换到外层的mysite目录,即项目的根目录 mysite/
然后执行 python manage.py runserver
C:\Users\HanMK\Desktop\mysite>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
March 23, 2020 - 11:53:58
Django version 2.2.1, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
更换端口:
$ python manage.py runserver 8080
更改监听所有服务器的公开IP
$ python manage.py runserver 0:8000
4. 创建应用
在 Django 中,每一个 应用 都是一个 Python 包,并且遵循着相同的约定。 进入 manage.py 所在的目录下,然后运行这行命令来创建一个 create_data 应用:
C:\Users\HanMK\Desktop\mysite>python manage.py startapp create_data
这将会创建一个 create_data 目录,它的目录结构大致如下:
create_data/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
5. 创建视图
因为功能比较简单,所以我的业务处理逻辑直接在视图文件中编写了
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from django.views.decorators.http import require_http_methods
import faker, json
from django.middleware.csrf import get_token
# Create your views here.
fake = faker.Faker(locale='zh_CN') # 初始化,指定生成中文格式数据def create_phone():
"""生成电话"""
phones = [fake.phone_number() for _ in range(5)] # 列表推导,把生成的数据组成一个列表
return " ".join(phones)
def phone(request):
data = create_phone()
return HttpResponse(data)
def create_id(num):
"""生成身份证"""
identity_ids = [fake.ssn() for i in range(int(num))]
return " ".join(identity_ids)
@require_http_methods(['GET', 'POST'])
def id(request):
num = request.POST.get("num") # 如果"Content-type"="application/x-www-form-urlencoded"
# num = json.loads(request.body).get("num") # 如果"Content-type"="application/json"
print(num)
if num == "" or num is None:
data1 = create_id(5)
else:
data1 = create_id(num)
return HttpResponse(data1)
def create_name(num):
"""生成姓名"""
names = [fake.name() for i in range(int(num))]
return " ".join(names)
def name(request):
num = request.GET.get("num")
print(num)
if num == "" or num is None:
data = create_name(20)
else:
data = create_name(num)
return HttpResponse(data)
注意:上述代码中id()视图方法和name()方法中,分别预留了一个参数num,是需要从前端请求中获取的,这里我们先定义出来,后续写前端页面时,需要从页面输入num参数传递给后端
6. 配置路由
关于django的路由配置,我以前写过一篇关于如何理解它的文章,有兴趣可以看看,传送门:django:理解urls路由
在create_data目录里新建一个 urls.py 文件,你的应用目录现在看起来应该是这样:
create_data/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
urls.py
views.py
在 create_data/urls.py 中,输入如下代码:
# coding: utf-8
# author: hmk
from django.urls import path
from . import views
urlpatterns = [
path('', views.main, name='main'),
path('phone', views.phone, name='phone'),
path('id', views.id,name='id'),
path('name', views.name,name='name'),
]
下一步是要在根 URLconf 文件中指定我们创建的 create_data.urls 模块。 在 mysite/urls.py 文件的urlpatterns 列表里插入一个 include(), 如下:
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.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, include
urlpatterns = [
path('polls-admin/', admin.site.urls),
path('polls/', include('polls.urls')),
path('create_data/', include('create_data.urls')), # 指定create_data.urls模块
]
OK,这样就配置好了,可以试一下看看配置的视图是否生效,
在浏览器输入:http://localhost:8000/create_data/phone,
from django.views.decorators.http import require_http_methods
@require_http_methods(['POST'])
def phone(request):
data = create_phone()
return HttpResponse(data)
django后端部分基本上写好了,接下来写前端
喜欢记得来一个