191016Django基礎

1、簡單的webserver框架

from wsgiref.simple_server import make_server
def login(req):  #view函數
    print(req["QUERY_STRING"])
    return b"welcome!"
def signup(req):
    pass
def dongfei(req):
    return b"<h1>Hello Dongfei</h1>"
def router():  #路由函數
    url_patterns=[
        ("/login", login),
        ("/signup", signup),
        ("/dongfei", dongfei)
    ]
    return url_patterns

def application(environ, start_response):
    print("path",environ["PATH_INFO"])
    path=environ["PATH_INFO"]
    start_response('200 OK', [('Content-Type', 'text/html')])  # 設置請求頭
    url_patterns = router()
    func = None
    for item in url_patterns:
        if item[0] == path:
            func = item[1]
            break
    if not func:
        return [b'404']
    return [func(environ)]
    # return [b'<h1>Hello World!</h1>']  #響應請求體

httpd = make_server('', 8080, application)
print('Serving HTTP on port 8080...')
httpd.serve_forever()

2、MVC和MTV模型

一、MVC模型

  • M:模型,負責業務對象與數據庫的對象(ORM)
  • C:控制器,接受用戶的輸入調用模型和視圖完成用戶請求
  • V:視圖,指展現的HTML文件

二、MTV模型

  • M:模型,負責業務對象與數據庫的對象(ORM)
  • T:模板,HTML模板文件css

  • V:視圖函數,view,和MVC模型中的C功能相似html

3、Django環境準備

>pip install django
>django-admin startproject mysite01  #建立Django項目
>cd mysite01
mysite01>python manage.py startapp blog  #建立app
-─mysite01
    │  manage.py
    │
    ├─blog
    │  │  admin.py
    │  │  apps.py
    │  │  models.py
    │  │  tests.py
    │  │  views.py  #視圖
    │  │  __init__.py
    │  │
    │  └─migrations
    │          __init__.py
    │
    └─mysite01
        │  settings.py  #與Django相關的全部的配置信息
        │  urls.py  #負責路由分發
        │  wsgi.py
        │  __init__.py
        │
        └─__pycache__
                settings.cpython-36.pyc
                __init__.cpython-36.pyc

4、簡單Django項目

  • urls.py
from django.contrib import admin
from django.urls import path
from blog import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('show_time', views.show_time)  #路由信息
]
  • blog/views.py
from django.shortcuts import render,HttpResponse
import time
def show_time(request):
    now_time = time.ctime()
    return render(request, "index.html", locals())
  • templates/index.html
<body>
    <h1>Time: {{ now_time }}</h1>
</body>

5、css/js等靜態文件的引入

一、第一種引入方式

  • setting.py
STATIC_URL = '/static/'  #別名
STATICFILES_DIRS=(
    os.path.join(BASE_DIR,"static"),
)
  • templates/index.html
<body>
    <h1>Time: {{ now_time }}</h1>
    <script src="/static/jquery-3.4.1.js"></script>
    <script>
        $("h1").css("color","red")
    </script>
</body>
  • 建立一個static文件夾,將jquery文件放在此文件夾下

二、第二種引入方式

  • templates/index.html
<head>
    <meta charset="UTF-8">
    {% load staticfiles %}  #在此load
    <title>Title</title>
</head>
<body>
    <h1>Time: {{ now_time }}</h1>
    <script src="{% static 'jquery-3.4.1.js' %}"></script>  #指定文件
    <script>
        $("h1").css("color","red")
    </script>
</body>

### 6、Url路由配置系統python

  • 無命名分組
path('article/<int:year>/<int:month>',views.article_year),
  • 命名分組
path('hello/<str:name>/', views.printname),
  • 別名
path('register', views.register, name="alias_reg")  #定義別名
<form action="{% url 'alias_reg' %}"></form>  #引用別名
  • 路由分發
from django.urls import path,include
urlpatterns = [
    path('blog/', include('blog.urls'))
]
from django.contrib import admin
from django.urls import path
from blog import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('show_time', views.show_time),
    path('article/<int:year>/<int:month>/<str:name>',views.article_year),
    path('hello/<str:name>/', views.printname),
    path('register', views.register, name="alias_reg")
]

7、View函數

一、request對象

def show_time(request):
    print(request.path)  #/blog/show_time
    print(request.get_full_path())  #/blog/show_time?name=dongfei
    now_time = time.ctime()
    return render(request, "index.html", locals())

二、HttpResponse對象

from django.shortcuts import render,HttpResponse,render_to_response
import time
def show_time(request):
    print(request.path)  #/blog/show_time
    print(request.get_full_path())  #/blog/show_time?name=dongfei
    now_time = time.ctime()
    # return render(request, "index.html", locals())  #推薦使用render,locals()將局部變量傳給templates
    return render_to_response("index.html", locals())

三、redirect對象

from django.shortcuts import render,HttpResponse,render_to_response,redirect
import time
def show_time(request):
    return redirect("http://time.tianqi.com/")  #跳轉
相關文章
相關標籤/搜索