django基礎(一)

wanghui發表於2018-11-07

django基礎-(一)

專案的建立和啟動

(venv3) [vagrant@localhost ~]$ cd /vagrant/
(venv3) [vagrant@localhost vagrant]$ django-admin startproject devops
(venv3) [vagrant@localhost vagrant]$ tree devops/
devops/      #專案容器
├── devops     #是實際的python專案包
│ ├── __init__.py
│ ├── settings.py   #配置檔案
│ ├── urls.py     #路由檔案
│ └── wsgi.py
└── manage.py     #實用的命令列工具
(venv3) [vagrant@localhost vagrant]$ vim devops/devops/settings.py    #資料庫配置檔案更改
DATABASES = {
   `default`: {
       `ENGINE`: `django.db.backends.mysql`,
       `NAME`: `devops`,
       `USER`: `root`,
       `PASSWORD`: `123456`,
       `HOST`: `localhost`,
       `PORT`: 3306,
          `OPTIONS`:{
           `init_command`: `SET default_storage_engine=INNODB;`,
           },
    }
}
  • 服務啟動
(venv3) [vagrant@localhost devops]$ python manage.py runserver 0:8000
  • 新建專案
(venv3) [vagrant@localhost devops]$ python manage.py startapp dashboard     #方法一
(venv3) [vagrant@localhost devops]$ django-admin startapp dashboard1           #方法二

startproject和startapp的區別

一個專案下有多個app(一對多的關係)
  • 配置url
(venv3) [vagrant@localhost devops]$ vim dashboard/urls.py
from django.conf.urls import url
urlpatterns = [
]
  • 註冊app
(venv3) [vagrant@localhost devops]$ vim devops/settings.py
INSTALLED_APPS = [
    `django.contrib.admin`,
    `django.contrib.auth`,
    `django.contrib.contenttypes`,
    `django.contrib.sessions`,
    `django.contrib.messages`,
    `django.contrib.staticfiles`,
    `dashboard`
]

hello world

  • 檢視函式
(venv3) [vagrant@localhost devops]$ vim dashboard/views.py
from django.shortcuts import render
from django.http import HttpResponse
#檢視函式
def index(request):
    return HttpResponse("hello world")
  • 配置app url
(venv3) [vagrant@localhost devops]$ vim dashboard/urls.py
from django.conf.urls import url
from .views import index
urlpatterns = [
    url(r`^$`,index,name=`index`)
]
  • 配置project url
(venv3) [vagrant@localhost devops]$ vim devops/urls.py
from django.conf.urls import url,include
from django.contrib import admin
urlpatterns = [
    url(r`^admin/`, admin.site.urls),
    url(r`^dashboard/`,include("dashboard.urls"))
]
  • 啟動專案
(venv3) [vagrant@localhost devops]$ python3 manage.py runserver 0:8000

HttpRequest物件

  • 是在django.http這個模組中
  • 是有django建立
  • 官方文件docs

常用的屬性:

request.body —–b“
request.scheme —–http
request.path —- /dashboard/
request.method — GET
request.GET
request.POST
request.META

HttpResponse物件

  • HttpResponse:返回字串
  • JsonResponse:返回字典,注意safe=False是針對於列表型別

GET與POST請求

- GET
request.GET
request.GET.get(`xx`)
request.GET.getlist(`oo`)
- POST
request.GET
request.GET.get(`xx`)
request.GET.getlist(`oo`)

Querydict

In [1]: from django.http import QueryDict                                                                  
In [2]: QueryDict(`aa=bb&cc=dd&cc=xxx`)                                                                    
Out[2]: <QueryDict: {`aa`: [`bb`], `cc`: [`dd`, `xxx`]}>
In [3]: q = QueryDict(`aa=bb&cc=dd&cc=xxx`)                                                         
In [4]: QueryDict.fromkeys([`a`,`b`,`a`],value=`val`)                                                      
Out[4]: <QueryDict: {`a`: [`val`, `val`], `b`: [`val`]}>
In [5]: q                                                                                                  
Out[5]: <QueryDict: {`aa`: [`bb`], `cc`: [`dd`, `xxx`]}>
In [6]: q.dict()                                                                                           
Out[6]: {`aa`: `bb`, `cc`: `xxx`}
In [7]: q.urlencode()                                                                                      
Out[7]: `aa=bb&cc=dd&cc=xxx`

DELETE&PUT請求

請求返回都在request.body中

  • 檢視函式
def index_2(request):
    if request.method == "GET":
        print("request get =",request.GET)
        data = request.GET.copy()
        data[`aa`] = `xxxxxx`
        print("data =",data)
        print("aa =",request.GET.get("aa"))       #取出單個值
        print("cc =",request.GET.getlist("cc"))   #取出多個值
    elif request.method == "POST":
        print("request post =",request.POST)
        print("aa =",request.POST.get("aa"))
        print("cc =",request.POST.getlist("cc"))

    elif request.method == "DELETE":
        print("delete=",QueryDict(request.body))

    elif request.method == "PUT":
        print("put=",QueryDict(request.body))

    return HttpResponse("")
  • 請求方式:
In [1]: import requests                                                                             
In [2]: url = "http://127.0.0.1:8000/dashboard/"    
In [3]: data = {}                                                                                         
In [4]: data[`aa`] = `bb`                                                                              
In [5]: data[`cc`] = [`dd`,`ee`]      
In [9]: requests.delete(url,data=data)                                                     Out[9]: <Response [200]>
In [10]: requests.put(url,data=data)                                                         Out[10]: <Response [200]>
使用者登入練習
  • 檢視函式
def login(request):
    msg = ""
    if request.method == "POST":
        username = request.POST.get("username")
        userpass = request.POST.get("userpass")
        if username == "admin" and userpass == "123456":
            msg = "login success"
        else:
             msg = "login failed"
    else:
         msg = "請求方法不被允許!"
     returnHttpResponse(msg) 
  • post請求方法
In [11]: url = "http://192.168.33.10/login/"                                       
In [12]: data = {}                                                                                       
In [13]: data[`username`] = "admin"                                                         
In [14]: data[`userpass`] = "123456"   
In [16]: r = requests.post(url,data)  
In [18]: r.content.decode(`utf8`)  

使用者建立

(venv3) [vagrant@localhost devops]$ python3 manage.py shell
(venv3) [vagrant@localhost devops]$ python3 manage.py dbshell
(venv3) [vagrant@localhost devops]$ python3 manage.py showmigrations
(venv3) [vagrant@localhost devops]$ python3 manage.py makemigrations
(venv3) [vagrant@localhost devops]$ python3 manage.py migrate
-----------------------------------建立使用者--------------------------------------
(venv3) [vagrant@localhost devops]$ python3 manage.py shell
In [1]: from django.contrib.auth.models import User                                                        
In [2]: User.objects.create_user("wanghui","wanghui@qq.com",`123456`)      #建立普通使用者
In [3]: User.objects.create_superuser("admin","admin@qq.com",`123456`)                  #建立超級管理員

———修改密碼——————————————————-

In [5]: u = User.objects.get(username="wanghui")                                                           
In [6]: u.set_password(`654321`)                                                                           
In [7]: u.save()       

———刪除使用者—————————-

使用者登入

步驟:
一個檢視

GET請求:展示登陸頁面
POST請求:執行使用者登陸
                   1. 接收使用者post過來的使用者名稱密碼
                    2. 驗證使用者名稱密碼
                    3. 返回結果
  • 檢視函式
from django.contrib.auth.models import User
from django.contrib.auth import login,authenticate
def LoginView(request):
    if request.method == `POST`:
        username = request.POST.get(`username`)
        userpass = request.POST.get(`userpass`)
        # try:
        # User.objects.get(username=username)
        # except User.DoesNotExist:
        # return HttpResponse("使用者不存在!")
        user = authenticate(request,username=username,password=userpass)
        if user is not None:
            login(request,user)
            return HttpResponse("使用者登入成功")
        else:
            return HttpResponse("使用者登入失敗")
    return render(request, `login.html`)
  • 模板檔案
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>使用者登入</title>
</head>
<body>
<div>
    <form method="POST">
        <li>
            <span>username</span>
            <input type="text" name="username" id="">
        </li>
        <li>
            <span>password</span>
            <input type="password" name="userpass">
        </li>
        <li>
            <input type="submit">
        </li>
    </form>
</div>
</body>
</html>
  • 路由
from django.conf.urls import url
from . import views
urlpatterns = [
    url(r`^$`,views.index,name="index"),
    url(r`^index2/$`,views.index_1,name="index_1"),
    url(r`^login/$`,views.loginv1,name="login"),
    url(r`^loginv2/$`,views.LoginView,name="loginv2"),
]

相關文章