xweb: 一款无依赖的 Python web 框架(低于 500 行代码)

2017-03-07 18:13:58 +08:00
 prasanta

我用极少的代码了实现一款 web 框架,目标是用低于 1000 行的代码实现 flask 的核心功能, xweb 框架基于 python3.5 以上开发,实在是居家旅行良品.

github 地址:https://github.com/gaojiuli/xweb

我的目标是用最少的代码实现符合现状的 web 框架,欢迎同样有兴趣的同学一起参与进来

说明

基于3.5开发

安装

pip install xweb

基本用法

from xweb.application import XWeb

app = XWeb()


@app.route('/:name/')
def call_my_name(name):
    return 'hi {}!'.format(name)


app.listen(3000)

请求与相应

from xweb.globals import request

request.path
request.query_string
request.query
request.files
request.forms
request.json
request.ip
request.hostname
request.headers



from xweb.globals import response

response.headers
response.status
response.body

中间件

from xweb.application import XWeb

app = XWeb()

@app.middleware('request')
def print_on_request1():
    print("I print when a request is received by the server1")


@app.middleware('request')
def print_on_request2():
    print("I print when a request is received by the server2")


@app.middleware('response')
def print_on_response1():
    print("I print when a response is returned by the server1")


@app.middleware('response')
def print_on_response2():
    print("I print when a response is returned by the server2")

@app.route('/:name/')
def call_my_name(name):
    return 'hi {}!'.format(name)


app.listen(3000)

我的目标是用最少的代码实现符合现状的 web 框架,欢迎同样有兴趣的同学一起参与进来

github 地址:https://github.com/gaojiuli/xweb

4930 次点击
所在节点    Python
28 条回复
Kilerd
2017-03-08 00:06:05 +08:00
@aljun 我在写的 web 框架也是这样搭建测试 HTTP 的,(基本所有 python web 框架都是使用 wsgiref 的 make_server 来本地测试的)

他这种写法并没有问题。 是要是对象里面有 __call__ 函数 满足 wsgi 就可以了。
wellsc
2017-03-08 00:16:32 +08:00
闲着没事的话可以给 bottle 增加 asyncIo 支持,就像 sanic 对 Flask 做的一样。
prasanta
2017-03-08 09:20:42 +08:00
@wellsc 我可不乐意写那些兼容 python2 的代码
huanglongtiankon
2017-03-08 09:22:52 +08:00
简单易懂,学习下,看看有没有机会做点贡献
wuxqing
2017-03-08 09:44:17 +08:00
建议去完善 sanic ,而不是再造一个轮子
prasanta
2017-03-08 09:48:50 +08:00
@wuxqing sanic 使用 uvloop ,造成了无法使用像 flask 中的全局变量 request,response,g 等,并且它依赖于 aiofiles , httptools , ujson , uvloop 这几个库,如果这几个库更新,那么 sanic 不得不被牵着鼻子走. 我想实现的是无第三方依赖,并且摒弃 python2 .
wellsc
2017-03-08 09:53:42 +08:00
@prasanta bottle 本来就是兼容 Python2 和 3 的,但是 bottle 现在不支持 asyncio 。
prasanta
2017-03-08 17:58:28 +08:00
@wellsc 我的意思是既然开发基于 python3, 那么所有为了 Python2 而生的代码都是多余的.

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/345653

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX