1. 程式人生 > >飲冰三年-人工智能-Python-22 Python初始Django

飲冰三年-人工智能-Python-22 Python初始Django

char value utf8 方法 templates index () enc rev

1:一個簡單的web框架

技術分享圖片
# 導包
from wsgiref.simple_server import make_server
#自定義個處理函數
def application(environ,start_response):
    start_response("200 OK",[(Content-Type,text/html)])
    return [b<h1>Hello,web!</h1>]

httpd = make_server(‘‘,8091,application)
print(Serving HTTP on port 8091....)
httpd.serve_forever()
HelloWorld

技術分享圖片

技術分享圖片
# 導包
from wsgiref.simple_server import make_server
#自定義個處理函數
def application(environ,start_response):
    # 獲取路徑
    path = environ["PATH_INFO"]
    start_response("200 OK",[(Content-Type,text/html)])
    if path=="/yang":
        return [b<h1>Hello,yang!</h1>]
    elif path=="
/Aaron": return [b<h1>Hello,aaron!</h1>] else: return [b<h1>404!</h1>] httpd = make_server(‘‘,8091,application) print(Serving HTTP on port 8091....) httpd.serve_forever()
View Code2.0

技術分享圖片

技術分享圖片
# 導包
from wsgiref.simple_server import make_server

def yang():
    f
=open("yang.html","rb") data=f.read() return data def aaron(): f=open("aaron.html","rb") data=f.read() return data #自定義個處理函數 def application(environ,start_response): # 獲取路徑 path = environ["PATH_INFO"] start_response("200 OK",[(Content-Type,text/html)]) if path=="/yang": return [yang()] elif path=="/Aaron": return [aaron()] else: return [b<h1>404!</h1>] httpd = make_server(‘‘,8091,application) print(Serving HTTP on port 8091....) httpd.serve_forever()
調用HTML內容

技術分享圖片

技術分享圖片
# 導包
import time
from wsgiref.simple_server import make_server

def region(req):
    pass;
def login(req):
    print(req["QUERY_STRING"])
    f=open("login.html",rb)
    data=f.read();
    return data;
def yang(req):
    f=open("yang.html","rb")
    data=f.read()
    return data
def aaron(req):
    f=open("aaron.html","rb")
    data=f.read()
    return data
def show_time(req):
   times=time.ctime()
   # 方法一:通過模板使用
   # con=("<h1>time:%s</h1>" %str(times)).encode("utf8")
   # return con
   # 方法二:字符串替換
   f = open("show_time.html", "rb")
   data = f.read()
   data=data.decode("utf8")
   data =data.replace("{{time}}",str(times))
   return data.encode("utf8")
# 定義路由
def router():
    url_patterns=[
        ("/login",login),
        ("/region", region),
        ("/yang", yang),
        ("/aaron", aaron),
        ("/show_time",show_time),
    ]

    return url_patterns
#自定義個處理函數
def application(environ,start_response):
    # 獲取路徑
    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 func:
        return [func(environ)]
    else:
        return [b404]
httpd = make_server(‘‘,8091,application)
print(Serving HTTP on port 8091....)
httpd.serve_forever()
模擬路由 技術分享圖片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
     <style>
        *{
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>
    <h1>時間:{{time}}}</h1>
</body>
</html>
show_time.html

技術分享圖片

2:一個簡單的django案例

  Django的下載與安裝

  技術分享圖片

技術分享圖片

  如何檢驗是否安裝成功?

  技術分享圖片

  2.1 創建django項目的兩種方法  

技術分享圖片
--創建Django項目
django-admin startproject mysite
 
--創建應用
python manage.py startapp blog
通過命令創建

技術分享圖片

技術分享圖片

方式2:通過Pycharm創建

技術分享圖片

創建成功

技術分享圖片

大致分為三步

a:修改urls.py 類似控制器,把想要展示的內容通過地址配置一下

技術分享圖片

b:在views中設置具體的邏輯

技術分享圖片

c:在templates中設置要顯示的頁面內容

技術分享圖片

通過命令行啟動django。

python manage.py runserver 8091

技術分享圖片

如何引用js

a:添加static文件,並把js放置到該文件下

技術分享圖片

b:在setting文件中配置

技術分享圖片

c:在對應的文件中做引用

技術分享圖片

技術分享圖片

URL配置(URLconf):又叫做路由系統,其本質是提供路徑和視圖函數之間的調用映射表。

格式:

  urlpatterns=[

    url(正在表達式,views視圖函數,參數,別名)

  ]

例1:匹配 XXX/articles/年份(只能匹配4位數字)

技術分享圖片
from django.contrib import admin
from django.urls import path
from django.conf.urls import  url
from blog import views
urlpatterns = [
    path(admin/, admin.site.urls),
    path(show_time/,views.show_time),
    url(r^articles/[0-9]{4}/$, views.year_archive),

]
urls.py--1.0 技術分享圖片
from django.shortcuts import render,HttpResponse
import time
def show_time(request):
    # return HttpResponse("Hello")
    return render(request,"index.html",{"time":time.ctime()})
# Create your views here.
def year_archive(request):
    return HttpResponse("2018");
Views.py

技術分享圖片

例2:如何獲取到地址欄中的年份(通過路由添加()匹配)

技術分享圖片

技術分享圖片

例3:給分組命名

urls中的配置

url(r‘^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})$‘, views.year_archive),

views視圖中的代碼

return HttpResponse(year+"-"+month)

技術分享圖片

例四:註冊小練習
技術分享圖片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="" method="post">
    <p>姓名 <input type="text" name="name"></p>
    <p>年齡 <input type="text" name="age"></p>
    <p>愛好 <input type="checkbox" name="hobby" value="1">讀書
            <input type="checkbox" name="hobby" value="2">寫字
            <input type="checkbox" name="hobby" value="3">看報
    </p>
    <p><input type="submit"></p>
</form>
</body>
</html>
Register.html 技術分享圖片
from django.shortcuts import render,HttpResponse
import time
def show_time(request):
    # return HttpResponse("Hello")
    return render(request,"index.html",{"time":time.ctime()})
# Create your views here.
def year_archive(request,month,year):
    return HttpResponse(year+"-"+month)

def Register(request):
    if request.method=="POST":
        con="Hello,%s,你的年齡是%s"%(request.POST.get("name"),request.POST.get("age"))
        return HttpResponse(con)
    return render(request,"Register.html")
Views.py 技術分享圖片
"""django01 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 django.conf.urls import  url
from blog import views
urlpatterns = [
    path(admin/, admin.site.urls),
    path(show_time/,views.show_time),
    url(r^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})$, views.year_archive),
    url(r^Register/, views.Register),

]
urls.py

註意:需要把這句代碼給註釋掉

技術分享圖片

效果圖

技術分享圖片技術分享圖片

在url中給地址設置一個別名,這樣後期Register名稱的修改將不影響系統中其他調用的功能

技術分享圖片

技術分享圖片

URL分發

技術分享圖片

技術分享圖片

效果:

技術分享圖片

飲冰三年-人工智能-Python-22 Python初始Django