Django是Python中Web開發的最有代表性的架構之一。本文将簡單介紹如何入門Django開發。
首先確定你的linux系統已安裝django子產品。打開Python3,利用以下指令可找到django所在目錄:
>>> import django
>>> print(django.__path__)
筆者顯示的是:
['/usr/lib/python3/dist-packages/django']
接下來開始django開發!首先切換到django目錄,建立poem項目:
django-admin.py startproject poem
輸入tree poem,檢視poem項目的樹結構:
在urls.py的urlpatterns清單中添加:
url(r'^$', 'poem.views.output'),
在/poem/poem檔案夾下,建立views.py檔案,輸入代碼:
from django.http import HttpResponse
def output(request):
title = "<h1>When You Are Old</h1>"
author = "<h2>William Butler Yeats</h2>"
content = """
When you are old and grey and full of sleep,<br/>
And nodding by the fire, take down this book,<br/>
And slowly read, and dream of the soft look<br/>
Your eyes had once, and of their shadows deep;<br/>
How many loved your moments of glad grace,<br/>
And loved your beauty with love false or true,<br/>
But one man loved the pilgrim soul in you,<br/>
And loved the sorrows of your changing face;<br/>
And bending down beside the glowing bars,<br/>
Murmur, a little sadly, how love fled<br/>
And paced upon the mountains overhead<br/>
And hid his face amid a crowd of stars.<br/>
"""
return HttpResponse([title, author, content])
進入poem檔案夾,輸入指令:
python3 manage.py runserver 8000
打開浏覽器,輸入localhost:8000,頁面如下圖:
這樣我們就完成了一個簡單的django項目的開發。期待下期分享~~
本次分享到此結束,歡迎大家批評與交流~~