自定义python框架_Python自定义web框架、Jinja2

WSGI(Web Server Gateway Interface)是一种规范,它定义了使用python编写的web app与web server之间接口格式,实现web app与web server间的解耦。

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

标准Web框架

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

'

if __name__ == '__main__':

httpd = make_server('', 8000, RunServer)

print "Serving HTTP on port 8000..."

httpd.serve_forever()

自定义Web框架

from wsgiref.simple_server import make_server

def login():

return 'login'

def index():

data = open('index.html','r').read()

return data

url = (

('/login/',login),

('/index/',index),

)

def RunServer(environ, start_response):

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

geturl = environ['PATH_INFO']

for item in url:

if item[0] == geturl:

return item[1]()

else:

return '404'

if __name__ == '__main__':

httpd = make_server('', 8000, RunServer)

print "Serving HTTP on port 8000..."

httpd.serve_forever()

MVC和MTV       代码堆放的归类

MVC:Model、View、Controller    model存放数据操作,view存放html文件,controller负责逻辑处理

MTV:Model、Template、View

model存放数据操作,Template存放html文件,View负责逻辑处理

Django是 MTV模式

模板渲染jinja2

from wsgiref.simple_server import make_server

import time

from jinja2 import Template

import sys

reload(sys)

sys.setdefaultencoding('utf8') #//解决UnicodeDecodeError

def login():

return 'login'

def index():

data = open('index.html','r').read()

current_time = time.strftime('%Y-%m-%d %H:%M:%S')

template = Template(data) #使用jinja2模板处理

result = template.render(name='yangmv',

age='18',

current_time=current_time,

user_list=['wj','sb',],

num=1,

)

return result.encode('utf-8')

url = (

('/login/',login),

('/index/',index),

)

def RunServer(environ, start_response):

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

geturl = environ['PATH_INFO']

for item in url:

if item[0] == geturl:

return item[1]()

else:

return '404'

if __name__ == '__main__':

httpd = make_server('', 8000, RunServer)

print "Serving HTTP on port 8000..."

httpd.serve_forever()

{{ name }}

{{ age }}

{{ current_time }}

{% for item in user_list %}

{{item}}

{% endfor %}

{% if num == 1 %}

111

{% else %}

222

{% endif %}

你可能感兴趣的:(自定义python框架)