一,创建项目(如d1)以及应用(如a1
django-admin startproject d1
cd d1
python manage.py startapp a1
二,解决跨域
首先安装一个第三方库
pip install django-cors-headers
接着在项目的settings.py文件中,按照下面的文本进行修改或者删除:
"""
Django settings for d1 project.
Generated by 'django-admin startproject' using Django 4.2.15.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-_m6rp7oy8ig+^$_nwyy(r36nh3xg+#t!+nk&1+u(#b=jwz_6r*"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# -----------------变动1---------------------
ALLOWED_HOSTS = ['*'] # 这里修改
# -----------------变动1---------------------
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
# ------------------变动2--------------------------
"corsheaders", # 添加这里
# ------------------变动2--------------------------
]
MIDDLEWARE = [
# ------------------变动3--------------------------
'corsheaders.middleware.CorsMiddleware', # 添加这里
'django.middleware.common.CommonMiddleware', # 添加这里
# ------------------变动3--------------------------
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
# ------------------变动4--------------------------
# "django.middleware.csrf.CsrfViewMiddleware",# 注释这一行
# ------------------变动4--------------------------
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
# ------------------变动5--------------------------
# ------最后添加从这里开始
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)
CORS_ALLOW_HEADERS = (
'authorization',
'content-type',
)
# 到这里结束
# ------------------变动5--------------------------
ROOT_URLCONF = "d1.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"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",
],
},
},
]
WSGI_APPLICATION = "d1.wsgi.application"
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
STATIC_URL = "static/"
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
三,写接口
一般写接口的第一步是在views.py中写函数,如下:
from django.http import JsonResponse
def check_account(request):
return JsonResponse({'state': '0', 'msg': "hello world"})
接着为了让这个接口生效,需要在urls.py中引用这个函数,如下:(f1和check_account函数是一一对应的关系,当然也可以是f2,f3等)
from django.contrib import admin
from django.urls import path
import a1.views
urlpatterns = [
path("admin/", admin.site.urls),
path("f1", a1.views.check_account),
]
这压根以来,通过“python .\manage.py runserver”启动项目后,浏览器输入“http://127.0.0.1:8000/f1”后即可得到返回的json对象
四,分app管理
这里推荐一个app有自己的urls.py,用来存放该app的接口,于是在a1文件夹下创建一个urls.py,写入如下:
from django.urls import path
import a1.views
urlpatterns = [
path("f1", a1.views.check_account),
]
接着让a1/urls.py连接上d1/urls.py,在d1/urls.py中写入:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path("admin/", admin.site.urls),
path("a1/", include('a1.urls'))
]
到这里,就完成了分app管理的操作。总结一下这个操作与之前不分app操作的区别,主要是之前访问的json数据通过“http://127.0.0.1:8000/f1”,现在通过“http://127.0.0.1:8000/a1/f1”来访问;之后再加上接口,也是需要在a1/urls.py中写入即可