Skip to content

removed template fastapi users, moved main template to root cookiecut… #23

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

Merged
merged 3 commits into from
Feb 4, 2023
Merged
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
42 changes: 6 additions & 36 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,31 +26,28 @@ jobs:
with:
python-version: "3.10"

- name: Generate projects from templates using cookiecutter
# fastapi_users_project folder
# minimal_project folder
# Below will create fresh template in path: minimal_project
- name: Generate project from template using cookiecutter
run: |
pip install cookiecutter
python tests/create_minimal_project.py
python tests/create_fastapi_users_project.py

- name: Install Poetry
uses: snok/install-poetry@v1
with:
virtualenvs-create: true
virtualenvs-in-project: true

### template minimal ###

- name: Load cached venv-1
id: cached-poetry-dependencies-template-1
# run tests from folder minimal_project
- name: Load cached venv
id: cached-poetry-dependencies-template
uses: actions/cache@v2
with:
path: minimal_project/.venv
key: venv-${{ runner.os }}-${{ hashFiles('minimal_project/poetry.lock') }}

- name: Install template minimal dependencies
if: steps.cached-poetry-dependencies-template-1.outputs.cache-hit != 'true'
if: steps.cached-poetry-dependencies-template.outputs.cache-hit != 'true'
run: |
cd minimal_project
poetry install --no-interaction --no-root
Expand All @@ -66,30 +63,3 @@ jobs:
cd minimal_project
poetry run flake8 app --count --exit-zero --statistics
poetry run coverage run -m pytest

### template fastapi users ###

- name: Load cached venv-2
id: cached-poetry-dependencies-template-2
uses: actions/cache@v2
with:
path: fastapi_users_project/.venv
key: venv-${{ runner.os }}-${{ hashFiles('fastapi_users_project/poetry.lock') }}

- name: Install template fastapi users dependencies
if: steps.cached-poetry-dependencies-template-1.outputs.cache-hit != 'true'
run: |
cd fastapi_users_project
poetry install --no-interaction --no-root

- name: Run template fastapi users flake8 and then tests
env:
TEST_DATABASE_HOSTNAME: localhost
TEST_DATABASE_PASSWORD: postgres
TEST_DATABASE_PORT: 5432
TEST_DATABASE_USER: postgres
TEST_DATABASE_DB: postgres
run: |
cd fastapi_users_project
poetry run flake8 app --count --exit-zero --statistics
poetry run coverage run -m pytest
68 changes: 35 additions & 33 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,20 +54,18 @@ _Check out also online example: https://minimal-fastapi-postgres-template.rafsaf

## Quickstart


### 1. Install cookiecutter globally and cookiecutter this project

```bash
pip install cookiecutter

# And cookiecutter this project :)
cookiecutter https://github.com/rafsaf/minimal-fastapi-postgres-template

# if you want experimental fastapi-users template
# check "experimental_fastapi_users_template"
# to True in cookiecutter option
```

### 2. Install dependecies with poetry or without it

```bash
cd project_name
### Poetry install (python3.10)
Expand All @@ -78,24 +76,28 @@ python3.10 -m venv venv
source venv/bin/activate
pip install -r requirements-dev.txt
```

Note, be sure to use `python3.10` with this template with either poetry or standard venv & pip, if you need to stick to some earlier python version, you should adapt it yourself (remove python3.10+ specific syntax for example `str | int`)

### 3. Setup databases

```bash
### Setup two databases
docker-compose up -d

### Alembic migrations upgrade and initial_data.py script
bash init.sh
```

### 4. Now you can run app

```bash
### And this is it:
uvicorn app.main:app --reload

```
You should then use `git init` to initialize git repository and access OpenAPI spec at http://localhost:8000/ by default. To customize docs url, cors and allowed hosts settings, read section about it.

You should then use `git init` to initialize git repository and access OpenAPI spec at http://localhost:8000/ by default. To customize docs url, cors and allowed hosts settings, read section about it.

### Running tests

Expand Down Expand Up @@ -388,36 +390,36 @@ There are some **opinionated** default settings in `/app/main.py` for documentat

1. Docs

```python
app = FastAPI(
title=config.settings.PROJECT_NAME,
version=config.settings.VERSION,
description=config.settings.DESCRIPTION,
openapi_url="/openapi.json",
docs_url="/",
)
```
Docs page is simpy `/` (by default in FastAPI it is `/docs`). Title, version and description are taken directly from `config` and then directly from `pyproject.toml` file. You can change it completely for the project, remove or use environment variables `PROJECT_NAME`, `VERSION`, `DESCRIPTION`.

2. CORS

```python
app.add_middleware(
CORSMiddleware,
allow_origins=[str(origin) for origin in config.settings.BACKEND_CORS_ORIGINS],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
```
```python
app = FastAPI(
title=config.settings.PROJECT_NAME,
version=config.settings.VERSION,
description=config.settings.DESCRIPTION,
openapi_url="/openapi.json",
docs_url="/",
)
```

If you are not sure what are CORS for, follow https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS. React and most frontend frameworks nowadays operate on `localhost:3000` thats why it's included in `BACKEND_CORS_ORIGINS` in .env file, before going production be sure to include and frontend domain here, like `my-fontend-app.example.com`
Docs page is simpy `/` (by default in FastAPI it is `/docs`). Title, version and description are taken directly from `config` and then directly from `pyproject.toml` file. You can change it completely for the project, remove or use environment variables `PROJECT_NAME`, `VERSION`, `DESCRIPTION`.

3. Allowed Hosts
2. CORS

```python
app.add_middleware(TrustedHostMiddleware, allowed_hosts=config.settings.ALLOWED_HOSTS)
```
```python
app.add_middleware(
CORSMiddleware,
allow_origins=[str(origin) for origin in config.settings.BACKEND_CORS_ORIGINS],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
```

If you are not sure what are CORS for, follow https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS. React and most frontend frameworks nowadays operate on `localhost:3000` thats why it's included in `BACKEND_CORS_ORIGINS` in .env file, before going production be sure to include and frontend domain here, like `my-fontend-app.example.com`

3. Allowed Hosts

Prevents HTTP Host Headers attack, you shoud put here you server IP or (preferably) full domain under it's accessible like `example.com`. By default in .env there are two most popular records: `ALLOWED_HOSTS=["localhost", "127.0.0.1"]`
```python
app.add_middleware(TrustedHostMiddleware, allowed_hosts=config.settings.ALLOWED_HOSTS)
```

Prevents HTTP Host Headers attack, you shoud put here you server IP or (preferably) full domain under it's accessible like `example.com`. By default in .env there are two most popular records: `ALLOWED_HOSTS=["localhost", "127.0.0.1"]`
3 changes: 1 addition & 2 deletions cookiecutter.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
{
"project_name": "my_project_name",
"experimental_fastapi_users_template": false
"project_name": "my_project_name"
}
26 changes: 0 additions & 26 deletions hooks/post_gen_project.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,10 @@
"""
Copy template choosen from TEMPLATES to main folder.

Copy content from env template (autogenerated passwords etc)
to .env which is gitignored, then remove template env file as it is redundant.
"""
from pathlib import Path
from shutil import copytree, rmtree

PROJECT_NAME = "{{ cookiecutter.project_name }}"
USE_FASTAPI_USERS = "{{ cookiecutter.experimental_fastapi_users_template }}"
TEMPLATES = ["template_fastapi_users", "template_minimal"]


def copy_choosen_template_to_main_dir(used_template: str):
if used_template not in TEMPLATES:
raise ValueError(f"{used_template} not in {TEMPLATES}")

copytree(used_template, "./", dirs_exist_ok=True)

for template in TEMPLATES:
rmtree(Path(template))


def create_env_file_and_remove_env_template():
env_template_file = Path(".env.template")
Expand All @@ -31,14 +15,4 @@ def create_env_file_and_remove_env_template():


if __name__ == "__main__":
truthy = ["T", "t", "true", "True", 1]
falsy = ["F", "f", "false", "False", 0]
if USE_FASTAPI_USERS in truthy:
used_template = "template_fastapi_users"
elif USE_FASTAPI_USERS in falsy:
used_template = "template_minimal"
else:
raise ValueError(f"'experimental_fastapi_users_template' param must be in {truthy + falsy}")

copy_choosen_template_to_main_dir(used_template=used_template)
create_env_file_and_remove_env_template()
24 changes: 0 additions & 24 deletions tests/create_fastapi_users_project.py

This file was deleted.

1 change: 0 additions & 1 deletion tests/create_minimal_project.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ def main():
no_input=True,
extra_context={
"project_name": "minimal_project",
"experimental_fastapi_users_template": False,
},
)

Expand Down
19 changes: 0 additions & 19 deletions {{cookiecutter.project_name}}/template_fastapi_users/.env.example

This file was deleted.

19 changes: 0 additions & 19 deletions {{cookiecutter.project_name}}/template_fastapi_users/.env.template

This file was deleted.

29 changes: 0 additions & 29 deletions {{cookiecutter.project_name}}/template_fastapi_users/Dockerfile

This file was deleted.

Loading