|
| 1 | + |
| 2 | + |
| 3 | +`TiFeatures` and [`TiMVT`](https://github.com/developmentseed/timvt) share a lot of in common and it's possible to create a unique FastAPI application with both **Features** and **MVT** endpoints: |
| 4 | + |
| 5 | +```python |
| 6 | +"""Features and MVT app.""" |
| 7 | + |
| 8 | +from tifeatures.db import close_db_connection, connect_to_db, register_table_catalog |
| 9 | +from tifeatures.factory import Endpoints |
| 10 | +from timvt.factory import VectorTilerFactory |
| 11 | +from fastapi import FastAPI |
| 12 | +from starlette_cramjam.middleware import CompressionMiddleware |
| 13 | + |
| 14 | +app = FastAPI( |
| 15 | + title="Features and MVT", |
| 16 | + openapi_url="/api", |
| 17 | + docs_url="/api.html", |
| 18 | +) |
| 19 | + |
| 20 | +# Register endpoints. |
| 21 | +endpoints = Endpoints() |
| 22 | +app.include_router(endpoints.router, tags=["Features"]) |
| 23 | + |
| 24 | +# By default the VectorTilerFactory will only create tiles/ and tilejson.json endpoints |
| 25 | +mvt_endpoints = VectorTilerFactory() |
| 26 | +app.include_router(mvt_endpoints.router) |
| 27 | + |
| 28 | +app.add_middleware(CompressionMiddleware) |
| 29 | + |
| 30 | + |
| 31 | +@app.on_event("startup") |
| 32 | +async def startup_event() -> None: |
| 33 | + """Connect to database on startup.""" |
| 34 | + await connect_to_db(app) |
| 35 | + # TiMVT and TiFeatures share the same `Table_catalog` format |
| 36 | + # see https://github.com/developmentseed/timvt/pull/83 |
| 37 | + await register_table_catalog(app) |
| 38 | + |
| 39 | + |
| 40 | +@app.on_event("shutdown") |
| 41 | +async def shutdown_event() -> None: |
| 42 | + """Close database connection.""" |
| 43 | + await close_db_connection(app) |
| 44 | +``` |
| 45 | + |
| 46 | +!!! Note |
| 47 | + To run the example, copy the code to a file main.py, and start uvicorn with: |
| 48 | + |
| 49 | + `uvicorn main:app --reload` |
| 50 | + |
| 51 | + |
| 52 | + |
0 commit comments