首页 > 代码库 > django

django

  对于所有的Web应用,本质上其实就是一个socket服务端,用户的浏览器其实就是一个socket客户端。

阶段1

socket服务端和客户端都自己编写

实现访问8080端口,返回一个‘hello world‘

技术分享
#!/usr/bin/env python
#encoding: utf-8
#@2017-03-30
"""最简单的web框架"""
 
import socket

def handle_request(client):
    """应用程序,web开发者自定义部分"""
    buf = client.recv(1024)
    client.send(HTTP/1.1 200 OK\1\n\r\n)
    client.send("Hello, world!")
    
def server():
    """服务端程序,web开发者共用部分
    本质:对socket进行封装"""
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind((0.0.0.0, 8080))
    sock.listen(5)
    
    while True:
        connection, address = sock.accept()
        handle_request(connection) # 阻塞
        connection.close()

if __name__ == __main__:
    server()
View Code

 

阶段2

socket服务端由python封装后提供,实现访问8000端口,返回一个‘hello world‘

技术分享
#!/usr/bin/env python
#coding:utf-8

# 封装后的服务程序
from wsgiref.simple_server import make_server

def RunServer(environ, start_response):
    start_response(200 OK, [(Content-Type, text/html)])
    return Hello, world!

if __name__ == __main__:
    httpd = make_server(0.0.0.0, 8000, RunServer)
    print "Serving HTTP on port 8000..."
    httpd.serve_forever()
View Code

 

阶段3

一些功能模块化,逐渐有了django的影子

demo:<strong><a href="http://files.cnblogs.com/files/wupeiqi/django_dynamic_router.rar" target="_blank">点击下载</a></strong>

main.py作为程序入口

技术分享
#!/usr/bin/env python
#coding:utf-8

# 封装后的服务程序
from wsgiref.simple_server import make_server
from urls import url

def RunServer(environ, start_response):
    start_response(200 OK, [(Content-Type, text/html)])
    # 获取用户URL
    user_url = environ[PATH_INFO]
    
    # 根据URL不同返回不同的结果
    for item in url:
        if item[0] == user_url:
            return item[1]()
    else:
        return <h1>404 not found</h1>

if __name__ == __main__:
    httpd = make_server(0.0.0.0, 8000, RunServer)
    print "Serving HTTP on port 8000..."
    httpd.serve_forever()
View Code

 

views.py方法函数

技术分享
#!/usr/bin/env python
#coding:utf-8

def index():
    return index

def login():
    return login

def logout():
    return logout

url = (
    (/index/, index),
    (/login/, login),
    (/logout/, logout),
)
View Code

 

url到方法函数的映射urls.py

技术分享
#encoding: utf-8
from views import *

"""指定URL到处理函数的映射"""
url = (
    (/index/, index),
    (/login/, login),
    (/logout/, logout),
)
View Code

django