Django框架-Django初识

Posted 裙下的小香蕉

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django框架-Django初识相关的知识,希望对你有一定的参考价值。

Django初识

一、Web框架本质—自己实现Web框架

1、所有的Web应用本质上就是一个socket服务端,而用户的浏览器就是一个socket客户端

import socket

sk = socket.socket()
sk.bind((\'127.0.0.1\', 8888))
sk.listen()

while True:
    conn, addr = sk.accept()
    data = conn.recv(8192)
    conn.send(b\'OK\')
    conn.close()

 

 

2、增加HTTP协议响应头

import socket

sk = socket.socket()
sk.bind((\'127.0.0.1\', 8888))
sk.listen()

while True:
    conn, addr = sk.accept()
    data = conn.recv(8192)
    conn.send(b\'HTTP/1.1 200 OK\\r\\n\\r\\n\')
    conn.send(b\'OK\')
    conn.close()

 

 

3、根据用户请求不同的URL返回不同的内容

import socket

sk = socket.socket()
sk.bind((\'127.0.0.1\', 8888))
sk.listen()


# 将不同的页面封装成不同的函数
def index(url):
    page = "这是 {} 页面!".format(url)
    return bytes(page, encoding="utf8")


def home(url):
    page = "这是 {} 页面!".format(url)
    return bytes(page, encoding="utf8")


while True:
    conn, addr = sk.accept()
    data = conn.recv(8192)
    # 根据接收用户的信息获取url路径
    data = str(data, encoding=\'utf-8\')
    data1 = data.split("\\r\\n")[0]
    url = data1.split()[1]

    # 根据不同的路径返回不同内容
    if url == "/index/":
        response = index(url)
    elif url == "/home/":
        response = home(url)
    else:
        response = b"404 NOT FOUND"

    # 给客户端发送数据
    conn.send(b\'HTTP/1.1 200 OK\\r\\nContent-Type: text/html; charset=utf-8\\r\\n\\r\\n\')
    conn.send(response)
    conn.close()

 

 

4、用反射优化请求不同URL返回不同内容

import socket

sk = socket.socket()
sk.bind((\'127.0.0.1\', 8888))
sk.listen()


# 将不同的页面封装成不同的函数
def index(url):
    page = "这是 {} 页面!".format(url)
    return bytes(page, encoding="utf8")


def home(url):
    page = "这是 {} 页面!".format(url)
    return bytes(page, encoding="utf8")


# 定义一个url和实际要执行的函数的对应关系
url_list = [
    ("/index/", index),
    ("/home/", home),
]

while True:
    conn, addr = sk.accept()
    data = conn.recv(8192)

    # 根据接收用户的信息获取url路径
    data = str(data, encoding="utf-8")
    data1 = data.split("\\r\\n")[0]
    url = data1.split()[1]

    # 根据不同的路径返回不同内容
    func = None
    for i in url_list:
        if i[0] == url:
            func = i[1]
            break
    if func:
        response = func(url)
    else:
        response = b"404 NOT FOUND"

    # 给客户端发送数据
    conn.send(b\'HTTP/1.1 200 OK\\r\\nContent-Type: text/html; charset=utf-8\\r\\n\\r\\n\')
    conn.send(response)
    conn.close()

 

 

5、返回完整的静态HTML

import socket

sk = socket.socket()
sk.bind((\'127.0.0.1\', 8888))
sk.listen()


# 将不同的页面封装成不同的函数
def index(url):
    with open("index.html", "r", encoding="utf8") as f:
        s = f.read()
    return bytes(s, encoding="utf8")


def home(url):
    with open("home.html", "r", encoding="utf8") as f:
        s = f.read()
    return bytes(s, encoding="utf8")


# 定义一个url和实际要执行的函数的对应关系
url_list = [
    ("/index/", index),
    ("/home/", home),
]

while True:
    conn, addr = sk.accept()
    data = conn.recv(8192)

    # 根据接收用户的信息获取url路径
    data = str(data, encoding="utf-8")
    data1 = data.split("\\r\\n")[0]
    url = data1.split()[1]

    # 根据不同的路径返回不同内容
    func = None
    for i in url_list:
        if i[0] == url:
            func = i[1]
            break
    if func:
        response = func(url)
    else:
        response = b"404 NOT FOUND"

    # 给客户端发送数据
    conn.send(b\'HTTP/1.1 200 OK\\r\\nContent-Type: text/html; charset=utf-8\\r\\n\\r\\n\')
    conn.send(response)
    conn.close()

 

 

6、返回动态的HTML,本质上就是HTML内容中利用一些特殊的符号来替换要展示的数据;模板渲染有个现成的工具:jinja2

import time
import socket

sk = socket.socket()
sk.bind((\'127.0.0.1\', 8888))
sk.listen()


# 将不同的页面封装成不同的函数
def index(url):
    with open("index.html", "r", encoding="utf8") as f:
        s = f.read()
        now = str(time.asctime(time.localtime(time.time())))
        s = s.replace("@@oo@@", now)
    return bytes(s, encoding="utf8")


def home(url):
    with open("home.html", "r", encoding="utf8") as f:
        s = f.read()
    return bytes(s, encoding="utf8")


# 定义一个url和实际要执行的函数的对应关系
url_list = [
    ("/index/", index),
    ("/home/", home),
]

while True:
    conn, addr = sk.accept()
    data = conn.recv(8192)

    # 根据接收用户的信息获取url路径
    data = str(data, encoding="utf-8")
    data1 = data.split("\\r\\n")[0]
    url = data1.split()[1]

    # 根据不同的路径返回不同内容
    func = None
    for i in url_list:
        if i[0] == url:
            func = i[1]
            break
    if func:
        response = func(url)
    else:
        response = b"404 NOT FOUND"

    # 给客户端发送数据
    conn.send(b\'HTTP/1.1 200 OK\\r\\nContent-Type: text/html; charset=utf-8\\r\\n\\r\\n\')
    conn.send(response)
    conn.close()

 

7、返回动态的HTML,wsgiref版

import time
from wsgiref.simple_server import make_server

# 将不同的页面封装成不同的函数
def index(url):
    with open("index.html", "r", encoding="utf8") as f:
        s = f.read()
        now = str(time.asctime(time.localtime(time.time())))
        s = s.replace("@@oo@@", now)
    return bytes(s, encoding="utf8")


def home(url):
    with open("home.html", "r", encoding="utf8") as f:
        s = f.read()
    return bytes(s, encoding="utf8")


# 定义一个url和实际要执行的函数的对应关系
url_list = [
    ("/index/", index),
    ("/home/", home),
]

def run_server(environ, start_response):
    start_response(\'200 OK\', [(\'Content-Type\', \'text/html;charset=utf8\'), ])  # 设置HTTP响应的状态码和头信息
    url = environ[\'PATH_INFO\']  # 取到用户输入的url

    # 根据不同的路径返回不同内容
    func = None
    for i in url_list:
        if i[0] == url:
            func = i[1]
            break
    if func:
        response = func(url)
    else:
        response = b"404 NOT FOUND"
    return [response, ]

if __name__ == \'__main__\':
    httpd = make_server(\'127.0.0.1\', 8888, run_server)
    print("Serving HTTP on port 8888...")
    httpd.serve_forever()

 

8、返回动态的HTML,wsgiref + jinja2 版

import time
import jinja2
from wsgiref.simple_server import make_server

# 将不同的页面封装成不同的函数
def index(url):
    with open("index.html", "r", encoding="utf8") as f:
        s = f.read()
        now = str(time.asctime(time.localtime(time.time())))
        s = s.replace("@@oo@@", now)
    return bytes(s, encoding="utf8")

def home(url):
    with open("home.html", "r", encoding="utf8") as f:
        s = f.read()
    return bytes(s, encoding="utf8")

def person(url):
    with open("person.html", "r", encoding="utf8") as f:
        s = f.read()
         # 生成一个jinja2的Template(模板)对象
        template = jinja2.Template(s)
        data = {"name": "Yang", "hobby_list": ["爱好1", "爱好2", "爱好3"]}
         # 本质上是完成了字符串的替换
        response = template.render(data)
    return bytes(response, encoding="utf8")

# 定义一个url和实际要执行的函数的对应关系
url_list = [
    ("/index/", index),
    ("/home/", home),
    ("/person/", person),
]

def run_server(environ, start_response):
    start_response(\'200 OK\', [(\'Content-Type\', \'text/html;charset=utf8\'), ])  # 设置HTTP响应的状态码和头信息
    url = environ[\'PATH_INFO\']  # 取到用户输入的url

    # 根据不同的路径返回不同内容
    func = None
    for i in url_list:
        if i[0] == url:
            func = i[1]
            break
    if func:
        response = func(url)
    else:
        response = b"404 NOT FOUND"
    return [response, ]

if __name__ == \'__main__\':
    httpd = make_server(\'127.0.0.1\', 8888, run_server)
    print("Serving HTTP on port 8888...")
    httpd.serve_forever()

 

9、使用pymysql连接数据库

import time
import jinja2
import pymysql
from wsgiref.simple_server import make_server

# 将不同的页面封装成不同的函数
def index(url):
    with open("index.html", "r", encoding="utf8") as f:
        s = f.read()
        now = str(time.asctime(time.localtime(time.time())))
        s = s.replace("@@oo@@", now)
    return bytes(s, encoding="utf8")

def home(url):
    with open("home.html", "r", encoding="utf8") as f:
        s = f.read()
    return bytes(s, encoding="utf8")

def person(url):
    with open("person.html", "r", encoding="utf8") as f:
        s = f.read()
        # 生成一个jinja2的Template(模板)对象
        template = jinja2.Template(s)

        conn = pymysql.connect(
            host="127.0.0.1",
            port=3306,
            user="root",
            passwd="",
            db="userinfo",
            charset="utf8"
        )
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
        cursor.execute("SELECT name, hobby FROM user")
        user = cursor.fetchone()
        cursor.close()
        conn.close()

        hobby_list = user["hobby"].split()
        user["hobby_list"] = hobby_list

        # 本质上是完成了字符串的替换
        response = template.render(user)
    return bytes(response, encoding="utf8")

# 定义一个url和实际要执行的函数的对应关系
url_list = [
    ("/index/", index),
    ("/home/", home),
    ("/person/", person),
]

def run_server(environ, start_response):
    start_response(\'200 OK\', [(\'Content-Type\', \'text/html;charset=utf8\'), ])  # 设置HTTP响应的状态码和头信息
    url = environ[\'PATH_INFO\']  # 取到用户输入的url

    # 根据不同的路径返回不同内容
    func = None
    for i in url_list:
        if i[0] == url:
            func = i[1]
            break
    if func:
        response = func(url)
    else:
        response = b"404 NOT FOUND"
    return [response, ]

if __name__ == \'__main__\':
    httpd = make_server(\'127.0.0.1\', 8888, run_server)
    print("Serving HTTP on port 8888...")
    httpd.serve_forever()

 

二、Django初识

1、下载&安装

①建议安装最新LTS版 
pip3 install django==1.11.11

2、创建项目

①创建一个名为mysite的Django项目 
django-admin startproject mysite

 

或者pycharm新建一个Django项目

3、目录结构说明

   mysite/
   ├── manage.py   # 管理文件
   └── mysite      # 项目目录
       ├── __init__.py
       ├── settings.py  # 配置
       ├── urls.py  # 路由 --> URL和函数的对应关系
       └── wsgi.py  # runserver命令就使用wsgiref模块做简单的web server

4、运行操作 & 模板文件配置 & 静态文件配置

①运行Django项目: 
python manage.py runserver 127.0.0.1:8000 

 

或者直接用pycharm的运行


②模板文件配置

TEMPLATES = [
    {
        \'BACKEND\': \'django.template.backends.django.DjangoTemplates\',
        \'DIRS\': [os.path.join(BASE_DIR, "template")],  # template文件夹位置
        \'APP_DIRS\': True,
        \'OPTIONS\': {
            \'context_processors\': [
                \'django.template.context_processors.debug\',
                \'django.template.context_processors.request\',
                \'django.contrib.auth.context_processors.auth\',
                \'django.contrib.messages.context_processors.messages\',
            ],
        },
    },
]

具体从settings里面的tempaltes里面修改dirs路径

 

③静态文件配置

STATIC_URL = \'/static/\'  # HTML中使用的静态文件夹前缀
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),  # 静态文件存放位置
]

 

另外需要新建一个static文件夹存放css等文件:

④刚开始学习时可在配置文件中暂时禁用csrf中间件,方便表单提交测试

MIDDLEWARE = [
    \'django.middleware.security.SecurityMiddleware\',
    \'django.contrib.sessions.middleware.SessionMiddleware\',
    \'django.middleware.common.CommonMiddleware\',
    # \'django.middleware.csrf.CsrfViewMiddleware\',
    \'django.contrib.auth.middleware.AuthenticationMiddleware\',
    \'django.contrib.messages.middleware.MessageMiddleware\',
    \'django.middleware.clickjacking.XFrameOptionsMiddleware\',
]        

 

5、Django基础必备三件套介绍

  • from django.shortcuts import HttpResponse, render, redirect

①HttpResponse

  • 介绍 
    内部传入一个字符串参数,返回给浏览器
  • 示例
def index(request):
# 业务逻辑代码
return HttpResponse("OK")

 

②render

  • 介绍 
    除request参数外还接受一个待渲染的模板文件和一个保存具体数据的字典参数。 
    将数据填充进模板文件,最后把结果返回给浏览器。(类似于我们上面用到的jinja2)
  • 示例
def index(request):
# 业务逻辑代码
return render(request, "index.html", {"name": "yang", "hobby": ["hobby_1", "hobby_2"]})

 

 

③redirect

  • 介绍 
    接受一个URL参数,表示跳转到指定的URL
  • 示例
def index(request):
# 业务逻辑代码
return redirect("/home/")


最后:




以上是关于Django框架-Django初识的主要内容,如果未能解决你的问题,请参考以下文章

初识django

Django框架-Django初识

Django框架下载与Django框架初识

python——初识django的template

Python之初识Django项目

Python Day18(Django初识)