Python全栈 part02 - 005 Django(一)

什么是web框架

框架(framework),指为解决一个开放性问题而设计的具有一定约束的支撑结构.

对于web应用来说,其本质上就是一个socket服务端,下面代码使用socket实现一个静态web应用:

import socket

def handle_request(client):
    buf = client.recv(1024)
    client.send("HTTP/1.1 200 OK\r\n\r\n".encode("utf-8"))
    client.send("

Hello, fbo

".encode("utf-8")) def main(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('localhost', 8001)) sock.listen(5) while True: connection, address = sock.accpet() handle_request(connection) connection.close() if __name__ == "__main__": main()

最简单的Web应用就是把HTML文件先保存好,用一个现成的http服务器软件,从文件中读取HTML然后返回.

WSGI实现动态web框架

下面我们来使用Python的WSGI接口来编写动态web框架

  1. 简单的wsgi示例
from wsgiref.simple_server import make_server

def application(environ, start_response):
    start_response("200 OK", [('Content-Type', 'text/html')])
    return [b'

Hello web!

'] prot = 8080 httpd = make_server('', port, application) print('Serving Http on port %s...' % (port)) # 开始监听HTTP请求 httpd.serve_forever()

appliction()函数没有设计到任何解析HTTP的部分,由程序自己封装;
application()函数必须由wsgi服务器来调用;
python内置了一个WSGI服务器,这个模块叫做wsgiref;
application()函数就是一个标准的HTTP处理函数,它接受两个函数environ(包含所有HTTP请求的dict对象),start_response(一个发送HTTP响应的函数);

  1. 定义http路由
print(environ['PATH_INFO'])
path=environ['PATH_INFO']
start_response('200 ok',['Content-Type', 'text/html'])
f1 = open("index.html", "rb")
data1=f1.read()
f1.close()
f2 = open("index2.html", "rb")
data2 = f2.read()
f2.close()

if path == "/index1":
    return [data1]
elif path == "/index2":
    return [data2]
else:
    return ["

404

".encode('utf-8')]
  1. 将函数分离
from wsgiref.simple_server import make_server

def f1():
    f1.open("index1.html", "rb")
    data1=f1.read()
    f1.close()
    return [data1]
    
def f2():
    f2.open("index2.html", "rb")
    data2=f2.read()
    f2.close()
    return data2
    
def application(environ, start_response):
    print(environ['PATH_INFO'])
    path=environ['PATH_INFO']
    start_response('200 OK', [('Content-Type', 'text/html')])
    
    if path == '/index1':
        return f1()
    elif path == '/index2':
        return f2()
    else:
        return ["

404

.encode("utf-8")] httpd = make_server('', 8502, application) print("Serving HTTP on 8502...") httpd.serve_forever()
  1. 引入模板
from wsgiref import make_server

def f1(req):
    print(req)
    print(req["QUERY_STRING"])
    with open("index1.html", "rb") as f1:
        data1 = f1.read()
        return [data1]
        
def f2(req):
    with open("index2.html", "rb") as f2:
        data2 = f2.read()
        return [data2]

import time

def f3(req):    # modle and database
    with open("index3.html", "rb")
    data3 = f3.read()
    times = time.strftime("%Y-%m-%d %X", time.localtime())
    data3 = str(data3, "utf-8").replace("!time!", str(times))
    return [data3.encode("utf-8")]
    
    
def routers():
    urlpatterns = (
    ('/index1', f1),
    ('/index2', f2),
    ('/cur_time', f3),
    )
    return urlpatterns
    
def application(environ, start_response):
    print(environ['PATH_INFO'])
    path=environ['PATH_INFO']
    start_response('200 OK', [('Content-Type', 'text/html')])
    
    urlpatterns = routers()
    func = None
    for item in urlpatterns:
        if item[0] == path:
            func = item[1]
            break
    if func:
        return func(environ)
    else:
        return ["

404

".encode("utf-8")] httpd = make_server('', 8518, application) print('Serving HTTP on port 8518...') httpd.make_serve_forever()

MVC和MTV模式

MVC模式

  • M(model): 模型,负责与数据库交互
  • V(view): 视图, 展现给用户的html
  • C(Controller), 控制器, url和路由分发

MTV模式

Django使用的是MTV模式

  • Model(模型): 负责业务对象与数据库对象(ORM)
  • Template(模板): 负责如何把页面展示给用户
  • View(视图): 负责业务逻辑,并在适当的时候调用Model和Template

此外Django还有一个url分发器, 将不同的URL请求分发给不同的view处理

初识Django(Django使用流程)

# 1. 创建django项目
$ django-admin startproject mysite

$ tree mysite/
mysite/
├── manage.py       --> Django项目里面的工具,通过它可以调用django shell和数据库
└── mysite
    ├── __init__.py
    ├── settings.py     --> 包含项目默认设置,包括数据库信息,调试标志以及一些工作的变量
    ├── urls.py     --> 负责把URL映射到应用程序
    └── wsgi.py

2. 创建blog应用
$ python3 manage.py startapp blog

$ tree
.
├── blog
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py       --> 数据库操作
│   ├── tests.py
│   └── views.py        --> 写函数
├── manage.py
└── mysite
    ├── __init__.py
    ├── __pycache__
    │   ├── __init__.cpython-35.pyc
    │   └── settings.cpython-35.pyc
    ├── settings.py
    ├── urls.py
    └── wsgi.py
    
# 3. 启动项目
$ python3 manage.py runserver 8080
Performing system checks...

System check identified no issues (0 silenced).

You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

January 23, 2018 - 07:11:03
Django version 2.0.1, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8080/
Quit the server with CONTROL-C.

你可能感兴趣的:(Python全栈 part02 - 005 Django(一))