开启一个最简单的服务

本文介绍了Django中视图函数的定义及其注意事项,包括接收request参数和返回HttpResponse对象。同时,详细阐述了URL配置的三种方式,从视图方式到基于视图类的方式,并展示了在不同层级的urls.py文件中的实现。最后,讲解了如何设置项目模板文件夹,注册模板并在视图中使用render函数进行内容渲染。
摘要由CSDN通过智能技术生成

1. 第一步:定义视图函数(可以伪代码)

1.1 在自己定义的apps中的views.py文件中进行定义

HttpResponse 源码

class HttpResponseBase:
    """
    An HTTP response base class with dictionary-accessed headers.

    This class doesn't handle content. It should not be used directly.
    Use the HttpResponse and StreamingHttpResponse subclasses instead.
    """

    status_code = 200

    def __init__(self, content_type=None, status=None, reason=None, charset=None):
        # _headers is a mapping of the lowercase name to the original case of
        # the header (required for working with legacy systems) and the header
        # value. Both the name of the header and its value are ASCII strings.
        self._headers = {}
        self._closable_objects = []
        # This parameter is set by the handler. It's necessary to preserve the
        # historical behavior of request_finished.
        self._handler_class = None
        self.cookies = SimpleCookie()
        self.closed = False
        if status is not None:
            try:
                self.status_code = int(status)
            except (ValueError, TypeError):
                raise TypeError('HTTP status code must be an integer.')

            if not 100 <= self.status_code <= 599:
                raise ValueError('HTTP status code must be an integer from 100 to 599.')
        self._reason_phrase = reason
        self._charset = charset
        if content_type is None:
            content_type = '%s; charset=%s' % (settings.DEFAULT_CONTENT_TYPE,
                                               self.charset)
        self['Content-Type'] = content_type

代码

from django.shortcuts import render
from django.http import HttpResponse
  
# Create your views here.
  
# 视图函数
def index(param):
	# 视图函数必须有返回值,必须有参数
    print('----->这是获取的参数')
    print(param)
    
    print('----->这是处理主页index的视图函数')
    return HttpResponse('ok')

1.2 视图函数定义注意点

1.视图函数需要至少一个参数,用来接收框架自定传递过来的request对象
2.视图函数需要一个返回值,必须返回的是HttpResponse对象

2. 第二步:定义路径,家那个路径和视图函数进行映射

2.1 路径匹配

在这里插入图片描述

2.1.1 第一种配置

在这里插入图片描述

2.2 第一种路径定义方式(视图方式)

在项目所在的同名文件夹下的urls中进行定义

from django.contrib import admin
from django.urls import path


from collect import views


urlpatterns = [
    # path(路径,视图映射)
    path('admin/', admin.site.urls),
    # 1.版本使用url     2.x版本用path
    # django.urls.path()普通路径 and / or django.urls.re_path()带正则的路径
    path('index/',views.index)# 只要开始写映射关系浏览器就会报错

]

在这里插入图片描述

2.3 第二种路径定义方式(基于视图类)

在这里插入图片描述

2.4 第三种路径定义方式

在这里插入图片描述
2.2.4.1 分别在每一个自定义APP中定义urls.py文件

from django.urls import path,include

urlpatterns = [
  
]

2.4.2 在初始urls.py中,分别加上二级路由匹配文件

from django.contrib import admin
from django.urls import path,include

from collect import views
from users import views

urlpatterns = [
    # path(路径,视图映射)
    path('admin/', admin.site.urls),
    # 1.版本使用url     2.x版本用path
    # django.urls.path()普通路径 and / or django.urls.re_path()带正则的路径
    # path('index/',views.index)# 只要开始写映射关系浏览器就会报错
    path('collect/',include('collect.urls')),
    path('users/',include('users.urls'))

2.4.3 在二级urls.py 文件中进行真正的路由和视图映射关系

from django.urls import path, include

from collect.views import index
# 分别定义collect这个app相关的路径

urlpatterns = [

    path('index/',index)

]

3. 定义模板

3.1 第一步:在项目下创建模板文件夹,文件夹名字固定为templates

在这里插入图片描述

3.2 第二步:将模板文件进行注册

在settings.py文件中,进行配置

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],# 使用os进行路径拼接,注意不要粘贴绝对路径
        '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',
            ],
        },
    },
]

3.3 在视图中进行使用,注意返回的函数是render

render源码

def render(request, template_name, context=None, content_type=None, status=None, using=None):
    """
    Return a HttpResponse whose content is filled with the result of calling
    django.template.loader.render_to_string() with the passed arguments.
    """
    content = loader.render_to_string(template_name, context, request, using=using)
    return HttpResponse(content, content_type, status)
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

# 视图函数
def index(param):
    print('----->这是获取的参数')
    print(param)
    print('----->这是处理主页index的视图函数')
    # 视图函数必须有返回值,必须有参数
    # return HttpResponse('ok')
    return render(request=param,template_name='collect/index.html')

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

W-Y-Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值