注册 我的社团

全部社团 > Python> 帖子

用Python写一个简单的Web框架【2

BigBoss
3698 0 0
发表于:06月19日 12:52 [ 只看楼主]

五、重构

上面的代码虽然奏效,但是在编码风格和灵活性方面有很多问题,下面逐步对其进行重构。

1、正则匹配URL

消除URL硬编码,增加URL调度的灵活性:

Python

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

#!/usr/bin/env python

# -*- coding: utf-8 -*-

 

"""application.py"""

 

import re ##########修改点

 

class my_app:

 

    urls = (

        ("/", "index"),

        ("/hello/(.*)", "hello"),

    ) ##########修改点

 

    def __init__(self, environ, start_response):

        self.environ = environ

        self.start = start_response

 

    def __iter__(self): ##########修改点

        path = self.environ['PATH_INFO']

        method = self.environ['REQUEST_METHOD']

 

        for pattern, name in self.urls:

            m = re.match('^' + pattern + '$', path)

            if m:

                # pass the matched groups as arguments to the function

                args = m.groups()

                funcname = method.upper() + '_' + name

                if hasattr(self, funcname):

                    func = getattr(self, funcname)

                    return func(*args)

 

        return self.notfound()

 

    def GET_index(self):

        status = '200 OK'

        response_headers = [('Content-type', 'text/plain')]

        self.start(status

  • 点赞  0
  • 收藏
  • 扫一扫分享朋友圈

    二维码

  • 分享

全部回复 (0) 倒向排序

课程推荐

社团热门帖