當前位置:成語大全網 - 新華字典 - 如何用Python寫壹個web框架

如何用Python寫壹個web框架

STEP.1

我們首先得選擇基於什麽協議來寫這種框架。我們可以選擇CGI協議,或者是WSGI接口。如果使用CGI,實際上我們只是按著CGI的規範寫了壹個python程序,然後每次服務器收到請求,就fork壹個程序來執行它,然後返回壹個ment/$','func_comment'),

('^/environ/$','get_environ'),

('^/post/$','post_test')]#urls是提供給app開發者來做鏈接的。

def getPage(self):

path = self.environ['PATH_INFO']

for pattern in self.urls:

m = re.match(pattern[0],path)#將urls元素的第0項和path進行比對,如果匹配上了,返回函數名

if m:

function = getattr(self,pattern[1])#getattr方法來得到函數

return function()

return '404 not found'#沒匹配上任何東西

寫到這裏之後,每次添加頁面,就只需要在urls列表中添加壹個元祖就行了。

STEP.4 獲取模版

既然是寫web app,模版肯定是得有的。這裏我提供了壹種getTemplate方法來做這件事。不過我只提供了變量的替換。

def getTemplate(self,tem_name,rep=0):

#這個函數返回內容,tem_name是文件名字

#參數rep是壹個字典,默認為0

f = open('template/'+tem_name)

html = f.read()

if(rep!=0):

for to_replace in rep:

strinfo = re.compile('\{\%\s*'+str(to_replace)+'\s*\%\}')

html = strinfo.sub(rep[to_replace],html)

return html

STEP.5 POST數據的處理

要想獲取POST數據,我們得通過environ['wsgi.input']來處理。而他實際上就是系統的標準輸入。

environ['wsgi.input'] = sys.stdin

知道這點後就很好寫了。

def getPost(self):

if(self.environ['REQUEST_METHOD'] == 'POST'):

try:

request_body_size = int(self.environ.get('CONTENT_LENGTH', 0))#讀出content_length的值

except:

request_body_size = 0

request_body = self.environ['wsgi.input'].read(request_body_size) #請求的body

post_data = parse_qs(request_body)#parse_qs是cgi提供的方法,幫助我們處理請求

return post_data

數據庫的鏈接

import MySQLdb

class Model(object):

def __init__(self):

self.host = 'localhost'

self.port = 3306

self.user = 'admin'

self.passwd = 'admin'

self.db = 'xieyi'

def build_connect(self):

self.conn = MySQLdb.connect(

host = self.host,

port = self.port,

user = self.user,

passwd = self.passwd,

db = self.db

)

def exec_ins(self,ins):

cur = self.conn.cursor()

num = cur.execute(ins)

info = {}

if(num>0):

info = cur.fetchmany(num)

cur.close()

self.conn.commit()

return info

def close(self):

self.conn.close()

STEP.6 清理工作

很多配置如果放到代碼中,會增加閱讀負擔。於是把urls,model抽取出來。

使得配置更加方便。