Django初识

WEB架构简介

架构分类:
  • CS 架构 [Client/Server]
  • BS 架构 [Browser/Server]
在BS架构下,客户端只需要浏览器,应用程序的逻辑和数据都存储在服务器端,浏览器只需要请求服务器,获取WEB页面,并把WEB页面展示给用户即可。大部分软件都是WEB形式提供的,比如新浪新闻,博客,微博等废物,均是WEB应用。
 
WEB应用开发经历的几个阶段:
  1. 静态WEB页面:由文本编辑器直接编辑并生成静态的HTML页面,如果要修改WEB页面的内容,就需要再次编辑HTML源文件。最早期的WEB就是静态的。
  2. CGI : 由于静态WEB页面无法与用户交,比如用户填写一个注册表单,静态WEB页面就无法处理。要处理用户发送的动态数据,出现了Common Gateway Interface,简称CGI,用C/C++编写。
  3. ASP/JSP/PHP:由于WEB应用特点是修改频繁,用C/C++这样低级语言非常不适合WEB开发,而脚本语言由于开发效率高,与HTML结合紧密,因此,迅速取代了CGI模式。APS是微软退出的用VBScript脚本编程的WEB开发技术,而JSP用Java来编写脚本,PHP本身则是开源的脚本语言。
  4. MVC : 为了解决直接用脚本语言嵌入HTML导致的可维护性差的问题,WEB应用也引入了 Moder-View-Controller 的模式,来简化WEB开发。ASP 发展为ASP.Net, JSP和PHP也有一大堆MVC框架。

进入Django世界

一.环境搭建

(1)安装Django

pip install django

(2)配置系统环境变量

成功安装Django后,在Python的安装目录的Scripts目录中会生成一个 django-admin.exe 文件,将它加入系统环境变量中,方便之后使用。

 

二.创建django项目

diango-admin startproject mysite
  • 在项目mysite 中会生成同名目录mysite
  • setttings.py   主配置文件
  • urls.py           url 路由文件
  • wsgi.py          网络通信接口
  • templates      html 文件们的存放目录
  • manage.py    django管理主程序,程序启动文件

三.创建APP

   在每个django 项目中可以包含多个APP,相当于大型项目中的分系统,子模块,功能部件等等,相互之间比较独立。所有的APP共享项目资源。

cd  mysite
# 创建一个叫做cmdb的app
python manage.py startapp cmdb

 cmdb目录结构说明:

  • migrations
  • admin.py        # 
  • apps.py          # 当前app的配置文件
  • models.py      # 和数据库相关
  • tests.py          # 单元测试文件
  • views.py         # 处理用户请求 

四.编写代码

  编写顺序为:先创建url,在编写views中对应的处理函数

# urls.py
# 路由系统
from django.conf.urls import url
from django.contrib import admin
from cmdb import views  # 导入对应app的views文件

urlpatterns = [
    # url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index),  # 编写自定义路由,重点是引号中的正则表达式和后面的业务逻辑函数
]
# cmdb.views.py
# 处理用户请求
from django.shortcuts import render        # 这个示例中未用到
from django.shortcuts import HttpResponse  # 导入HttpResponse模块

def index(request):  # request 参数必须有,它封装了用户请求的所有内容
    return HttpResponse('hello world')  # 在函数中不能直接返回字符串,需要由HttpResponse来封装返回,这是django的规则

  通过上面连个文件配置,我们就见index 这个url 指向了views里的index()函数,它会接收用户请求,并返回一个字符串。

五. 启动Django程序

# 本机启动程序,端口为8000
python manage.py runserver 127.0.0.1:8000

在WEB端访问结果:

 

 注意:如果直接访问127.0.0.1:8000会报错,因为我们在urls.py 中只配置了一个index页面,所以访问除了index页面外的其他页面都会报错。

六. 返回HTML文件

  上一步我们返回的是一个简单的字符串,实际中需求是要返回Html页面给用户。

创建一个index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1 style="color:red">hello world</h1>
</body>
</html>

  修改cmdb中的views.py

from django.shortcuts import render   
from django.shortcuts import HttpResponse
# 处理用户请求,导入了一个 render方法来返回html文件

def index(request):
    # return HttpResponse('hello world')
    # 不返回字符串,返回一个Html文件,需要使用render方法
    # render(request, "xxx.html") 表示给用户返回一个叫做xxx.html的页面
    return render(request, 'index.html')

  接下来我们再次访问WEB

 

七. 使用静态文件

  之前实现了给用户返回一个html而不是简单的字符串,这次,我们要给html加些插件了,例如css, js等。让html 更加美观的展示在用户面前。
在django中存放静态文件的目录一般为 statics ,需要在mysite项目中创建一个目录 statics, 将css,js等放入其中。然后需要在settings中进行设置。


# settings.py文件底端 STATIC_URL = '/static/' # static 类似于一个引用指针,不是具体的目标,可以改成其他任何你喜欢的名字,但是在html文件中,必须和它相对应 STATICFLIES_DIRS = ( os.path.join(BASE_DIR, 'statics'), ) # 新建一个元组,STATICFLIES_DIRS 全局变量,元组的内容是存放静态文件目录的绝对路径,路径是拼接出来的,这里的statics是我们之前手动创建的目录

  

# templates.index.html
# 在html文件中导入js文件,路径如下:
<body>
    <h1 style="color:red">hello world</h1>
    <script src="/static/jquery-1.8.2.min.js"></script>
</body>

  

八. 接受用户发送的数据

 示例:用户输入用户名和密码,提交给index这个url,服务器将接受这些数据。

# 修改 templates.index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <h1>用户输入:</h1>
    <form action="/index/" method="POST">
        <input type="text" name="user" />
        <input type="password" name="passwd" />
        <input type="submit" value="提交" />
    </form>
</body>
</html>
# 在修改views.py
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.shortcuts import redirect
from cmdb import models
def index(request):
    if(request.method == 'POST'):
        u = request.POST.get('user',None)
        p = request.POST.get('passwd',None)
        print(u,p)
    return render(request, 'index.html')

 WEB页面效果:

 

输入数据后,在django后台就可以获取用户输入的数据了。
 

九.返回动态页面

     我们接收到用户的数据,但是返回的依然是一个静态页面,我们应该通过处理用户数据,相应返回一个页面,从而达到动态页面效果。Django采用jinja2语言编写动态模板,jinja2会根据提供的数据,替换掉html中的相应部分。
# 先改造views.py
user_list = [
     {'user':'jack', 'pwd':'abc'},
     {'user':'tom', 'pwd':'ABC'},    
]
def index(request):
    if(request.method == 'POST'):
        u = request.POST.get('user',None)
        p = request.POST.get('passwd',None)
        temp = {'user':u, 'pwd':p}
        user_list.append(temp)
    return render(request, 'index.html', {'data': data_list })

  

# 在改造index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <h1>用户输入:</h1>
    <form action="/index/" method="POST">
        <input type="text" name="user" />
        <input type="text" name="email" />
        <input type="submit" value="提交" />
    </form>
    <h1>数据展示:</h1>
    <table border="1">
        <tr>
            <th>用户名</th>
            <th>密码</th>
        </tr>
        {% for line in data %}
            <tr>
                <td>{{ line.user }}</td>
                <td>{{ line.pwd }}</td>
            </tr>
        {% endfor %}
    </table>
    <script src="/fff/jquery-1.8.2.min.js"></script>
</body>
</html>

  WEB页面效果:

用户实时输入的账户密码,会显示在web页面上,这是一个简单的交互。

十. 使用数据库

     如果要保留数据,当然还是需要将数据写入数据中。下面简单介绍数据库使用,默认Django 使用的sqlite3,我们也使用这个。

# 首先注册你的APP : cmdb
# 在settings.py文件中添加
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'cmdb',  # 你的APP
]
# 如果不注册它,数据库就不知道该给哪个APP创建表
# 配置数据库相关参数,如果使用sqlite3,则不需要修改

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# 再编辑models.py ,也就是MTV中的M,负责数据库方面
from django.db import models

class UserInfo(models.Model):  # 默认继承,这个继承是django的固定写法
    user = models.CharField(max_length=32)
    pwd = models.CharField(max_length=32)

  

# 再编辑models.py ,也就是MTV中的M,负责数据库方面
from django.db import models

class UserInfo(models.Model):  # 默认继承,这个继承是django的固定写法
    user = models.CharField(max_length=32)
    pwd = models.CharField(max_length=32)

  通过命令创建表:

python manage.py makemigrations

python manage.py migrate

 

# 最后修改views.py中的业务逻辑
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.shortcuts import redirect
from cmdb import models
# 处理用户请求

def index(request):
    if(request.method == 'POST'):
        u = request.POST.get('user',None)
        e = request.POST.get('email',None)
        models.UserInfo.objects.create(user=u,email=e)
    data_list = models.UserInfo.objects.all()
    return render(request, 'index.html', {'data': data_list })

  重启WEB后,用户交互户的数据就会保存在数据库中了。初步认知Django就到这了。

posted @ 2016-09-03 09:50  Auvღ  阅读(103)  评论(0)    收藏  举报