教学代码,我们做些简化,服务器地址总是固定,没有那么多复杂的参数,代码简化再简化。
首先我们实现一个最基本的架子,浏览器输入http://localhost:8080,网页输出Hello World。
创建一个子目录xweb,照着web.py的结构新建以下文件:
- application.py
- db.py
- debugerror.py
- form.py
- http.py
- httpserver.py
- net.py
- py3helpers.py
- session.py
- template.py
- test.py
- utils.py
- webapi.py
- wsgi.py
- __init__.py
httpserver.py
效率什么的我们不需要考虑,直接使用cheroot提供的WSGI服务器好了。
server = None
def run_simple(func, server_address=('0.0.0.0', 8080)):
global server
# No middleware to handle static resouce, do log...
server = WSGIServer(server_address, func)
try:
server.start()
except (KeyboardInterrupt, SystemExit):
server.stop()
server = None
def WSGIServer(server_address, wsgi_app):
from cheroot import wsgi
return wsgi.Server(server_address, wsgi_app, server_name='localhost')
这里没有考虑对静态资源的访问,放在后面慢慢实现。HTTPS访问也不考虑。只需要调用run_simple就可以启动服务。
wsgi.py
不考虑各种参数配置,什么FCGI,FastCGI,SCGI统统都不考虑。
from . import httpserver
def runwsgi(func):
return httpserver.run_simple(func)
application.py
路径映射不考虑,不管什么都只返回Hello World。wsgifunc返回处理函数供wsgi.runwsgi调用。
from . import wsgi
__all__ = ['application'] # Limit what'll be exported
class application:
def __init__(self, mapping={}):
pass
def wsgifunc(self, *middleware):
def wsgi(env, start_response):
result = b'Hello World' # Fix the return for demo
start_response('200 OK', ())
return [result]
# Ignore middleware now
return wsgi
def run(self, *middleware):
return wsgi.runwsgi(self.wsgifunc(*middleware))
好了,我们的基本架子就这么顺利的完成了。等等,其实还差一小步,__init__.py里还有些东西要填。
__init__.py
这个文件的作用是标识该目录是一个python的模块包。当用户代码执行import xweb时,会先执行xweb目录下的__init__.py文件。在这里我们先加简单的一行:
from .application import *
不然的话我们要使用application类在代码里就得先import xweb.application,然后app = application.application(...)。
Hello World
好了,现在我们写一个最最精简的Hello World的Hello World应用了。
import sys
sys.path.append('.')
import xweb
app = xweb.application()
if __name__ == '__main__':
app.run()
执行后在浏览器地址栏输入http://localhost:8080,看下页面返回什么。
可以直接下载本章源代码,解压后执行python demo.py。