自己动手写一个web框架,因为我是菜鸟,对于python的一些内建函数不是清楚,所以在写这篇文章之前需要一些python和WSGI的预备知识,这是一系列文章。这一篇只实现了如何处理url。

参考这篇文章:http://www.cnblogs.com/russellluo/p/3338616.html

预备知识

web框架主要是实现web服务器和web应用之间的交互。底层的网络协议主要有web服务器完成。譬如监听端口,填充报文等等。

Python内建函数__iter__和__call__和WSGI

迭代器iterator

迭代器为类序列对象提供了类序列的接口,也就是说类序列对象可以通过迭代器像序列一样进行迭代。说简单一点就是遍历对象。如果想让类是可迭代的,那么就必须实现__iter__和next()。

__call__

只要在类定义的时候实现了__call__方法,那么该类的对象就是可调有的,即可以将对象当做函数来使用。这里只用明白什么是__call__函数即可,因为WSGI规范中用要求。

WSGI

关于WSGI的介绍可以点击http://webpython.codepoint.net,有很详细的介绍。这里只说明一下大概。WSGI接口是用可调用的对象实现的:一个函数,一个方法或者一个可调用的实例。下面是一个实例,注释写的很详细:

# This is our application object. It could have any name,
# except when using mod_wsgi where it must be "application"
def application( # It accepts two arguments:
# environ points to a dictionary containing CGI like environment variables
# which is filled by the server for each received request from the client
environ,
# start_response is a callback function supplied by the server
# which will be used to send the HTTP status and headers to the server
start_response): # build the response body possibly using the environ dictionary
response_body = 'The request method was %s' % environ['REQUEST_METHOD'] # HTTP response code and message
status = '200 OK' # These are HTTP headers expected by the client.
# They must be wrapped as a list of tupled pairs:
# [(Header name, Header value)].
response_headers = [('Content-Type', 'text/plain'),
('Content-Length', str(len(response_body)))] # Send them to the server using the supplied function
start_response(status, response_headers) # Return the response body.
# Notice it is wrapped in a list although it could be any iterable.
return [response_body]

简单来说就是根据接收的参数来返回相应的结果。

设计web框架

我之前用过django写过一个很简单的博客,目前放在SAE上,好久没更新了。网址:http://3.mrzysv5.sinaapp.com。一个web框架最基本的要求就是简化用户的代码量。所以在django中,我只需要写view、model和url配置文件。下面是我用django时写的一个处理视图的函数:

def blog_list(request):
blogs = Article.objects.all().order_by('-publish_date')
blog_num = Article.objects.count()
return render_to_response('index.html', {"blogs": blogs,"blog_num":blog_num}, context_instance=RequestContext(request))
def blog_detail(request):
bid = request.GET.get('id','')
blog = Article.objects.get(id=bid)
return render_to_response('blog.html',{'blog':blog})

需要我完成的就是操作数据库,返回相应的资源。所以我要编写的web框架就要尽可能的封装一些底层操作,留给用户一些可用的接口。根据我的观察,web框架的处理过程大致如下:

  1. 一个WSGI应用的基类初始化时传入配置好的url文件
  2. 用户写好处理方法,基类根据url调用方法
  3. 返回给客户端视图

一个WSGI基类,主要有以下的功能:

  • 处理environ参数
  • 根据url得到方法或者类名,并执行后返回
import re
class WSGIapp: headers = [] def __init__(self,urls=()):
self.urls = urls
self.status = '200 OK' def __call__(self,environ,start_response): x = self.mapping_urls(environ)
print x
start_response(self.status,self.headers) if isinstance(x,str):
return iter([x])
else:
return iter(x) def mapping_urls(self,environ):
path = environ['PATH_INFO'] for pattern,name in self.urls:
m = re.match('^'+pattern+'$',path)
if m:
args = m.groups()
func = globals()[name]
return func(*args)
return self.notfound() def notfound(self):
self.status = '404 Not Found'
self.headers = [('Content-Type','text/plain')]
return '404 Not Found\n' @classmethod
def header(cls,name,value):
cls.headers.append((name,value)) def GET_index(*args):
WSGIapp.header('Content-Type','text/plain')
return 'Welcome!\n'
def GET_hello(*args):
WSGIapp.header('Content-Type','text/plain')
return 'Hello %s!\n' % args
urls = [
('/','GET_index'),
('/hello/(.*)','GET_hello')
]
wsgiapp = WSGIapp(urls) if __name__ == '__main__':
from wsgiref.simple_server import make_server
httpd = make_server('',8000,wsgiapp)
print 'server starting...'
httpd.serve_forever()

上面的代码是不是很简介了,只需要定义函数即可。

Python学习 - 编写一个简单的web框架(一)的更多相关文章

  1. Python学习 - 编写一个简单的web框架(二)

    在上一篇日志中已经讨论和实现了根据url执行相应应用,在我阅读了bottle.py官方文档后,按照bottle的设计重写一遍,主要借鉴大牛们的设计思想. 一个bottle.py的简单实例 来看看bot ...

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

    一.概述 二.从demo_app开始 三.WSGI中的application 四.区分URL 五.重构 1.正则匹配URL 2.DRY 3.抽象出框架 六.参考 一.概述 在Python中,WSGI( ...

  3. 使用Java编写一个简单的Web的监控系统cpu利用率,cpu温度,总内存大小

    原文:http://www.jb51.net/article/75002.htm 这篇文章主要介绍了使用Java编写一个简单的Web的监控系统的例子,并且将重要信息转为XML通过网页前端显示,非常之实 ...

  4. 一个简单的web框架实现

    一个简单的web框架实现 #!/usr/bin/env python # -- coding: utf-8 -- __author__ = 'EchoRep' from wsgiref.simple_ ...

  5. 动手写一个简单的Web框架(HelloWorld的实现)

    动手写一个简单的Web框架(HelloWorld的实现) 关于python的wsgi问题可以看这篇博客 我就不具体阐述了,简单来说,wsgi标准需要我们提供一个可以被调用的python程序,可以实函数 ...

  6. 编写一个简单的Web Server

    编写一个简单的Web Server其实是轻而易举的.如果我们只是想托管一些HTML页面,我们可以这么实现: 在VS2013中创建一个C# 控制台程序 编写一个字符串扩展方法类,主要用于在URL中截取文 ...

  7. 动手写一个简单的Web框架(模板渲染)

    动手写一个简单的Web框架(模板渲染) 在百度上搜索jinja2,显示的大部分内容都是jinja2的渲染语法,这个不是Web框架需要做的事,最终,居然在Werkzeug的官方文档里找到模板渲染的代码. ...

  8. 动手写一个简单的Web框架(Werkzeug路由问题)

    动手写一个简单的Web框架(Werkzeug路由问题) 继承上一篇博客,实现了HelloWorld,但是这并不是一个Web框架,只是自己手写的一个程序,别人是无法通过自己定义路由和返回文本,来使用的, ...

  9. 使用Python来编写一个简单的感知机

    来表示.第二个元素是表示期望输出的值. 这个数组定义例如以下: training_data = [  (array([0,0,1]), 0),  (array([0,1,1]), 1),  (arra ...

随机推荐

  1. ios打包ipa的四种实用方法

    总结一下,目前.app包转为.ipa包的方法有以下几种: 1.Apple推荐的方式,即实用xcode的archive功能 Xcode菜单栏->Product->Archive->三选 ...

  2. 定制Centos系统(基于6.x)

    1.条件准备:      按照需求,最小化安装Centos原生系统           在安装后的系统中找到/root/install.log与/root/anaconda-ks.cfg文件     ...

  3. the partition number

    有一个容量为n的背包,有1, 2, 3, ..., n这n种物品,每种物品可以无限使用,求装满的方案数. 法一: http://mathworld.wolfram.com/PartitionFunct ...

  4. dom0的cpu hotplug【续】

    上一篇说到,手动xm vcpu-pin住,在hotplug就好了. 本质上,还是因为代码有bug,导致vcpu offline的时候,信息没有清理干净,有残留,当vcpu online的时候,如果调度 ...

  5. hdu 4742 Pinball Game 3D 分治+树状数组

    离散化x然后用树状数组解决,排序y然后分治解决,z在分治的时候排序解决. 具体:先对y排序,solve(l,r)分成solve(l,mid),solve(mid+1,r), 然后因为是按照y排序,所以 ...

  6. DSPack各种使用方法

    1. DSPack 2.3.4 安装   一. 下载由于sourceforge最近不能访问,所以可以去 http://www.progdigy.com/ 下载.下载 http://www.progdi ...

  7. Java基础知识强化之集合框架笔记33:Arrays工具类中asList()方法的使用

    1. Arrays工具类中asList()方法的使用 public static <T> List<T> asList(T... a): 把数组转成集合 注意事项: 虽然可以把 ...

  8. mailsend - Send mail via SMTP protocol from command line

    Introduction mailsend is a simple command line program to send mail via SMTP protocol. I used to sen ...

  9. 9.28noip模拟试题

    1.栅栏迷宫 田野上搭建了一个黄金大神专用的栅栏围成的迷宫.幸运的是,在迷宫的边界上留出了两段栅栏作为迷宫的出口.更幸运的是,所建造的迷宫是一个“完美的”迷宫:即你能从迷宫中的任意一点找到一条走出迷宫 ...

  10. new Integer(1)和Integer.valueOf(1)的区别

    java.lang包中的Integer类是我们比较常用的类,比如以下代码: Integer a=new Integer(1) Integer a=Integer.valueOf(1); 两个都是得到一 ...