Eurasia/快速开始
查看全部词条命名空间:Main
模板:Eurasia top 我们将从最简单的 hello world 开始,通过范例快速掌握 eurasia 。
这首先是一个 web 程序。
hello world
# 文件名: test.py
from eurasia.web import httpserver, mainloop
def handler(httpfile):
httpfile['Content-Type'] = 'text/html'
httpfile.write('<html>hello world!</html>')
httpfile.close()
httpd = httpserver(('', 8080), handler)
httpd.start()
mainloop()
把 handler 绑定到 8080 端口,浏览器访问该端口会得到 hello world 。
$/usr/bin/python2 test.py
- 一次可以通过 httpserver 创建多个 http 服务器
- 服务器通过 start() 启动 / 以 stop() 暂停
- 最后执行 mainloop() 主循环
httpfile对象
操作 httpfile 对象,获取请求,并完成响应。
request 操作:
response 操作:
下面将是一个完整的例子(文件服务器):
#-*- coding: utf-8 -*-
import os.path
from eurasia.web import httpserver, mainloop
def handler(httpfile):
# 注意,直接组合路径不安全
filename = '/var/www' + httpfile.path_info
if not os.path.exists(filename):
httpfile.status = 404 # 文件未找到
httpfile.write('<h1>Not Found</h1>')
return httpfile.close()
if os.path.isdir(filename):
httpfile.status = 403 # 不支持列出目录
httpfile.write('<h1>Forbidden</h1>')
return httpfile.close()
httpfile['Content-Type'] = 'application/octet-stream'
data = open(filename).read()
httpfile.write(data)
httpfile.close()
httpd = httpserver(('', 8080), handler)
httpd.start()
mainloop()
- 虽然 httpfile 形似 dict,但是读取接口仅用于读取 request,写入接口仅用于写入 response
- 这意味着从 httpfile[...] 获取的内容和写入 httpfile[...] 的内容并不一致
- httpfile.cookie 亦然
- 这里直接对路径进行相加是不安全的,用于演示
- 这里对磁盘文件的读取操作是低效的,应使用框架带有的文件 IO 接口
- 可以通过 httpfile.sockfile 得到原始 socket

