(二) Django-Hello World

Django

前言

当前环境: Ubuntu18 + Python3.6.5 + Django2.1.1

Django官网

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source.

上一节我们创建了mysiteDjango项目以及scetc应用(用来处理业务逻辑), 并成功运行了这个Django Server.

这一节, 我们来让我们的Server输出Hello World.


Django-Hello World

Django-view.py

修改scetc应用中的views.py(视图文件):

"""
	./scetc/views.py
"""
from django.shortcuts import render
from django.http import HttpResponse	# 用于返回http response.


# request为请求信息即client发送的请求信息.
def index(request):
    return HttpResponse("Hello World!")

# Create your views here.

修改完成后, 还需要将其映射到mysite项目的urls.py.

Django-urls.py

view.py中的对象映射到urls.py:

"""mysite URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from scetc import views		# 修改处.

urlpatterns = [
    path('index/', views.index),		# 修改处.
    path('admin/', admin.site.urls),
]

然后我们使用python3 manage.py runserver "IP:PORT"来运行Server.

我们在Browser来访问http://IP:PORT来访问我们的Server.

发现报错了:

在这里插入图片描述

为什么呢?因为修改urls.py文件.

  • path('index/', views.index),: 表示访问http://IP:PORT/index/时调用views.index对象来处理请求.

    • 这也是为什么我们请求首页会报错的原因.
  • path('', views.index),: 表示访问首页http://IP:PORT时调用views.index对象来处理请求.

    • urls规定了访问路径时应调用哪个对象来处理请求.

我们来访问下http://IP:PORT/index/:

在这里插入图片描述


猜你喜欢

转载自blog.csdn.net/One_of_them/article/details/82828518