Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add beanie support #185

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,12 @@ site
__pycache__/
.pytest_cache/
.examples/

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
4 changes: 2 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ First, add the pre-commit command to your git's pre-commit hooks. This will ensu
code

```shell
pre-commit install
hatch run pre-commit install
```

To make the pull request reviewing easier and keep the version tree clean your pull request should consist of a single
Expand All @@ -198,7 +198,7 @@ documentation, but more human friendly documentation might also be needed.
The documentation is generated using [mkdocs](https://www.mkdocs.org/). To see a preview of any edits you make you can run:

```shell
hatch run docs
hatch run docs:serve
```
and visit the printed address (usually localhost:8080) in your browser

Expand Down
24 changes: 24 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# docker build -t starlette-admin-image .
# docker run --name starlette-admin-container starlette-admin-image
# docker rm starlette-admin-container
# docker rmi starlette-admin-image

FROM python:3.7

COPY . /app/starlette-admin
WORKDIR /app/starlette-admin

# install git
RUN apt-get update && \
apt-get install -y --no-install-recommends git

# install hatch
RUN pip install hatch

# clone app, branch 'beanie-support'
# RUN git clone -b beanie-support https://github.com/opaniagu/starlette-admin.git

WORKDIR /app/starlette-admin

# run test
CMD ["hatch", "-e", "test", "run", "-m", "pytest", "-v", "tests/beanie"]
26 changes: 26 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# docker-compose up
# docker-compose down

services:
app:
build: .
container_name: python-test
volumes:
- .:/app/starlette-admin
environment:
- MONGO_URI=mongodb://mongodb:27017
depends_on:
- mongodb
networks:
- node-network

mongodb:
image: mongo:latest
ports:
- '27017:27017'
networks:
- node-network

networks:
node-network:
driver: bridge
78 changes: 78 additions & 0 deletions docs/tutorial/getting-started/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,22 @@ The first step is to initialize an empty admin interface for your app:
engine = AIOEngine()

admin = Admin(engine)
``

=== "beanie"
```python
from motor.motor_asyncio import AsyncIOMotorClient
from starlette_admin.contrib.beanie import Admin

import mongoengine
from gridfs import GridFS

client = AsyncIOMotorClient()

db = mongoengine.connect(db='demo', alias='demo')
fs = GridFS(database=db['demo'], collection='fs_files')

admin = Admin(fs=fs)
```

## Adding Views
Expand Down Expand Up @@ -101,6 +117,29 @@ Model views allow you to add a dedicated set of admin pages for managing any mod
admin.add_view(ModelView(Post))

```

=== "beanie"
```python hl_lines="2 16"
from motor.motor_asyncio import AsyncIOMotorClient
from starlette_admin.contrib.beanie import Admin, ModelView

import mongoengine
from gridfs import GridFS

from .models import Author

client = AsyncIOMotorClient()

db = mongoengine.connect(db='demo', alias='demo')
fs = GridFS(database=db['demo'], collection='fs_files')

admin = Admin(fs=fs)

admin.add_view(ModelView(Author))

```


This gives you a set of fully featured CRUD views for your model:

- A *list view*, with support for searching, sorting, filtering, and deleting records.
Expand Down Expand Up @@ -255,4 +294,43 @@ The last step is to mount the admin interfaces to your app
admin.mount_to(app)
```

=== "beanie"
```python hl_lines="2 24 26"
from motor.motor_asyncio import AsyncIOMotorClient
from starlette.applications import Starlette
from starlette_admin.contrib.beanie import Admin, ModelView

import mongoengine
from gridfs import GridFS

from beanie import init_beanie

from .models import Author

client = AsyncIOMotorClient()

db = mongoengine.connect(db='demo', alias='demo')
fs = GridFS(database=db['demo'], collection='fs_files')

async def init() -> None:
# init beanie
await init_beanie(database=client['demo'], document_models=[Author]) # type: ignore

# starlette-admin
admin = Admin(fs=fs)
admin.add_view(ModelView(Author))
admin.mount_to(app)

app = Starlette() # FastAPI()

@app.on_event("startup")
async def on_startup() -> None:
"""Initialize services on startup."""
await init()



```


You can now access your admin interfaces in your browser at [http://localhost:8000/admin](http://localhost:8000/admin)
44 changes: 44 additions & 0 deletions examples/beanie_basic/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
beanie document integration examples.

To run this example:

1. Clone the repository::

```shell
git clone https://github.com/jowilf/starlette-admin.git
cd starlette-admin
```

2. Create and activate a virtual environment:

* Linux:

```shell
python3 -m venv .venv
source env/bin/activate
```

* Windows

```shell
python -m venv .venv
.venv\Scripts\activate
```

3. Install requirements

```shell
pip install -r examples/beanie_basic/requirements.txt
```

4. Start mongo

```shell
docker run -d -p 27017:27017 --name test-mongo mongo:latest
```

5. Run the application:

```shell
uvicorn examples.beanie_basic.app_fastapi:app --reload
```
Empty file.
59 changes: 59 additions & 0 deletions examples/beanie_basic/app_fastapi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
from devtools import debug # noqa

from starlette.responses import RedirectResponse
from fastapi import FastAPI

import mongoengine
from motor.motor_asyncio import AsyncIOMotorClient
from gridfs import GridFS
from beanie import init_beanie

from starlette_admin.contrib.beanie import Admin

from .config import CONFIG
from .models import User, Author, BeanieView


# used by beanie
client = AsyncIOMotorClient(CONFIG.mongo_uri)

# used by gridfs
db = mongoengine.connect(
db=CONFIG.mongo_db, host=CONFIG.mongo_uri, alias=CONFIG.mongo_db
)
fs = GridFS(database=db[CONFIG.mongo_db], collection=CONFIG.mongo_col_gridfs)


async def init() -> None:
# init beanie
await init_beanie(
database=client[CONFIG.mongo_db],
document_models=[User, Author],
) # type: ignore

# Add admin
admin = Admin(
title="Example: beanie basic",
fs=fs,
debug=True,
)

# Add views
admin.add_view(BeanieView(User, icon="fa fa-users"))
admin.add_view(BeanieView(Author, icon="fa fa-users"))

admin.mount_to(app)


app = FastAPI()


@app.on_event("startup")
async def on_startup() -> None:
"""Initialize services on startup."""
await init()


@app.get("/")
async def index():
return RedirectResponse(url="/admin", status_code=302)
17 changes: 17 additions & 0 deletions examples/beanie_basic/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import os

from pydantic import BaseSettings


class Settings(BaseSettings):
mongo_uri: str = "mongodb://localhost:27017"
mongo_db: str = "starlette_admin_beanie"
mongo_col_gridfs: str = "fs_files"
upload_dir: str = "upload/"

class Config:
env_file = os.path.join(os.getcwd(), ".env")
env_file_encoding = "utf-8"


CONFIG = Settings() # type: ignore
47 changes: 47 additions & 0 deletions examples/beanie_basic/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from enum import Enum
from typing import Optional

from beanie import Document
from pydantic import BaseModel, EmailStr, Field
from starlette_admin.contrib.beanie import ModelView
from starlette_admin.contrib.beanie._file import Image
from starlette_admin.contrib.beanie._password import Password


class Country(str, Enum):
Argentina = "Argentina"
USA = "USA"


class Address(BaseModel):
Street: str = Field(..., max_length=10, description="Street Name")
Number: int
Floor: int
Apartment: Optional[str]
PostalCode: Optional[str]
Country: Country


class Author(Document):
first_name: str = Field(..., max_length=10, description="Your first name")
last_name: str
age: int
weight: float
active: bool
avatar: Optional[Image]
address: Address

class Settings:
use_revision = False


class User(Document):
email: EmailStr
password: Password


class BeanieView(ModelView):
exclude_fields_from_list = ["id", "revision_id"]
exclude_fields_from_detail = ["id", "revision_id"]
exclude_fields_from_create = ["id", "revision_id", "created_at", "updated_at"]
exclude_fields_from_edit = ["id", "revision_id", "created_at", "updated_at"]
17 changes: 17 additions & 0 deletions examples/beanie_basic/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# starlette-admin # using local version (dev)
# pip install C:\Users\opani\Documents\git\contrib\starlette-admin\dist\starlette_admin-0.8.1.tar.gz
beanie
devtools
pydantic
python-slugify
python-decouple # there's no need
mongoengine
pymongo
uvicorn
fastapi
# using by starlette-admin
itsdangerous
# using by beanie-support for starlette-admin
pillow
pydantic[email] # email validator
phonenumbers # phone validator
Loading