一、修改dj11项目下的urls.py,
path后面第一个参数默认可以为空'',这样访问的时候就不需要加上books/路径,原:path('books/', include('books.urls'))
代码如下:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
# path后面第一个参数默认可以为空'',这样访问的时候就不需要加上books/路径,原:path('books/', include('books.urls'))
path('', include('books.urls'))
]
二、re_path用法
例如我要查询某某城市某一天的天气,
http://127.0.0.1:8000/weather/cs/20211128 城市/日期
re_path(r'^weather/(?P[a-z]+)/(?P d{8})/$')
详细代码如下:books/urls.py
from django.urls import path,re_path
from .import views
app_name = 'books'
urlpatterns = [
# 第一个参数: 路由名 第二个参数: 匹配 的视图函数,
# name= 是给子路由进行命名 的 (起别名)
path('index/',views.index,name='index'),
# re_path和path的区别 路由的匹配不一样 re_path 有个^开始 $ 结束
# http://127.0.0.1:8000/weather/cs/20211128 城市日期
re_path(r'^weather/(?P[a-z]+)/(?Pd{8})/$',views.weather,name='weather'),
]
books/views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
# 定义一个视图函数
def index(request):
return HttpResponse ('你好,DJANGO! !!!!')
def weather(request,city,year): # 请求
print(city)
print(year)
return HttpResponse('查询xx城市天气')
打开浏览器http://127.0.0.1:8000/weather/cs/20211129/运行效果如下:
城市的英文字符匹配:(?P[a-z]+)
日期的匹配:(?P
三、通过请求获取参数
网页中“?”后面携带的参数如何获取到:http://127.0.0.1:8000/qs/?a=100&b=234
3.1添加路由,urls.py文件下,代码如下:
path('qs/',views.querys,name='querys'),
3.2定义querys的函数接收
views.py代码如下:
def querys(request):
print(request)
# get获取数据,getlist获取多个数据
a = request.GET.get("a")
b = request.GET.get("b")
print(a)
print(b)
return HttpResponse("获取请求的参数")
四、POST表单参数的获取
views.py代码如下:
# 获取表单数据
def query(request):
name = request.POST.get("name")
print(name)
pwd = request.POST.get("pwd")
print(pwd)
return HttpResponse("获取表单数据")
urls.py添加路由代码如下:
path('bd/',views.query,name='query'),
利用Postman模拟浏览器发送表单数据:
注意需要将:setting.py文件下的改行
'django.middleware.csrf.CsrfViewMiddleware',注释,否则会报403错误。
通过Postman模拟浏览器发送表单数据,在pycharm下返回表单数据
五、非表单Json数据的获取
http://127.0.0.1:8000/js/通过构造json数据利用Postman模拟浏览器发送json数据
views.py代码如下:
# 非表单json数据的获取
def get_body_json(request):
#获取json数据
json_bytes = request.body
print(json_bytes)
# 转换为字符串类型数据
import json
json_str = json_bytes.decode()
print(json_str)
# 再转换为字典格式数据
josn_dict = json.loads(json_str, encoding='utf-8')
print(josn_dict)
return HttpResponse("获取json数据成功")
urls.py文件代码如下:
path('js/',views.get_body_json),
最终pycharm运行结果如下:



