japronto精简教程

成玉

japronto是一个为微服务量身打造的python微框架,性能可以媲美golang、node。 其高性能的表现非常不俗,得益于核心模块使用c实现的。 用python每秒处理上百万次HTTP请求已成为现实。

下面是一个最简单web系统的示例
目录结构如下:
image.png

  • app.py
from japronto import Application  
import json

app = Application()

_PRE_PATH = '../static/'  
_INDEX = _PRE_PATH + "index.html"  
MAP_DB = dict()


def route(url, method='GET'):  
    def add_handler(handler):
        app.router.add_route(url, handler, method=method)
        return handler

    return add_handler


def format_json_response(request, data):  
    JOSN_TYPE = 'application/json'
    if isinstance(data, str):
        return request.Response(text=data, mime_type=JOSN_TYPE)
    elif isinstance(data, dict):
        return request.Response(json=data)
    raise Exception('Unknown JSON data format')


def main():  
    # 首页
    @route('/')
    def index(request):
        with open(_INDEX) as f:
            index_content = f.read()
        return request.Response(text=index_content, mime_type='text/html')

    # 静态文件
    @route('/static/{static_file}')
    async def get_static(request):
        path = request.match_dict['static_file'].strip('/')
        with open(_PRE_PATH + path) as html_file:
            return request.Response(text=html_file.read(), mime_type='text/html')

    # 测试json
    @route('/test-json')
    def index(request):
        return format_json_response(request, {"key": "value"})


if __name__ == '__main__':  
    main()
    app.run(debug=True, host="localhost")
  • index.html
<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="utf-8">
    <title>app</title>
</head>  
<body>  
<div id="app">hello world</div>  
</body>  
</html>  

启动之后浏览器访问 默认端口8080
image.png
image.png