Django框架

开发流程

开发服务器的启动配置

  • 指定解释器

  • 项目启动:python manage.py runserver

    • 指定端口:python manage.py runserver 2758

      • 也可在pycharm中配置

    • 指定ip:python manage.py runserver 0.0.0.0:8000

      • 需要在settings.py中配置ALLOW_HOSTS

  • 创建模块:python manage.py startapp hello

 

从请求到响应

URL的设计

  1. 使用正则表达式:

  2. 使用参数类型:/article/<int>:/article/123

  3. 固定字符串:/hello

path()参数解释

  • route:URL匹配规则

  • view:视图函数

  • name:路由的名称

  • **kwargs:其他参数

include()参数解释

  • urls: URL匹配规则列表

  • namespace:命名空间

扩展知识

反向解析url

from django.urls import reverse

def hello_world(request):
   print(reverse('hello_world'))
   return HttpResponse('hello world')

 

在视图中处理业务逻辑

响应HTML内容

def hello_html(request):
   html = """
  <html>
      <body>
          <h1 style="color:#f00">hello html</h1>      
      </body>
  </html>
  """
   return HttpResponse(html)

获取URL参数

获取URL中的指定类型的参数

URL规则: path('article/<int:month>/',views.article_list,name='article_list')

输入URL:

http://127.0.0.1:8000/article/05/

视图编写

def article_list(request, month):
   return HttpResponse('article: {}' .format(month))

获取URL中的正则匹配的参数

URL正则:

re_path(r'^article/(?P<month>0?[1-9]1[012])/$views.article, name='article list)

输入URL:

http://127.0.0.1:8000/article/05/

视图编写

def article_list(request, month):
   return HttpResponse('article: {}' .format(month))

获取请求中(GET/POST等)参数

输入URL:

http://127.0.0.1:8000/search/?name=五月天

视图编写:

def search(request):
   name = request.GET.get('name', '')
   print(name)
   return HttpResponse('查询成功')

 

从文件响应HTML内容

从磁盘文件中读取HTML

  1. 从地盘读取HTML文件

  2. 替换HTML中的特殊字符

  3. 发送给浏览器

render_to_string()

  • template_name 模板名称

  • context=None: 模板上下文对象(dict)

  • request=None:请求对象

  • using=None:模板引擎名称(如:Jinja2)

def render_str(request):
   template_name = 'index.html'
   html = render_to_string(template_name=template_name)
   return HttpResponse(html)

render()

  • context:模板上下文对象 (dict)

  • content_type: MIME类型,默认为text/html

  • status: HTTP状态码

  • using: 模板引擎名称 (如: Jinja2)

def render_html(request):
   return render(request,'index.html')

 

配置settings.py

  • DIRS:查找的名称

  • APP_DIRS:是否在模块下寻找

TEMPLATES = [
  {
       "BACKEND": "django.template.backends.django.DjangoTemplates",
       "DIRS": ['templates'],
       "APP_DIRS": False,#是否在模块中找templates
       "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",
          ],
      },
  },
]

 

请求响应对象

请求与响应

请求对象

  • 请求方式method(POST/GET/...)

  • 请求头信息META/headers

    • REMOTE ADDR一请求的IP地址

    • HTTP USER AGENT--用户请求终端信息

  • 获取请求传递参数

    • GET-GET请求参数

    • POST-POST请求参数

    • COOKIES-cookie信息

    • FILES-文件信息

在线JSON校验格式化工具(Be JSON)

def http_request(request):
   print(request.method)
   headers = request.META
   print(headers)
   ua = request.META.get('HTTP_USER_AGENT',None)
   print(ua)
   print(request.headers)
   print(request.headers['User-Agent'])
   name = request.GET.get('name')
   print(name)
   return HttpResponse('响应')

响应对象

  • HttpResponse

  • HttpResponseRedirect--重定向

  • JsonResponse一-响应json

  • FileResponse-响应文件

HttpResponse

  • status设置HTTP响应状态码

  • status code查看HTTP响应状态码

  • content type设置响应的类型

  • write写入响应内容

def http_response(request):
   res = HttpResponse('响应内容', status=201)
   res.status_code = 204
   print(res.status_code)
   return res

 

JsonResponse

def http_response(request):
   user_info = {
       'name': '张三',
       'age': 12
  }
   return JsonResponse(user_info)

 

FileResponse

from django.http import FileResponse
response = FileResponse(open('myfile.png,'rb'))

 

常见Content-Type

  • text/html-超文本标记语言文本 (HTML)

  • text/plain-普通文本

  • text/xml-XML文档

  • image/png、image/jpeg、image/gif-图片或图形

  • application/json-json数据类型

 

视图快捷方法

重定向

比如用户请求错误,重定向到404

实现URL访问的重定义

使用HttpResponseRedirect重定向

def no_data_404(request):
   return HttpResponse('404')


def article_detail(request, article_id):
   """文章详情,id从1000开始的整数
      :param article_id:文章ID
  """
   if article_id < 1000:
       return HttpResponseRedirect(reverse('no_data_404'))
   return HttpResponse('文章{}的内容'.format(article_id))

此处用到了反向解析reverse

使用redirect()快捷方式

def article_detail(request, article_id):
   """文章详情,id从1000开始的整数
      :param article_id:文章ID
  """
   if article_id < 1000:
       return redirect('no_data_404')  # 传入视图函数的名称
       # return redirect('hello/not/found/') #也可以传入地址
       # return redirect('www.baidu.com') #跳转到外部链接

   return HttpResponse('文章{}的内容'.format(article_id))

 

内置的视图及重写

内置的错误处理视图

  • 400 Bad Request

  • 403 Forbidden

  • 404 Not Found

  • 500 Internal Server Error

def hello_china(request):
   raise
   return HttpResponse('hello china')

 

重写内置的错误处理视图

  1. 在项目urls.py中添加配置

  2. handler500="my_project.views.page_500"

  3. 切换到生产模式DEBUG=False(能看到视图效果)

#urls.py
from django.contrib import admin
from django.urls import path, include
from test_django.views import page_500
urlpatterns = [
   path("admin/", admin.site.urls),
   path("hello/", include('hello.urls'))
]

handler500 = page_500
#views.py
from django.http import HttpResponse


def page_500(request):
   return HttpResponse('服务器正忙')

 

static.serve处理静态文件

  • 在项目settings.py中添加配置

    MEDIA_URL = '/media/'

    MEDIA_ROOT = os.path.join(BASE_DIR, 'medias')

     

  • 在项目urls.py中添加配置

    from django.views.static import serve
    from test_django import settings
    if settings.DEBUG:
       urlpatterns += [
           re_path(r'^media/(?P<path>.*)$', serve, {
               'document_root': settings.MEDIA_ROOT,
          }),
      ]

 

使用class重写视图

基于类的视图

  • 视图是一个可调用对象,可以接收一个请求然后返回一个响应

  • 基于类的视图可以结构化你的视图

  • 基于类的视图可以利用继承和混合重用代码

  • 内置的视图拿来即用,代码更简洁

TemplateView

  1. 继承视图

    django.views.generic.TemplateView

  2. 配置模板地址

  3. 配置URL

def index(request):
   return render(request, 'index.html')


class HomeView(TemplateView):
   template_name = 'home.html'
    path('index/',index,name='index'),
   path('home/',HomeView.as_view(),name='home')

原理解析

  • 从项目主目录寻找模板文件

  • 从app的模板目录寻找模板文件

 

内置通用视图

  • django.views.generic.ListView -- 列表类数据的封装,如:景点列表支持分页

  • django.views.generic.DetailView -- 详情类数据的封装,如:景点详情

 

 

 

posted @ 2023-05-09 18:18  qfzwy  阅读(72)  评论(0)    收藏  举报