GithubHelp home page GithubHelp logo

rochacbruno / fastapi-project-template Goto Github PK

View Code? Open in Web Editor NEW
362.0 7.0 34.0 266 KB

DO NOT FORK, CLICK "Use this template" - The base to start an openapi project featuring: SQLModel, Typer, FastAPI, JWT Token Auth, Interactive Shell, Management Commands.

License: The Unlicense

Shell 1.25% Makefile 12.24% Python 86.33% Dockerfile 0.18%
template fastapi project-template python-template python-project-template api-template rochacbruno-template hacktoberfest

fastapi-project-template's Introduction

FastAPI Project Template

The base to start an openapi project featuring: SQLModel, Typer, FastAPI, JWT Token Auth, Interactive Shell, Management Commands.

See also

HOW TO USE THIS TEMPLATE

DO NOT FORK this is meant to be used from Use this template feature.

  1. Click on Use this template
  2. Give a name to your project
    (e.g. my_awesome_project recommendation is to use all lowercase and underscores separation for repo names.)
  3. Wait until the first run of CI finishes
    (Github Actions will process the template and commit to your new repo)
  4. If you want codecov Reports and Automatic Release to PyPI
    On the new repository settings->secrets add your PIPY_API_TOKEN and CODECOV_TOKEN (get the tokens on respective websites)
  5. Read the file CONTRIBUTING.md
  6. Then clone your new project and happy coding!

NOTE: WAIT until first CI run on github actions before cloning your new project.

What is included on this template?

  • ๐Ÿ–ผ๏ธ The base to start an openapi project featuring: SQLModel, Typer, FastAPI, VueJS.
  • ๐Ÿ“ฆ A basic setup.py file to provide installation, packaging and distribution for your project.
    Template uses setuptools because it's the de-facto standard for Python packages, you can run make switch-to-poetry later if you want.
  • ๐Ÿค– A Makefile with the most useful commands to install, test, lint, format and release your project.
  • ๐Ÿ“ƒ Documentation structure using mkdocs
  • ๐Ÿ’ฌ Auto generation of change log using gitchangelog to keep a HISTORY.md file automatically based on your commit history on every release.
  • ๐Ÿ‹ A simple Containerfile to build a container image for your project.
    Containerfile is a more open standard for building container images than Dockerfile, you can use buildah or docker with this file.
  • ๐Ÿงช Testing structure using pytest
  • โœ… Code linting using flake8
  • ๐Ÿ“Š Code coverage reports using codecov
  • ๐Ÿ›ณ๏ธ Automatic release to PyPI using twine and github actions.
  • ๐ŸŽฏ Entry points to execute your program using python -m <project_name> or $ project_name with basic CLI argument parsing.
  • ๐Ÿ”„ Continuous integration using Github Actions with jobs to lint, test and release your project on Linux, Mac and Windows environments.

Curious about architectural decisions on this template? read ABOUT_THIS_TEMPLATE.md
If you want to contribute to this template please open an issue or fork and send a PULL REQUEST.

โค๏ธ Sponsor this project


project_name

codecov CI

project_description

Install

from source

git clone https://github.com/author_name/project_urlname project_name
cd project_name
make install

from pypi

pip install project_name

Executing

$ project_name run --port 8080

or

python -m project_name run --port 8080

or

$ uvicorn project_name:app

CLI

โฏ project_name --help
Usage: project_name [OPTIONS] COMMAND [ARGS]...

Options:
  --install-completion [bash|zsh|fish|powershell|pwsh]
                                  Install completion for the specified shell.
  --show-completion [bash|zsh|fish|powershell|pwsh]
                                  Show completion for the specified shell, to
                                  copy it or customize the installation.
  --help                          Show this message and exit.

Commands:
  create-user  Create user
  run          Run the API server.
  shell        Opens an interactive shell with objects auto imported

Creating a user

โฏ project_name create-user --help
Usage: project_name create-user [OPTIONS] USERNAME PASSWORD

  Create user

Arguments:
  USERNAME  [required]
  PASSWORD  [required]

Options:
  --superuser / --no-superuser  [default: no-superuser]
  --help 

IMPORTANT To create an admin user on the first run:

project_name create-user admin admin --superuser

The Shell

You can enter an interactive shell with all the objects imported.

โฏ project_name shell       
Auto imports: ['app', 'settings', 'User', 'engine', 'cli', 'create_user', 'select', 'session', 'Content']

In [1]: session.query(Content).all()
Out[1]: [Content(text='string', title='string', created_time='2021-09-14T19:25:00.050441', user_id=1, slug='string', id=1, published=False, tags='string')]

In [2]: user = session.get(User, 1)

In [3]: user.contents
Out[3]: [Content(text='string', title='string', created_time='2021-09-14T19:25:00.050441', user_id=1, slug='string', id=1, published=False, tags='string')]

API

Run with project_name run and access http://127.0.0.1:8000/docs

For some api calls you must authenticate using the user created with project_name create-user.

Testing

โฏ make test
Black All done! โœจ ๐Ÿฐ โœจ
13 files would be left unchanged.
Isort All done! โœจ ๐Ÿฐ โœจ
6 files would be left unchanged.
Success: no issues found in 13 source files
================================ test session starts ===========================
platform linux -- Python 3.9.6, pytest-6.2.5, py-1.10.0, pluggy-1.0.0 -- 
/fastapi-project-template/.venv/bin/python3
cachedir: .pytest_cache
rootdir: /fastapi-project-template
plugins: cov-2.12.1
collected 10 items                                                                                                                               

tests/test_app.py::test_using_testing_db PASSED                           [ 10%]
tests/test_app.py::test_index PASSED                                      [ 20%]
tests/test_cli.py::test_help PASSED                                       [ 30%]
tests/test_cli.py::test_cmds_help[run-args0---port] PASSED                [ 40%]
tests/test_cli.py::test_cmds_help[create-user-args1-create-user] PASSED   [ 50%]
tests/test_cli.py::test_cmds[create-user-args0-created admin2 user] PASSED[ 60%]
tests/test_content_api.py::test_content_create PASSED                     [ 70%]
tests/test_content_api.py::test_content_list PASSED                       [ 80%]
tests/test_user_api.py::test_user_list PASSED                             [ 90%]
tests/test_user_api.py::test_user_create PASSED                           [100%]

----------- coverage: platform linux, python 3.9.6-final-0 -----------
Name                              Stmts   Miss  Cover
-----------------------------------------------------
project_name/__init__.py              4      0   100%
project_name/app.py                  16      1    94%
project_name/cli.py                  21      0   100%
project_name/config.py                5      0   100%
project_name/db.py                   10      0   100%
project_name/models/__init__.py       0      0   100%
project_name/models/content.py       47      1    98%
project_name/routes/__init__.py      11      0   100%
project_name/routes/content.py       52     25    52%
project_name/routes/security.py      15      1    93%
project_name/routes/user.py          52     26    50%
project_name/security.py            103     12    88%
-----------------------------------------------------
TOTAL                               336     66    80%


========================== 10 passed in 2.34s ==================================

Linting and Formatting

make lint  # checks for linting errors
make fmt   # formats the code

Configuration

This project uses Dynaconf to manage configuration.

from project_name.config import settings

Acessing variables

settings.get("SECRET_KEY", default="sdnfjbnfsdf")
settings["SECRET_KEY"]
settings.SECRET_KEY
settings.db.uri
settings["db"]["uri"]
settings["db.uri"]
settings.DB__uri

Defining variables

On files

settings.toml

[development]
dynaconf_merge = true

[development.db]
echo = true

dynaconf_merge is a boolean that tells if the settings should be merged with the default settings defined in project_name/default.toml.

As environment variables

export PROJECT_NAME_KEY=value
export PROJECT_NAME_KEY="@int 42"
export PROJECT_NAME_KEY="@jinja {{ this.db.uri }}"
export PROJECT_NAME_DB__uri="@jinja {{ this.db.uri | replace('db', 'data') }}"

Secrets

There is a file .secrets.toml where your sensitive variables are stored, that file must be ignored by git. (add that to .gitignore)

Or store your secrets in environment variables or a vault service, Dynaconf can read those variables.

Switching environments

PROJECT_NAME_ENV=production project_name run

Read more on https://dynaconf.com

Development

Read the CONTRIBUTING.md file.

fastapi-project-template's People

Contributors

feliciss avatar rochacbruno avatar sarath-ps avatar urjeetpatel avatar violentmagician avatar webbpinner avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

fastapi-project-template's Issues

How invoke __main__.py to use cli commands?

Thanks for share your template, it's amazing.

I'm trying to invoke cli command from terminal, can anyone give an example of this invocation?.

I have a project named "templateFast" and I tried:

  • At c:\templateFast path:

    c:\templateFast> python project/__main__.py --help
    Traceback (most recent call last):
     File "C:\.....\templateFast\templatefast\__main__.py", line 2, in <module>
        from .cli import cli
      ImportError: attempted relative import with no known parent package
    
  • At c:\templateFast\templateFast path throw the same error

  • The execution with python -m don't run in any case

Any help will be appreciated.
Thanks

Template CodeCov to 100%

At the moment, when CI with codecov is executed it reports coverage of 81%

It might be great if this can be increased to 100%

Fix init.sh

Fix init.sh and add to the python-project-template makefile

How to use pyinstaller with this template?

git clone --depth=1 https://github.com/rochacbruno/fastapi-project-template
cd fastapi-project-template

# setup venv ...
python -V
# Python 3.11.4

pip install -r requirements.txt
python -m project_name run
# all ok

Try pyinstaller:

pip install pyinstaller
pyinstaller --name project_name -y --onefile project_name/__main__.py
./dist/project_name

Got:

Traceback (most recent call last):
  File "project_name/__main__.py", line 2, in <module>
    from .cli import cli
ImportError: attempted relative import with no known parent package
[455] Failed to execute script '__main__' due to unhandled exception!

It seems that this error can be solved with from project_name.cli import cli, but this is not a graceful solution I guess.

FastAPIError when using Dependencies

I am using this amazing template to build an app I followed the first steps and I got an error while running the tests;
When I run make test I get a "fastapi.exceptions.FastAPIError" in a route definition but if I remove the dependency to AuthenticatedUser the error disapears.

This is the route where it happens

"/", response_model=ContentResponse, dependencies=[AuthenticatedUser]

@router.post(
    "/", response_model=ContentResponse, dependencies=[AuthenticatedUser],
)
async def create_content(
    *,
    session: Session = ActiveSession,
    request: Request,
    content: ContentIncoming,
):
    # set the ownsership of the content to the current user
    db_content = Content.from_orm(content)
    user: User = get_current_user(request=request)
    db_content.user_id = user.id
    session.add(db_content)
    session.commit()
    session.refresh(db_content)
    return db_content

and the whole exception is

ImportError while loading conftest '/home/konradzuse/PycharmProjects/app-service/application-service/tests/conftest.py'.
tests/conftest.py:11: in
from app_service import app, settings, db # noqa
app_service/init.py:1: in
from .app import app
app_service/app.py:9: in
from .routes import main_router
app_service/routes/init.py:5: in
from .content import router as content_router
app_service/routes/content.py:35: in
@router.patch(
...
raise fastapi.exceptions.FastAPIError(
E fastapi.exceptions.FastAPIError: Invalid args for response field! Hint: check that typing.Optional[starlette.requests.Request] is a valid Pydantic field type. If you are using a return type annotation that is not a valid Pydantic field (e.g. Union[Response, dict, None]) you can disable generating the response model from the type annotation with the path operation decorator parameter response_model=None.

I tried to use response_model = None but still got the same error. I looked for similar questions but normally they are related to the model itself. I hope somone can cast some light.

Thanks beforehand!

ERROR: No matching distribution found for dynaconf

  • Linux Mint 20.3
  • Python 3.9.5
$ git clone https://github.com/mbnoimi/fastapi-template.git fastapi_template
Cloning into 'fastapi_template'...
remote: Enumerating objects: 84, done.
remote: Counting objects: 100% (84/84), done.
remote: Compressing objects: 100% (66/66), done.
remote: Total 84 (delta 19), reused 70 (delta 13), pack-reused 0
Unpacking objects: 100% (84/84), 200.89 KiB | 965.00 KiB/s, done.

$ cd fastapi_template
$ make install
grep: pyproject.toml: No such file or directory
Don't forget to run 'make virtualenv' if you got errors.
Defaulting to user installation because normal site-packages is not writeable
Obtaining file:///home/laptop/Desktop/Boilerlaptes/fastapi_template
  Preparing metadata (setup.py) ... done
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f8d1df80d60>: Failed to establish a new connection: [Errno -2] Name or service not known')': /simple/dynaconf/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f8d1df800a0>: Failed to establish a new connection: [Errno -2] Name or service not known')': /simple/dynaconf/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f8d1df80730>: Failed to establish a new connection: [Errno -2] Name or service not known')': /simple/dynaconf/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f8d1df80e50>: Failed to establish a new connection: [Errno -2] Name or service not known')': /simple/dynaconf/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f8d1df80250>: Failed to establish a new connection: [Errno -2] Name or service not known')': /simple/dynaconf/
ERROR: Could not find a version that satisfies the requirement dynaconf (from fastapi-template[test]) (from versions: none)
ERROR: No matching distribution found for dynaconf
make: *** [Makefile:23: install] Error 1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.