Piccolo API 项目教程
1. 项目的目录结构及介绍
piccolo_api/
├── docs/
│ ├── conf.py
│ ├── index.rst
│ └── ...
├── example_projects/
│ ├── example_project/
│ │ ├── app.py
│ │ ├── config.py
│ │ └── ...
│ └── ...
├── piccolo_api/
│ ├── __init__.py
│ ├── middleware/
│ │ ├── __init__.py
│ │ ├── auth.py
│ │ └── ...
│ ├── endpoints/
│ │ ├── __init__.py
│ │ ├── rest.py
│ │ └── ...
│ └── ...
├── requirements/
│ ├── base.txt
│ ├── dev.txt
│ └── ...
├── scripts/
│ ├── setup.sh
│ └── ...
├── tests/
│ ├── __init__.py
│ ├── test_auth.py
│ └── ...
├── .flake8
├── .gitignore
├── .readthedocs.yaml
├── CHANGES.rst
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── pyproject.toml
└── setup.py
目录结构介绍
- docs/: 存放项目的文档文件,包括Sphinx配置文件和文档源文件。
- example_projects/: 包含示例项目的目录,每个示例项目都有自己的配置和启动文件。
- piccolo_api/: 核心代码目录,包含中间件、端点和其他功能模块。
- requirements/: 存放项目的依赖文件,包括基础依赖和开发依赖。
- scripts/: 存放项目的脚本文件,如设置脚本等。
- tests/: 存放项目的测试文件,包括单元测试和集成测试。
- .flake8: Flake8配置文件,用于代码风格检查。
- .gitignore: Git忽略文件配置。
- .readthedocs.yaml: Read the Docs配置文件。
- CHANGES.rst: 项目变更日志。
- CONTRIBUTING.md: 贡献指南。
- LICENSE: 项目许可证文件。
- README.md: 项目介绍和使用说明。
- pyproject.toml: 项目配置文件,包含构建系统和依赖信息。
- setup.py: 项目安装脚本。
2. 项目的启动文件介绍
在 example_projects/example_project/
目录下,有一个典型的启动文件 app.py
,其内容如下:
from piccolo_api.endpoints import Rest
from piccolo.engine import engine_finder
from piccolo.apps.migrations.auto import MigrationManager
# 初始化数据库引擎
engine = engine_finder()
# 创建迁移管理器
migration_manager = MigrationManager()
# 定义REST端点
rest_endpoint = Rest(table_class=YourTableClass)
# 启动应用
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)
启动文件介绍
- 导入模块: 导入必要的模块,包括
Rest
端点、数据库引擎和迁移管理器。 - 初始化数据库引擎: 使用
engine_finder
初始化数据库引擎。 - 创建迁移管理器: 创建
MigrationManager
实例,用于管理数据库迁移。 - 定义REST端点: 使用
Rest
类定义一个REST端点,绑定到指定的表类。 - 启动应用: 使用
uvicorn
启动ASGI应用,监听本地8000端口。
3. 项目的配置文件介绍
在 example_projects/example_project/
目录下,有一个典型的配置文件 config.py
,其内容如下:
from piccolo.conf.apps import AppRegistry
from piccolo.engine.postgres import PostgresEngine
# 数据库配置
DB = PostgresEngine(
config={
"database": "your_database",
"user": "your_user",
"password": "your_password",
"host": "localhost",
"port": 5432,
}
)
# 应用注册表
APP_REGISTRY = AppRegistry(
apps=["piccolo_api.piccolo_app", "your_app.piccolo_app"]
)
配置文件介绍
- 数据库配置: 使用
PostgresEngine
配置数据库连接信息,包括数据库名称、用户名、密码、主机和端口。 - 应用注册表: 使用
AppRegistry
注册应用,指定应用的模块路径。
通过以上配置,项目可以连接到指定的数据库,并加载相应的应用模块。