Django视图函数和资源

文章目录

    • 1.视图
      • [1.1 文件or文件夹](#1.1 文件or文件夹)
      • [1.2 相对和绝对导入urls](#1.2 相对和绝对导入urls)
      • [1.3 视图参数](#1.3 视图参数)
      • [1.4 返回值](#1.4 返回值)
      • [1.5 响应头](#1.5 响应头)
      • [1.6 FBV和CBV](#1.6 FBV和CBV)
    • 2.静态资源
      • [2.1 静态文件](#2.1 静态文件)
      • [2.2 媒体文件](#2.2 媒体文件)

1.视图

1.1 文件or文件夹

1.2 相对和绝对导入urls

注意实现:不要再项目根目录做相对导入。

原则:

  • 绝对导入
  • 相对导入(层级深)

1.3 视图参数

python 复制代码
urlpatterns = [
    path('login/', account.login, name="login"),
    path('auth/', order.auth, name='auth'),
]
python 复制代码
from django.shortcuts import HttpResponse


def login(request):
    return HttpResponse("login")

requests是什么呢?

复制代码
对象,包裹,可以放很多东西。

requests是一个对象,存放了浏览器给咱们发过来的所有内容,所以含有:
- 请求相关所有的数据: 当前访问的url、请求方式、...
- django额外添加的数据
python 复制代码
from django.shortcuts import HttpResponse


def login(request):
    # 1.当前URL  /api/login/
    print(request.path_info)

    # 2.URL传递的参数
    print(request.GET)
    print(request.GET.get("age"))

    # 3.请求方式  GET/POST
    print(request.method)

    # 4.如果post请求,传递请求体(原始数据)
    print(
        request.body)  # b'{"code":"083Sjmll2yla694F3bll2DguCM2SjmlG","unionId":"oP6QCsyT_9bk1dfSaVf0GEV5Y-yE"}'  b'v1=123&v2=456'

    # 4.1 请求体+请求头       b'v1=123&v2=456'  +  content-type:application/x-www-form-urlencoded
    print(request.POST)
    print(request.POST.get("v1"))
    print(request.POST.get("v2"))

    # 4.2 请求体+请求头   文件
    print(request.FILES)  # 文件格式           + multipart/form-data
    print(request.FILES.get("n1"))
    print(request.FILES.get("n2"))

    # 5.请求头
    # {'Content-Length': '', 'Content-Type': 'text/plain', 'Host': '127.0.0.1:8000', 'Connection': 'keep-alive', 'Cache-Control': 'max-age=0', 'Sec-Ch-Ua': '" Not A;Brand";v="99", "Chromium";v="102", "Google Chrome";v="102"', 'Sec-Ch-Ua-Mobile': '?0', 'Sec-Ch-Ua-Platform': '"macOS"', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'Sec-Fetch-Site': 'none', 'Sec-Fetch-Mode': 'navigate', 'Sec-Fetch-User': '?1', 'Sec-Fetch-Dest': 'document', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7', 'Cookie': 'csrftoken=CdidpKSGbLxzmOXnbmlkvrZep1eJmKLAA81T73UjcjxEnMOa4YOZqtc849AkYfUy'}
    print(request.headers)

    # 5.1 请求头有个特殊的cookie
    # request.headers['cookie']  # 'csrftoken=CdidpKSGbLxzmOXnbmlkvrZep1eJmKLAA81T73UjcjxEnMOa4YOZqtc849AkYfUy;session=xxxx'
    # {'csrftoken': 'CdidpKSGbLxzmOXnbmlkvrZep1eJmKLAA81T73UjcjxEnMOa4YOZqtc849AkYfUy'}
    print(request.COOKIES)

    # 6.requests中其他值
    print(request.resolver_match)

    return HttpResponse("login")

1.4 返回值

  • HttpResponse
  • JsonResponse
  • render
  • redirect
python 复制代码
from django.shortcuts import HttpResponse, redirect, render
from django.http import JsonResponse


def auth(request):
    pass


def login(request):
    # 1.获取请求数据
    print(request)

    # 2.根据请求数据进行条件的判断 GET/POST   GET.get("xx")    POST.get("xx")

    # 3.返回数据

    # 3.1 字符串/字节/文本数据(图片验证码)
    # return HttpResponse("login")

    # 3.2 JSON格式(前后端分离、app小程序后端、ajax请求)
    # data_dict = {"status": True, 'data': [11, 22, 33]}
    # return JsonResponse(data_dict)

    # 3.3 重定向
    # return redirect("https://www.baidu.com")
    # return redirect("http://127.0.0.1:8000/api/auth/")
    # return redirect("http://127.0.0.1:8000/api/auth/")
    # return redirect("/api/auth/")
    # return redirect("/api/auth/")  # name
    #
    # from django.urls import reverse
    # url = reverse("auth")
    # return redirect(url)  # name
    # return redirect("auth")

    # 3.4 渲染
    # - a.找到 'login.html' 并读取的内容,问题:去哪里找?
    # -   默认先去settings.TEMPLATES.DIRS指定的路径找。(公共)
    # -   按注册顺序每个已注册的app中找他templates目录,去这个目录中寻找'login.html'
    # -   一般情况下,原则,那个app中的的模板,去哪个那个app中寻找。
    # - b.渲染(替换)得到替换完成的字符串
    # - c.返回浏览器
    return render(request, 'api/login.html')

1.5 响应头

python 复制代码
from django.shortcuts import HttpResponse, redirect, render
from django.http import JsonResponse


def login(request):
    res = HttpResponse("login")
    res['xx1'] = "hahaha"
    res['xx2'] = "hahaha"
    res['xx3'] = "hahaha"

    res.set_cookie('k1',"aaaaaaaa")
    res.set_cookie('k2',"bbbbbb")

    return res

1.6 FBV和CBV

  • FBV,视图用函数的形式编写。(目前主流)
  • CBV,视图用类的形式编写。

请注意,这一些都是表象,本质一模一样。

2.静态资源

静态资源:

  • 开发需要:css、js、图片。

    复制代码
    - 根目录的 /static/
    - 已经app目录下载 /static/ 文件夹下
  • 媒体文件:用户上传的数据(excel/pdf/video)

    复制代码
    - 根目录的 /media/

2.1 静态文件

python 复制代码
INSTALLED_APPS = [
    # 'django.contrib.admin',
    # 'django.contrib.auth',
    # 'django.contrib.contenttypes',
    # 'django.contrib.sessions',
    # 'django.contrib.messages',
    'django.contrib.staticfiles',
    "apps.api.apps.ApiConfig",
    "apps.web.apps.WebConfig",
]
...

STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)
  • 顺序: 项目根目录的static文件夹和已注册的app目录下的static文件夹

  • 多app开发:各自app的图片放在各自 /static/app名字/。。。

  • 在开发过程中

    • 禁止

      html 复制代码
      <img src="/static/api/1.png">
    • 建议

      html 复制代码
      {% load static %}
      
      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>Title</title>
      </head>
      <body>
      <h1>登录页面</h1>
      <a href="/xxx/xxxxx/">调换dao xx</a>
      <a href="{% url 'login' %}">跳转</a>
      
      <img src="{% static 'api/1.png' %}">
      
      </body>
      </html>

2.2 媒体文件

urls.py

python 复制代码
from django.contrib import admin
from django.urls import path, re_path, include
from django.conf.urls.static import static
from django.conf import settings

from apps.api import views


# 很多功能,很多URL
urlpatterns = [
    path('api/', include('apps.api.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
相关推荐
寂寞旅行30 分钟前
向量数据库Milvus的使用
数据库·milvus
闻哥1 小时前
Redis事务详解
java·数据库·spring boot·redis·缓存·面试
道亦无名1 小时前
aiPbMgrSendAck
java·网络·数据库
面向对象World4 小时前
正点原子Mini Linux 4.3寸800x480触摸屏gt115x驱动
linux·服务器·数据库
dinga198510265 小时前
mysql之联合索引
数据库·mysql
微风中的麦穗5 小时前
【SQL Server 2019】企业级数据库系统—数据库SQL Server 2019保姆级详细图文下载安装完全指南
大数据·数据库·sqlserver·云计算·个人开发·运维必备·sqlserver2019
zjttsh6 小时前
MySQL加减间隔时间函数DATE_ADD和DATE_SUB的详解
android·数据库·mysql
顾北126 小时前
SpringCloud 系列 04:Gateway 断言 / 过滤器 / 限流 一站式落地指南
java·开发语言·数据库
禹凕6 小时前
MYSQL——基础知识(NULL 值处理)
数据库·mysql
码云数智-大飞6 小时前
SQL Server 无法启动?常见原因及详细解决方法指南
数据库