向服务器传参
- 通过url - path传参
path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail),
- 查询字符串方式传参
http://localhost:8000?key1=value1&key2=value2 ;
- (body)请求体的方式传参,比如文件,照片等
- 在http的报文的头(header)中传参
传参练习
子应用
from django.http import HttpResponse
from django.shortcuts import render# Create your views here.
def index(request):return HttpResponse("视图测试...")def weather(request,city,date):return HttpResponse(f'weather :城市 {city} 日期:{date}')
from django.contrib import admin
from django.urls import path,include
from .views import *
urlpatterns = [path('index/',index ),# 路由转换器提取path('weather/<str:city>/<int:date>', weather),
]
Django中的QueryDict对象
定义在django.http.QueryDict
HttpRequest对象的属性GET、POST都是QueryDict类型的对象
与python字典不同,QueryDict类型的对象用来处理同一个键带有多个值的情况
获取请求路径中的查询字符串参数(形如?k1=v1&k2=v2),可以通过request.GET属性获取,返回
QueryDict对象。
from django.http import HttpResponse
from django.shortcuts import render# Create your views here.
def index(request):return HttpResponse("视图测试...")def weather(request, city, date):return HttpResponse(f'weather :城市 {city} 日期:{date}')def qs(request):"""查询字符串获取"""a = request.GET.get("num")b = request.GET.get("price")b_list = request.GET.getlist("price")return HttpResponse(f'参数a:{a}, 参数b:{b} 参数b(列表):{b_list}')
from django.contrib import admin
from django.urls import path,include
from .views import *
urlpatterns = [path('index/',index ),# 路由转换器提取path('weather/<str:city>/<int:date>', weather),path('qs/',qs),
]
请求体
get - post:两种不同的请求方式
请求体数据格式不固定,可以是表单类型字符串,可以是JSON字符串,可以是XML字符串,应区别对
待。
可以发送请求体数据的请求方式有POST、PUT、PATCH、DELETE
Django默认开启了CSRF防护,会对上述请求方式进行CSRF防护验证,在测试时可以关闭CSRF防护机制,方法为在settings.py文件中注释掉CSRF中间件,如:
表单类型 Form Data
前端发送的表单类型的请求体数据,可以通过request.POST属性获取,返回QueryDict对象。
from django.http import HttpResponse
from django.shortcuts import render# Create your views here.
def index(request):return HttpResponse("视图测试...")def weather(request, city, date):return HttpResponse(f'weather :城市 {city} 日期:{date}')def qs(request):"""查询字符串获取"""a = request.GET.get("num")b = request.GET.get("price")b_list = request.GET.getlist("price")return HttpResponse(f'参数a:{a}, 参数b:{b} 参数b(列表):{b_list}')def regist(request):"""注册表单1.取表单,返回表单2.获取用户通过表单填写的用户信息"""if request.method == 'GET':return render(request,'reqister.html')elif request.method == 'POST':return HttpResponse('post请求')
"""
Django settings for HighDjangoProject project.Generated by 'django-admin startproject' using Django 2.2.8.For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""import os# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '3^9vuh6$ya+bh0bkdj4)m7_0wji2i+o1gh7rm@2)1*sosk(n_h'# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = TrueALLOWED_HOSTS = []# Application definitionINSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','urldemo.apps.UrldemoConfig',# 手动注册子应用'viewdemo.apps.ViewdemoConfig'
]MIDDLEWARE = ['django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.middleware.common.CommonMiddleware',# 'django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware',
]ROOT_URLCONF = 'HighDjangoProject.urls'TEMPLATES = [{'BACKEND': 'django.template.backends.django.DjangoTemplates','DIRS': [os.path.join(BASE_DIR, 'templates')],'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 = 'HighDjangoProject.wsgi.application'# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databasesDATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3','NAME': os.path.join(BASE_DIR, 'db.sqlite3'),}
}# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validatorsAUTH_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/2.2/topics/i18n/LANGUAGE_CODE = 'en-us'TIME_ZONE = 'UTC'USE_I18N = TrueUSE_L10N = TrueUSE_TZ = True# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/STATIC_URL = '/static/'
from django.contrib import admin
from django.urls import path,include
from .views import *
urlpatterns = [path('index/',index ),# 路由转换器提取path('weather/<str:city>/<int:date>', weather),path('qs/',qs),path('register/', regist),
]
非表单类型 Non-Form Data
非表单类型的请求体数据 (ajax提交数据),Django无法自动解析,可以通过request. body属性获取最
原始的请求体数据,自己按照请求体格式(JSON、XML等)进行解析。request.body返回bytes类
型
请求头
可以通过request.META属性获取请求头headers中的数据,request.META为字典类型。
常见的请求头如:
CONTENT_LENGTH – The length of the request body (as a string).
CONTENT_TYPE – The MIME type of the request body.
HTTP_ACCEPT – Acceptable content types for the response.
HTTP_ACCEPT_ENCODING – Acceptable encodings for the response.
HTTP_ACCEPT_LANGUAGE – Acceptable languages for the response.
HTTP_HOST – The HTTP Host header sent by the client.
HTTP_REFERER – The referring page, if any.
HTTP_USER_AGENT – The client’s user-agent string.
QUERY_STRING – The query string, as a single (unparsed) string.
REMOTE_ADDR – The IP address of the client.
REMOTE_HOST – The hostname of the client.
REMOTE_USER – The user authenticated by the Web server, if any.
REQUEST_METHOD – A string such as “GET” or “POST” .
SERVER_NAME – The hostname of the server.
SERVER_PORT – The port of the server (as a string).
其他常用HttpRequest对象属性
requtest.GET
requtest.POST
request.META
method:一个字符串,表示请求使用的HTTP方法,常用值包括:‘GET’、‘POST’。
user:请求的用户对象。(如获取user属性值,需访问django_session表 makemigrations
migrate)
path:一个字符串,表示请求的页面的完整路径,不包含域名和参数部分。
encoding:一个字符串,表示提交的数据的编码方式。
如果为None则表示使用浏览器的默认设置,一般为utf-8。
这个属性是可写的,可以通过修改它来修改访问表单数据使用的编码,接下来对属性的任何
访问将使用新的encoding值。
FILES:一个类似于字典的对象,包含所有的上传文件