Skip to content

Commit

Permalink
🚀🥳
Browse files Browse the repository at this point in the history
  • Loading branch information
arthurio committed May 17, 2022
0 parents commit 3cc7818
Show file tree
Hide file tree
Showing 42 changed files with 3,404 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .bandit
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[bandit]
targets: fastapi_filter,tests,examples
skips: B101
8 changes: 8 additions & 0 deletions .flake8
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[flake8]
max_line_length = 120
extend-ignore =
A003
D1
E203
docstring-convention = google
max-complexity = 15
13 changes: 13 additions & 0 deletions .github/FUNDING.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# These are supported funding model platforms

github: [python, tiangolo, encode, sqlalchemy]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
8 changes: 8 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
version: 2
updates:
- package-ecosystem: pip
directory: "/"
schedule:
interval: daily
time: "00:00"
open-pull-requests-limit: 10
44 changes: 44 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
name: Test

on:
pull_request:
types:
- "opened"
- "synchronize"
push:
branches:
- "main"

jobs:
test:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: [ "3.10" ]

steps:
- uses: actions/checkout@v2

- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}

- name: Set up MongoDB
uses: supercharge/[email protected]

- name: Install dependencies
run: |
pip install -U poetry
poetry install -E all
- name: Unit tests
run: poetry run pytest tests --cov-report=xml

- name: Upload coverage to Codecov
uses: codecov/codecov-action@v2
with:
fail_ci_if_error: true
file: ./coverage.xml
verbose: true
8 changes: 8 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
*.sqlite-journal
.DS_Store
.coverage
.pypirc
coverage.xml
dist/
fastapi_filter.sqlite
poetry.toml
44 changes: 44 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
repos:
- repo: local
hooks:
- id: isort
name: "isort"
entry: isort
types: [python]
language: system
- id: flynt
name: "flynt"
entry: flynt
args: [--fail-on-change]
types: [python]
language: system
- id: black
name: "black"
entry: black
language: system
types: [python]
- id: flake8
name: "flake8"
entry: flake8
args: ["--config", ".flake8"]
types: [python]
language: system
- id: bandit
name: "bandit"
entry: bandit
language: system
types: [python]
args: [--ini, .bandit]
- id: mypy
name: "mypy"
entry: mypy
args: ["--config-file", "pyproject.toml"]
types: [python]
language: system

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.2.0
hooks:
- id: end-of-file-fixer
exclude: .*(min.js|min.css|html|svg|css.map|js.map)
- id: trailing-whitespace
1 change: 1 addition & 0 deletions .python-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.10.4/envs/fastapi-filter
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 Yurii Karabas

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[![codecov](https://codecov.io/gh/arthurio/fastapi-filter/branch/main/graph/badge.svg?token=I1DVBL1682)](https://codecov.io/gh/arthurio/fastapi-filter)
[![Netlify Status](https://api.netlify.com/api/v1/badges/83451c4f-76dd-4154-9b2d-61f654eb0704/deploy-status)](https://app.netlify.com/sites/soft-sherbet-1c5dfd/deploys)

# FastAPI filter

## Example

![Swagger UI](https://raw.githubusercontent.com/arthurio/fastapi-filter/main/docs/swagger-ui.png)
13 changes: 13 additions & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Welcome to FastAPI filter

## Why?

Add querystring filters to your api endpoints and show them in the swagger UI.

## Example

![Swagger UI](./swagger-ui.png)

## Filter

## Order by
Binary file added docs/swagger-ui.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 4 additions & 0 deletions docs_requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
mkdocs
mkdocs-material
pymdown-extensions
fontawesome-markdown
Empty file added examples/__init__.py
Empty file.
115 changes: 115 additions & 0 deletions examples/fastapi_filter_mongoengine.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
from typing import Any, Dict, Generator

import uvicorn
from bson.objectid import ObjectId
from faker import Faker
from fastapi import FastAPI
from mongoengine import Document, connect, fields
from pydantic import BaseModel, Field

from fastapi_filter import FilterDepends, nested_filter
from fastapi_filter.contrib.mongoengine import Filter

fake = Faker()


class PydanticObjectId(ObjectId):
@classmethod
def __get_validators__(cls) -> Generator:
yield cls.validate

@classmethod
def validate(cls, v: ObjectId) -> str:
if not ObjectId.is_valid(v):
raise ValueError("Invalid objectid")
return str(v)

@classmethod
def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
field_schema.update(type="string")


class Address(Document):
street = fields.StringField()
city = fields.StringField()
country = fields.StringField()


class User(Document):
name = fields.StringField()
email = fields.EmailField()
age = fields.IntField()
address = fields.ReferenceField(Address)


class AddressOut(BaseModel):
id: PydanticObjectId = Field(..., alias="_id")
street: str
city: str
country: str

class Config:
orm_mode = True


class UserIn(BaseModel):
name: str
email: str
age: int


class UserOut(UserIn):
id: PydanticObjectId = Field(..., alias="_id")
address: AddressOut | None

class Config:
orm_mode = True


class AddressFilter(Filter):
street: str | None
country: str | None
city: str | None = "Nantes"
city__in: list[str] | None

class Constants:
collection = Address


class UserFilter(Filter):
name: str | None
address: AddressFilter | None = FilterDepends(nested_filter("address", AddressFilter))
age__lt: int | None
age__gte: int # <-- NOTE(arthurio): This filter required

class Constants:
collection = User


app = FastAPI()


@app.on_event("startup")
async def on_startup() -> None:
connect(host="mongodb://localhost:27017/fastapi_filter")
for _ in range(100):
address = Address(street=fake.street_address(), city=fake.city(), country=fake.country())
address.save()
user = User(name=fake.name(), email=fake.email(), age=fake.random_int(min=5, max=120), address=address)
user.save()


@app.on_event("shutdown")
async def on_shutdown() -> None:
Address.drop_collection()
User.drop_collection()


@app.get("/users", response_model=list[UserOut])
async def get_users(user_filter: UserFilter = FilterDepends(UserFilter)) -> Any:
query = user_filter.filter(User.objects()).select_related()
return [user.to_mongo() | {"address": user.address.to_mongo()} for user in query]


if __name__ == "__main__":
uvicorn.run("fastapi_filter_mongoengine:app", reload=True)
Loading

0 comments on commit 3cc7818

Please sign in to comment.