1. 程式人生 > >(二) Django-Hello World

(二) Django-Hello World

Django

前言

當前環境: Ubuntu18 + Python3.6.5 + Django2.1.1

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/:

在這裡插入圖片描述