django基础(一)

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"),
]
    原文作者:wanghui
    原文地址: https://segmentfault.com/a/1190000016932707
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞