一句话描述

将数据库的东西通过ORM的映射取出来,通过view文件,按照template文件排出的模板渲染成HTML。当用户请求相应的url时,返回相应的结果。

安装

pip install django

获取版本号

import django
django.VERSION

配置使用

++ Django 所提供的命令

django-admin

++ 创建项目

django-admin startproject projectName

manage.py:命令行工具,可以用多种方式与该django项目进行交互;
projectName 文件夹里面有4个.py文件 
+ init.py:一个空的文件,用它标识一个目录为Python的标准包
+ settings.py:Django项目的配置文件,包括Django模块应用配置、数据库配置、模板配置等
+ urls.py:Django项目的URL声明
+ wsgi.py:与WSGI兼容的Web服务器,为你的项目提供服务的入口点

++ 创建应用

python manage.py startapp webName

migrations:用于记录models中数据的变更
admin.py:映射models中的数据到Django自带的admin后台
apps.py:用于应用程序的配置,在新的Django版本中新增文件
models.py:Django的模型文件,创建应用程序数据表模型(对应数据库的相关操作)
tests.py:创建Django测试用例
views.py:Django的视图文件,控制向前端页面展示的内容

Django 的管理

python manage.py createsuperuser,按提示输入用户名、邮箱、密码

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

# zebk/zebk/urls.py
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
url(r'^hello/', include('hello.urls')),
url(r'^admin/', admin.site.urls),
]

# zebk/hello/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]

# zebk/hello/views.py
# -*- coding: utf-8 -*-
from django.shortcuts import render

def index(request):
context = {}
context['hello'] = 'Hello Django!';
context['title'] = '中二病控丶!';
context['menuLists']=[
{'name':'首页'},
{'name':'Hello'},
{'name':'Admin'}
]
return render(request, 'hello.html', context)

# zebk/templates/base.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{title}}</title>
</head>
<body>
<ul class='menu'>
{% for menu in menuLists %}
<li><a href="javascript:;">{{ menu.name }}</a></li>
{% endfor %}
</ul>

<div class='main'>
{% block mainbody %}
<p>这是一个 Django 样例!</p>
{% endblock %}
</div>
</body>
</html>

# zebk/templates/hello.html
{%extends "base.html" %}
{% block mainbody %}
<h1>{{hello}}</h1>
<p> Django 模板应用实例 ... </p>
<p> 继承了 base.html 文件 ... </p>
{% endblock %}

# 访问地址
# localhost:10888/hello
# localhost:10888/admin

settings.py 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',

'应用名称', //新建的 app 如果不加到 INSTALL_APPS 中的话, django 就不能自动找到app中的模板文件

//管理界面本地化,设置编码、时区
LANGUAGE_CODE = 'zh-Hans' #'en-us'
TIME_ZONE = 'Asia/Shanghai' #'UTC'
)

// 数据库配置
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'mysql': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test',
'USER': 'test',
'PASSWORD': 'test123',
'HOST':'localhost',
'PORT':'3306',
}
}

启动 Django

python manage.py runserver 0.0.0.0:10888

url $ 警告:$ 修改成 /

++ Django 采用了MVC的软件设计模式,即模型M,视图V和控制器C。

Django 模板标签

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

# if/else 标签
{% if condition1 %}
... display 1
{% elif condition2 %}
... display 2
{% else %}
... display 3
{% endif %}

# for 标签
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}

# ifequal/ifnotequal 标签
{% ifequal user currentuser %}
<h1>Welcome!</h1>
{% endifequal %}

# 注释标签
{# 这是一个注释 #}

# 过滤器
{{ my_list|first|upper }}
{{ bio|truncatewords:"30" }}

# include 标签
{% include "nav.html" %}

# 继承模板
{%extends "base.html" %}

{% block mainbody %}
<p>继承了 base.html 文件</p>
{% endblock %}

访问配置文件

from django.conf import settings
sql_str = settings.DATABASES

使用外部样式,脚本,第三方库控件

STATIC_URL = '/static/'
STATICFILES_DIRS=(
    os.path.join(BASE_DIR,'static'),  #注意括号后面的还有个逗号
)

项目目录,创建 static -> css/imgs/jscript/plugins

Django for循环计数器:forloop

forloop.counter
forloop.revcounter
forloop.first
forloop.last
forloop.parentloop

Nginx 配置

高性能的HTTP和反向代理服务器,同时也是一个 IMAP/POP3/SMTP 代理服务器
在高并发连接的情况下,Nginx 是 Apache 服务器不错的替代品。Nginx 同时也可以作为7层负载均衡服务器来使用。

++ 下载 Nginx
++ 解压后,进入目录下,start nginx.exe

**注意:80端口是否被占用**

Nginx相应命令

nginx.exe -s stop           //停止nginx
nginx.exe -s reload         //重新加载nginx
nginx.exe -s quit           //退出nginx
nginx.exe -s reopen         //重新打开日志文件
nginx –v
uwsgi 不支持 windows
++ Uwsgi 配置
pip install uwsgi
报错:AttributeError: module 'os' has no attribute 'uname'
原因:os.uname()是不支持windows系统的,platform模块是支持任何系统。

++ 下载uwsgi离线安装
++ 解压后,进入目录下,修改 uwsgiconfig.py 文件中的os.uname()为platform.uname()
++ cd进入目录执行:python setup.py install

报错:Exception: you need a C compiler to builduWSGI
本机上没有C编译环境,需要下载一个编译器

++ 推荐下载:MinGW
++ 配置环境变量:path=MinGW安装目录/bin
++ python setup.py install

1.9以上的 django 移除了 FastCGI 支持
++ FastCGI配置

++ flup - Python的FastCGI组件下载

pip install flup

python manage.py runfcgi method=threaded host=127.0.0.1 port=8051
报错:Unknown command: 'runfcgi' 。

Window IIS Django

  • 安装 wfastcgi
pip install wfastcgi
  • 复制一份 wfastcgi.py 文件到项目根目录
wfastcgi-enable  //wfastcgi.py 安装路径
  • IIS 发布网站
  • 添加处理程序映射的模块映射,CGI组件必须安装
填写模块映射参数:
请求路径为 *,
模块为 FastCgiModule,
可执行文件选择 [你的python安装路径]|[项目中wfastcgi.py的路径],
示例:"D:\Python36\python.exe"|D:\web\wfastcgi.py
名称随意
  • 请求限制,去掉勾选
  • IIS 根节点,修改FastCGI设置,编辑FastCGI应用程序的环境变量
WSGI_HANDLER:django.core.wsgi.get_wsgi_application()
PYTHONPATH:项目路径
DJANGO_SETTINGS_MODULE:项目名称.settings

     ** 静态文件访问设置 **

  • static 目录创建 web.config
1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
      <!-- this configuration overrides the FastCGI handler to let IIS serve the static files -->
      <handlers>
<clear/>
<add name="StaticFile" path="*" verb="*" modules="StaticFileModule"
resourceType="File" requireAccess="Read" />
     </handlers>
   </system.webServer>
</configuration>
  • Admin 管理样式丢失
设置 settings.py:STATIC_ROOT = os.path.join(BASE_DIR,'static')
执行python命令:python manage.py collectstatic
  • IIS 网站虚拟路径设置

    右键 -> 添加虚拟目录 -> static/创建 web.config 的 static 目录路径

  • 重启 IIS,运行

SqlServer Models

++ Django 中使用 Microsoft SQL SERVER
++ 扩展资料
++ QuerySet

安装三方库

pip install pyodbc django-pyodbc-azure

    ODBC 驱动配置

DATABASES 数据库连接串配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
'default': {
#数据库引擎设置
'ENGINE': 'sql_server.pyodbc',
#数据库主机地址
'HOST': 'xxx',
#数据库端口号,默认可以不写
'PORT': '',
#要连接的数据库名
'NAME': 'xxx',
#数据库用户名
'USER': 'sa',
#数据库密码
'PASSWORD': 'xxx',
#选项,这个要先在操作系统上完成ODBC的连接创建,并连接成功,注意 DRIVER 这个地方,要和自己的ODBC版本一致
'OPTIONS': {
'DRIVER':'SQL Server',
#使用MARS (multiple active result sets),支持异步
# 'MARS_Connection': True,
},
},

模型使用

将变更的 models.py 登记到当前APP的 migrations 文件夹中的_init.py文件中

python manage.py makemigrations  

将登记的改动信息转换成SQL语句,转移到数据库中执行

python manage.py migrate       
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from django.db import models
# 创建的对象必须继承 Model
class Children(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
age = models.IntegerField()
phone = models.CharField(max_length=11)

class Meta:
db_table = "Hello_Children"

def __tuple__(self):
id = self.id
name = self.name
age = self.age
phone = self.phone

return id,name,age,phone

Django 中常用返回查询集

all() 返回所有数据
get() 获取符号条件的数据
filter() 返回符合条件的数据
exclude() 返回符合条件之外的数据
order_by() 对结果进行排序 

补充知识

单文件 Django
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from django.conf import settings
from django.http import HttpResponse
from django.conf.urls import url
setting = {
'DEBUG':True,
'ROOT_URLCONF':__name__
}

settings.configure(**setting)

def home(request):
return HttpResponse('Hello world!')

urlpatterns = [url('^$',home,name='home')]

if __name__ == '__main__':
import sys
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
  • django 中,加载配置文件有两种方式:
    settings.configure(**settings)
    django.setup()

  • python test.py runserver

pipreqs

可以帮你找到当前项目的所有组件及其版本

# 安装
pip install pipreqs
# 生成 requirements.txt
pipreqs ./ --encoding=utf-8
# 安装项目组件
pip3 install -r requirements.txt
其他