Skip to content
On this page

注意:

  • 请使用 Python 3.8+ 版本进行开发
  • 除了特别需求外,一般情况下,LinuxMacWin 代码是一致的

本文列子


创建项目格式


python
├── helloworld       # APP 目录名
│   ├── app.json    # APP 配置文件
│   ├── icon.png    # APP 图标
│   ├── main       # APP 代码
|   |   └── run.py  # APP 入口文件
│   └── readme.md   # APP 说明文件

编写代码


python
#!/usr/bin/env python
# encoding:utf-8
from loguru import logger # 导入日记库,没有请先安装 pip install loguru

# 为了保证性能,使用了 async await 开启异步携程,Python 3.7+ 的特性
async def hello_world(name):
    # 输出日记,生产环境会输出到指定目录
    logger.info("[Hello World] 该 APP 执行参数为: {name}", name=name)
    # 返回值,格式为: 状态码,返回内容
    return {"status": 0, "result": "Hello," + name}

async , await 使用 Demo

python
#!/usr/bin/env python
# encoding:utf-8
from loguru import logger

async def hello_world(name):
    try:
        import requests
    except:
        logger.info("[Hello World] 导入 requests 模块失败, 请输入命令 pip install requests")
        return 2, "缺少 requests 模块"

    # 使用 await
    r = await requests.get(url="https://w5.io")
    print(r)

    logger.info("[Hello World] 该 APP 执行参数为: {name}", name=name)
    return {"status":0,"result":"Hello," + name,"html": '''<span style="color:red">{name}</span>'''.format(name="Hello," + name)}

APP 测试


使用 asyncio 运行测试,正式发布后请删除 main 入口函数

python
#!/usr/bin/env python
# encoding:utf-8
from loguru import logger  # 导入日记库,没有请先安装 pip install loguru


# 为了保证性能,使用了 async await 开启异步,Python 3.7+ 的特性
async def hello_world(name):
    # 输出日记,生产环境会输出到指定目录
    logger.info("[Hello World] 该 APP 执行参数为: {name}", name=name)
    # 返回值,格式为: 状态码,返回内容
    return {"status": 0, "result": "Hello," + name}


if __name__ == '__main__':
    # 导入异步库
    import asyncio


    # 测试函数
    async def test():
        result = await hello_world("W5")
        print(result)


    # 加入异步队列
    async def main(): await asyncio.gather(test())


    # 启动执行
    asyncio.run(main())

执行演示


dev_1