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

自己动手写一个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()

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

时间: 2024-08-24 06:55:36

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

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

在上一篇日志中已经讨论和实现了根据url执行相应应用,在我阅读了bottle.py官方文档后,按照bottle的设计重写一遍,主要借鉴大牛们的设计思想. 一个bottle.py的简单实例 来看看bottle是如何使用的,代码来自http://www.bottlepy.org/docs/0.12/index.html: from bottle import route, run, template @route('/hello/<name>') def index(name): return t

一个简单的web框架实现

一个简单的web框架实现 #!/usr/bin/env python # -- coding: utf-8 -- __author__ = 'EchoRep' from wsgiref.simple_server import make_server def index(): # data = open('html/index.html').read() return data def echo(): # data = open('html/echo.html').read() return d

编写一个简单的Web应用

上一篇我们搭建了一个简单的Web应用:http://www.cnblogs.com/lay2017/p/8468515.html 本文将基于上一篇搭建的应用,编写一些内容 编写Servlet类 编写JSP页面 首先我们添加目录结构如下: 这里在java类目录下添加了cn.lay目录,并创建了HelloServlet的Java文件 在webapp/WEB-INF目录下创建了jsp目录,并创建了hello.jsp文件 HelloServlet.java package cn.lay; import

python web编程(一): web流程,手写一个简单的web框架

# -*- coding: utf-8 -*-__author__ = 'xzq' '''1. HTTP: 特点: 1>. 请求/响应模式 2>. 无状态协议, Client每一次访问都会被Server当作是第一次访问 (Cookie, Session) Request: POST /index.html HTTP/1.1 # 请求方法 url 协议版本 Header: Host: www.bilibili.com # 请求域名 --> DNS Connection: keep-aliv

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

https://blog.dbrgn.ch/2013/3/26/perceptrons-in-python/ 目前,我在HSR上参加了一个神经网络和机器学习的课程,其中学习到一个最简单的神经网络模型,就是感知机(perceptronperceptronperceptron). 背景资料 最简单的神经网络的模型就是感知机分类器,它有不同的输入(x1, x2,......xn),然后有不同的权重值(w1, w2,......Wn),如下式计算: 每个对应的权重值与输入值进行相乘,再相加在一起,然后通

使用js编写一个简单的运动框架

下班后,,没事捣鼓捣鼓个人的小爱好. 首先,说明我的这个运动框架(css所有属性)也是常见的框架一种,健壮性并不是太好,对于新手学习倒是挺好,,若是大神,老司机请拐弯. 上来,我们先定义一个区块,然后在关联一个可以实时看到属性值发生变化值的标签. html: <body> <div id = "div1"> </div> <input type = "text" id = "txt1"> </

自定义一个简单的web框架

from wsgiref.simple_server import make_server def book(request):     #视图函数 return [b'<h1> book !!! </h1>']def web(request): return [b'<h1> web !!! </h1>'] def routers(): urlpatterns = ( ('/book',book),      #url 映射    ('/web',web),

【Java学习笔记】如何写一个简单的Web Service

本Guide利用Eclipse以及Ant建立一个简单的Web Service,以演示Web Service的基本开发过程: 1.系统条件: Eclipse Java EE IDE for Web Developers Java SE 6 Windows XP 2.基本环境搭建: 1)Java SE6 JDK的安装:下载Java SE6 JDK,双击,安装默认选项进行安装即可. 2)Eclipse的安装与配置: 安装时直接解压.     配置处有两点,Window>Preferences>Jav

简单的web框架(python)

1.web框架介绍 Web框架(Web framework)是一种开发框架,用来支持动态网站.网络应用和网络服务的开发.这大多数的web框架提供了一套开发和部署网站的方式,也为web行为提供了一套通用的方法.web框架已经实现了很多功能,开发人员使用框架提供的方法并且完成自己的业务逻辑,就能快速开发web应用了.浏览器和服务器的是基于HTTP协议进行通信的.也可以说web框架就是在以上十几行代码基础张扩展出来的,有很多简单方便使用的方法,大大提高了开发的效率. 2.实现简单的web框架 基于so