1. 程式人生 > >django-1.開始hello world!

django-1.開始hello world!

() hello gop off world sym 程序配置 需要 content

前言

當你想走上測試開發之路,用python開發出一個web頁面的時候,需要找一個支持python語言的web框架。django框架有豐富的文檔和學習資料,也是非常成熟的web開發框架,想學python開發的小夥伴,從django入手是一個不錯的選擇。本篇寫一個簡單的“hello world! ”頁面,開始django之旅~
環境準備:
Python 3.6.0
django 2.1.2
pycharm

環境準備

django的環境安裝非常簡單,只需用pip安裝一個django庫就可以了,編輯器選擇pycharm

pip install django

查看版本號:pip show django

C:\Users\dell>pip show django
Name: Django
Version: 2.1.2
Summary: A high-level Python Web framework that encourages rapid development and clean, pragmatic design.
Home-page: https://www.djangoproject.com/
Author: Django Software Foundation
Author-email: foundation@djangoproject.com
License: BSD
Location: e:\python36\lib\site-packages
Requires: pytz
Required-by:

安裝完之後在cmd檢查下是否能用

C:\Users\dell>python
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> print(django.get_version())
2.1.2
>>>

創建項目

先建一個工程,比如我的項目代碼想放到E:\web_djo目錄下,然後新建一個Django project( 即一個 Django 項目實例需要的設置項集合,包括數據庫配置、Django 配置和應用程序配置。)
打開命令行,cd 到一個你想放置你代碼的目錄,然後運行以下命令:

django-admin startproject helloworld

執行完之後打開pycharm就可以看到web_djo工程目錄下多了以下層級文件

helloworld
    │  manage.py
    │  
    └─helloworld
            settings.py
            urls.py
            wsgi.py
            __init__.py

技術分享圖片

這些目錄和文件的用處是:

  • 最外層的:helloworld: 項目的容器,可以隨便命名。
  • manage.py: 一個讓你用各種方式管理 Django 項目的命令行工具。
  • helloworld/__init__.py:一個空文件,告訴 Python 這個目錄應該被認為是一個 Python 包。
  • helloworld/settings.py:Django 項目的配置文件。
  • helloworld/urls.py:Django 項目的 URL 聲明,就像你網站的“目錄”。
  • helloworld/wsgi.py:作為你的項目的運行在 WSGI 兼容的Web服務器上的入口。

django-admin

django-admin.exe是一個可執行文件,安裝django時候會默認安裝到python3\Scripts目錄下,相關指令用-h查看

E:\python36\Scripts>django-admin -h

Type ‘django-admin help <subcommand>‘ for help on a specific subcommand.

Available subcommands:

[django]
    check
    compilemessages
    createcachetable
    dbshell
    diffsettings
    dumpdata
    flush
    inspectdb
    loaddata
    makemessages
    makemigrations
    migrate
    runserver
    sendtestemail
    shell
    showmigrations
    sqlflush
    sqlmigrate
    sqlsequencereset
    squashmigrations
    startapp
    startproject
    test
    testserver
Note that only Django core commands are listed as settings are not properly configured (error: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.).

啟動服務

接下來啟動django服務,使用helloworld下的manage.py,先cd到web_djo/helloworld目錄下,到在命令行輸入以下指令:

python manage.py runserver

E:\web_djo\helloworld>python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).

You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run ‘python manage.py migrate‘ to apply them.
October 23, 2018 - 21:09:39
Django version 2.1.2, using settings ‘helloworld.settings‘
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

啟動完只看看到這句:Starting development server at http://127.0.0.1:8000/,復制地址在瀏覽器打開

技術分享圖片

django服務默認在8000端口啟動,如果想換個端口,可以輸入以下指令

python manage.py runserver 8080

如果一個局域網另外一臺電腦也需要能訪問,可以監聽所有ip:python manage.py runserver 0.0.0.0:8000,訪問的時候用電腦ip代替127.0.0.1

用於開發的服務器在需要的情況下會對每一次的訪問請求重新載入一遍 Python 代碼。所以你不需要為了讓修改的代碼生效而頻繁的重新啟動服務器。然而,一些動作,比如添加新文件,將不會觸發自動重新加載,這時你得自己手動重啟服務器。

視圖和URL配置

在先前創建的helloworld/helloworld目錄新建一個 view.py 文件,並輸入代碼

# helloworld/helloworld/view.py
from django.http import HttpResponse
 
def index(request):
    return HttpResponse("Hello world !  django ~~")

綁定URL與視圖函數。打開 urls.py 文件,刪除原來代碼,將以下代碼復制粘貼到 urls.py 文件中

# helloworld/helloworld/urls.py
from django.conf.urls import url
from . import view

urlpatterns = [
    url(r‘^$‘, view.index),
]

技術分享圖片

url函數

url() 可以接收四個參數,分別是兩個必選參數:regex、view 和兩個可選參數:kwargs、name.

def url(regex, view, kwargs=None, name=None):
    return re_path(regex, view, kwargs, name)
  • regex: 正則表達式,與之匹配的 URL 會執行對應的第二個參數 view。

  • view: 用於執行與正則表達式匹配的 URL 請求。

  • kwargs: 視圖使用的字典類型的參數。

  • name: 用來反向獲取 URL。

多個url設置

urlpatterns裏面url(r‘^$‘, view.index)這項是打開首頁http://127.0.0.1:8000,平常網站會有多個頁面,如果想加個頁面地址如:http://127.0.0.1:8000/yoyo打開另外一個頁面.

view.py加個函數

from django.http import HttpResponse
 
def index(request):
    return HttpResponse("Hello world ! django ~~ ")


def yoyo(request):
    return HttpResponse("yoyo!  django ~~ ")

urls.py加個配置

from django.conf.urls import url
from . import view

urlpatterns = [
    url(‘^$‘, view.index),
    url(‘^yoyo$‘, view.yoyo),
]

這樣在瀏覽器上輸入地址:http://127.0.0.1:8000/,打開頁面出現:Hello world ! django ~~
在瀏覽器輸入地址:http://127.0.0.1:8000/yoyo, 打開頁面出現:yoyo! django ~~

關於regex正則表達式用法可以參考菜鳥教程http://www.runoob.com/regexp/regexp-tutorial.html

django-1.開始hello world!