轻量级配置以在纯Python中生成网页
我刚接触Python,想用它来制作网页(但不想用任何网页框架或模板模块)。请问最低需要什么?能给我推荐一个简单的设置吗?
谢谢!
补充说明:我并不是想要极简主义。我想要的是一个简单、常见的解决方案,尽量贴近Python语言本身(而不是强制使用某种设计模式,比如MVC)。
4 个回答
这是一个干净的WSGI应用,不需要复杂的框架:
from wsgiref.simple_server import make_server
def application(environ, start_response):
# Sorting and stringifying the environment key, value pairs
response_body = ['%s: %s' % (key, value)
for key, value in sorted(environ.items())]
response_body = '\n'.join(response_body)
status = '200 OK'
response_headers = [('Content-Type', 'text/plain'),
('Content-Length', str(len(response_body)))]
start_response(status, response_headers)
return [response_body]
# Instantiate the WSGI server.
# It will receive the request, pass it to the application
# and send the application's response to the client
httpd = make_server(
'localhost', # The host name.
8051, # A port number where to wait for the request.
application # Our application object name, in this case a function.
)
# Wait for a single request, serve it and quit.
httpd.handle_request()
然后你可以使用nginx:http://wiki.nginx.org/NgxWSGIModule
这是最稳定、安全且简单的设置。
更多示例可以在这里找到:https://bitbucket.org/lifeeth/mod_wsgi/src/6975f0ec7eeb/examples/。
这是学习的最佳方式(正如你所问的)。我已经走过这条路了。
我觉得使用一个轻量级的框架是个不错的选择。
首先,网页应用会让你的服务器面临安全风险,所以用一个有比较多开发者维护的框架是好的(更多的人关注,就能更快修复漏洞)。
如果你想要“贴近语言本身”,你需要一些抽象层来以一种Pythonic的方式管理HTTP。Python就是强调高层次的东西[自带功能]。
有些框架的语法、语义和风格都和Python非常接近。比如可以看看webpy。我觉得这句话很好地表达了webpy背后的理念:
“Django让你用Django写网页应用。TurboGears让你用TurboGears写网页应用。Web.py让你用Python写网页应用。” -- Adam Atlas
另一个在简洁性和使用“常规”Python方面也不错的选择是cherrypy。他们网站上说:
CherryPy允许开发者以构建其他面向对象的Python程序的方式来构建网页应用。[...] 你的CherryPy驱动的网页应用实际上是独立的Python应用,内嵌了自己的多线程网页服务器。你可以在任何可以运行Python应用的地方部署它们。