Django基础教程总结


本文摘自php中文网,作者php中文网,侵删。

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

一个简单的web程序:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

#!/usr/bin/env python

#coding:utf-8

  

import socket

  

def handle_request(client):

    buf = client.recv(1024)

    client.send("HTTP/1.1 200 OK\r\n\r\n")

    client.send("Hello, Seven")

  

def main():

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    sock.bind(('localhost',8000))

    sock.listen(5)

  

    while True:

        connection, address = sock.accept()

        handle_request(connection)

        connection.close()

  

if __name__ == '__main__':

    main()

python web程序一般会分为服务器程序和应用程序。服务器程序负责对socket服务器进行封装,并在请求到来时对请求的各种数据进行整理。应用程序则负责具体的逻辑处理。为了方便应用程序的开发,就出现了众多的web框架。例如Django,Flask,web.py等。

不同的框架有不同的开发方式,但是无论如何,开发出的应用程序都要和服务器程序配合,再能为用户提供服务。这样,服务器程序就需要为不同的框架提供不同的支持。这样混乱的局面无论对服务器还是框架,都是不好的。对服务器来说,需要支持各种不同框架,对框架来说只有支持它的服务器才能被开发出的应用使用。这个时候,标准化就变的尤为重要。我们可以设立一个标准,只要服务器程序支持这个标准,框架也支持这个标准,那么他们就可以配合使用。一旦标准确定,双方各自实现。这样,服务器可以支持更多支持标准的框架,框架也可以使用更多支持标准的服务器。

WSGI

web server gateway interface 是一种规范,它定义了使用python编写的web app与web server 之间的接口格式,实现 web app与 web server间的解耦。

python标准库提供的独立的wsgi服务器称为wsgiref

1

2

3

4

5

6

7

8

9

10

#!/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 '<h1>Hello, web!</h1>'

if __name__ == '__main__':

    httpd = make_server('', 8000, RunServer)

    print "Serving HTTP on port 8000..."

    httpd.serve_forever()

自定义web框架

通过python标准库提供的wsgiref模块开发一个自己的web框架

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

#!/usr/bin/env python

#coding:utf-8

from wsgiref.simple_server import make_server

def index():

    return 'index'

def login():

    return 'login'

def routers():

     

    urlpatterns = (

        ('/index/',index),

        ('/login/',login),

    )

     

    return urlpatterns

def RunServer(environ, start_response):

    start_response('200 OK', [('Content-Type', 'text/html')])

    url = environ['PATH_INFO']

    urlpatterns = routers()

    func = None

    for item in urlpatterns:

        if item[0] == url:

            func = item[1]

            break

    if func:

        return func()

    else:

        return '404 not found'

     

if __name__ == '__main__':

    httpd = make_server('', 8000, RunServer)

    print "Serving HTTP on port 8000..."

    httpd.serve_forever()

以上就是Django基础教程总结的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python在函数中使用列表作为默认参数的介绍(代码示例)

Python的数据结构

实例讲解Python基于回溯法子集树模板解决旅行商问题(tsp)

Python交互模式下输入命令怎么换行

Python用什么软件写爬虫

Python如何创建二维列表?

Python如何声明全局变量

Python可以自学吗

一次完整的自动化登录测试-2017-7-4

总结Python常用的机器学习库

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...