Python+Django(Python Web項目初體驗)

來源:互聯網
上載者:User

標籤:ams   hello   小結   cin   .net   session   100%   round   模組   

參考:79229784

Django是一個開放原始碼的Web應用程式框架,由Python寫成。

安裝Django:pip install  django 

Python和Django版本對應表

Django version Python versions
1.8 2.7, 3.2 (until the end of 2016), 3.3, 3.4, 3.5
1.9, 1.10 2.7, 3.4, 3.5
1.11 2.7, 3.4, 3.5, 3.6
2.0 3.5+

 

1、建立Django項目(myweb)

django-admin startproject myweb

2、啟動Django服務

python manage.py runserver

瀏覽器輸入: http://127.0.0.1:8000/ 就可以訪問了~

3、建立Django APP

什麼是Django APP,在Django中,app相當於一個功能模組, 與其他的web架構可能有很大的區別, 將不同功能放在不同的app中, 方便代碼的複用。

python manage.py startapp myapp

此時可以訪問:http://127.0.0.1:8000/admin

 

1)、在myapp目錄下建立一個templates檔案夾,並在該檔案夾中建立一個index.html檔案,用於展示的網頁內容。

index.html檔案內容如下:

<!DOCTYPE html>  <html lang="en">  <head>      <meta charset="UTF-8">      <title>Hello,Django!</title>  </head>  <body>      <h1>Hello,My First Django!</h1>   </body>  </html>  

2)、在myweb/myweb/settings.py下添加建立app,找到INSTALLED_APP,在其中添加’myapp,’, 然後儲存:

INSTALLED_APPS = [    ‘django.contrib.admin‘,    ‘django.contrib.auth‘,    ‘django.contrib.contenttypes‘,    ‘django.contrib.sessions‘,    ‘django.contrib.messages‘,    ‘django.contrib.staticfiles‘,    ‘myapp‘,  ]

3)、開啟myapp檔案夾下面的views.py檔案,在檔案中輸入:

from django.shortcuts import render# Create your views here.# 添加index函數,用於返回index.html頁面def index(request): return render(request, ‘index.html‘)  

4)、開啟myweb檔案夾下面的urls.py檔案,在檔案中輸入:

from django.contrib import adminfrom django.urls import pathfrom myapp import views # 匯入viewsurlpatterns = [    path(‘admin/‘, admin.site.urls),    path(‘‘, views.index), # 添加views.index]

5)、完成以上步驟,執行“python manage.py runserver”啟動Django中的伺服器,在瀏覽器中開啟127.0.0.1:8000

小結:

 Python Code 
1
2
3
4
5
  django-admin.py startproject myweb          #建立項目
python manage.py startapp myapp             #建立app
python manage.py runserver                  #啟動Django中的程式開發伺服器
python manage.py -h                         #協助文檔
python manage.py <command> [options]        #Django命令

Python+Django(Python Web項目初體驗)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.