• Django学习笔记第五篇--实战练习一--查询数据库并操作cookie


    一、启动项目:

    1 django-admin start mysite1
    2 cd mysite1
    3 python manage.py startapp loginapp

    根据上文敲命令就可以创建好了一个项目结构,之后就是修改配置文件,这里使用的数据库是MySQL的。

    二、修改配置文件:

    settings.py

      1 """
      2 Django settings for mysite1 project.
      3 
      4 Generated by 'django-admin startproject' using Django 1.8.
      5 
      6 For more information on this file, see
      7 https://docs.djangoproject.com/en/1.8/topics/settings/
      8 
      9 For the full list of settings and their values, see
     10 https://docs.djangoproject.com/en/1.8/ref/settings/
     11 """
     12 
     13 # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
     14 import os
     15 
     16 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
     17 
     18 
     19 # Quick-start development settings - unsuitable for production
     20 # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
     21 
     22 # SECURITY WARNING: keep the secret key used in production secret!
     23 SECRET_KEY = 'u-=+xrj*5cr+z92==pmlct&c2ta+7o8ia8_y!(ne^*538_afr1'
     24 
     25 # SECURITY WARNING: don't run with debug turned on in production!
     26 DEBUG = True
     27 
     28 ALLOWED_HOSTS = []
     29 
     30 
     31 # Application definition
     32 
     33 INSTALLED_APPS = (
     34     'django.contrib.admin',
     35     'django.contrib.auth',
     36     'django.contrib.contenttypes',
     37     'django.contrib.sessions',
     38     'django.contrib.messages',
     39     'django.contrib.staticfiles',
     40     'loginapp'
     41 )
     42 
     43 MIDDLEWARE_CLASSES = (
     44     'django.contrib.sessions.middleware.SessionMiddleware',
     45     'django.middleware.common.CommonMiddleware',
     46     'django.middleware.csrf.CsrfViewMiddleware',
     47     'django.contrib.auth.middleware.AuthenticationMiddleware',
     48     'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
     49     'django.contrib.messages.middleware.MessageMiddleware',
     50     'django.middleware.clickjacking.XFrameOptionsMiddleware',
     51     'django.middleware.security.SecurityMiddleware',
     52 )
     53 
     54 ROOT_URLCONF = 'mysite1.urls'
     55 
     56 TEMPLATES = [
     57     {
     58         'BACKEND': 'django.template.backends.django.DjangoTemplates',
     59         'DIRS': [],
     60         'APP_DIRS': True,
     61         'OPTIONS': {
     62             'context_processors': [
     63                 'django.template.context_processors.debug',
     64                 'django.template.context_processors.request',
     65                 'django.contrib.auth.context_processors.auth',
     66                 'django.contrib.messages.context_processors.messages',
     67             ],
     68         },
     69     },
     70 ]
     71 
     72 WSGI_APPLICATION = 'mysite1.wsgi.application'
     73 
     74 
     75 # Database
     76 # https://docs.djangoproject.com/en/1.8/ref/settings/#databases
     77 
     78 DATABASES = {
     79     'default': {
     80         'ENGINE': 'django.db.backends.mysql',
     81         'NAME': 'mysite1',
     82         'USER': 'root',
     83         'HOST': '127.0.0.1',
     84         'PORT': '3306',
     85     }
     86 }
     87 
     88 
     89 # Internationalization
     90 # https://docs.djangoproject.com/en/1.8/topics/i18n/
     91 
     92 LANGUAGE_CODE = 'en-us'
     93 
     94 TIME_ZONE = 'UTC'
     95 
     96 USE_I18N = True
     97 
     98 USE_L10N = True
     99 
    100 USE_TZ = True
    101 
    102 
    103 # Static files (CSS, JavaScript, Images)
    104 # https://docs.djangoproject.com/en/1.8/howto/static-files/
    105 
    106 STATIC_URL = '/static/'

    三、创建数据库:

    1 mysql -h 127.0.0.1 -u root
    2 create database mysite1
    3 exit

    然后编辑models.py文件:

    1 from django.db import models
    2 
    3 # Create your models here.
    4 class account(models.Model):
    5     username = models.CharField(max_length=20)
    6     password = models.CharField(max_length=256)

    然后选择创建数据库表结构

    1 $ python manage.py migrate   # 创建表结构
    2 $ python manage.py makemigrations loginapp  # 让 Django 知道我们的模型有一些变更
    3 $ python manage.py migrate loginapp   # 创建表结构

    四、编写urls.py文件:

     1 from django.conf.urls import include, url
     2 from django.contrib import admin
     3 from loginapp import views
     4 
     5 urlpatterns = [
     6     # Examples:
     7     # url(r'^$', 'mysite1.views.home', name='home'),
     8     # url(r'^blog/', include('blog.urls')),
     9 
    10     url(r'^admin/', include(admin.site.urls)),
    11     url(r'^login/', 'loginapp.views.login'),
    12     url(r'^main/', 'loginapp.views.main'),
    13     url(r'^logout/', 'loginapp.views.logout'),
    14 ]

    五、最重要的视图函数到了:

    views.py

     1 # -*- coding:utf-8 -*-
     2 import hashlib
     3 from django.shortcuts import render
     4 from django.http import HttpResponse
     5 from models import account
     6 # Create your views here.
     7 def get_md5(text):
     8     md5 = hashlib.md5()
     9     d5.update(text)
    10     return md5.hexdigest()
    11 
    12 def login(request):
    13     user = request.GET["user"]
    14     pswd = request.GET["pswd"]
    15     #pswd = get_md5(pswd)
    16     result = account.objects.get(username=user)
    17     try:
    18         if pswd == result.password:
    19             response = HttpResponse("Welcome %s, Login Success!"%user)
    20             response.set_cookie("login_name",user)
    21             response.set_cookie("login_code",1)
    22             return response
    23         else:
    24             return HttpResponse("Sorry,Login Failed!")
    25     except Excception,ex:
    26         return HttpResponse("Sorry,Login Failed!")
    27             
    28 
    29 def main(request):
    30     if "login_code" in request.COOKIES:
    31         logincode = request.COOKIES["login_code"]
    32         print logincode
    33         print type(logincode)
    34         if logincode == "1":
    35             return HttpResponse("Yes , sir!")
    36         else:
    37             return HttpResponse("Sorry , sir!")
    38 
    39 def logout(request):
    40     user = request.GET["user"]
    41     if "login_name" in request.COOKIES:
    42         if user == request.COOKIES["login_name"]:
    43             response = HttpResponse("ByeBye!")
    44             response.set_cookie("login_code",0)
    45             return response
    46         else:
    47             return HttpResponse("Sorry User Error!")
    48     else:
    49         return HttpResponse("Sorry User Error!")

    六、总结:

    1、数据库的对象应该是from modles.py import classname 这里就是数据库对象了,然后就是classname.objects.get或者其他操作;

    2、get方法获取的是符合条件的数据的一项,是一个数据实例,其属性使用ret.name方式调用;

    3、读写cookie,cookie在request.COOKIES中,字典结构,写的事后麻烦一些,需要response = HttpResponse等一类返回响应对象的函数的返回值。然后使用response.ser_cookie(key,value)方式设置,最后return response返回;

     1 from models import account
     2 #create a new user
     3 account.objects.create(username=user,password=pswd)
     4 ##or
     5 object = account(username=user,password=pswd)
     6 object.save()
     7 
     8 #delete a user
     9 account.objects.filter(username=user).delete()
    10 
    11 #update a user
    12 account.objects.filter(username=user).update(password=pswd)
    13 ##or
    14 object = account.objects.get(username=user)
    15 object.password = pswd
    16 object.save()
    17 
    18 #query for a user
    19 account.objects.get(username=user,password=pswd)
    20 ##or
    21 account.objects.all()
    22 ##or
    23 account.objects.all().values(username)
    24 account.objects.all().values_list(username,password)
  • 相关阅读:
    linuxc查看进程命令
    Springboot+post请求接口
    Springboot+get请求接口
    xml 加载多个properties文件
    TCP的三次握手(建立连接)和四次挥手(关闭连接)
    记一次 synchronized 锁字符串引发的坑兼再谈 Java 字符串
    java单点登录原理与简单实现
    关于 Java 面试,你应该准备这些知识点
    Java 内存模型
    java利用SuffixFileFilter统计目录下特定后缀名文件的数目
  • 原文地址:https://www.cnblogs.com/KevinGeorge/p/8364575.html
Copyright © 2020-2023  润新知