Giter Site home page Giter Site logo

fastapi-base's Introduction

alt text

FASTAPI BASE

Introduction

Dựng khung project để phát triển dự án khá tốn kém thời gian và công sức.

Vì vậy mình quyết định dựng FastAPI Base cung cấp sẵn các function basic nhất như CRUD User, Login, Register.

Project đã bao gồm migration DB và pytest để sẵn sàng sử dụng trong môi trường doanh nghiệp.

Source Library

Đây là phiên bản Backend base từ framework FastAPI. Trong code base này đã cấu hình sẵn

  • FastAPI
  • Postgresql(>=12)
  • Alembic
  • API Login
  • API CRUD User, API Get Me & API Update Me
  • Pagination
  • Authen/Authorize với JWT
  • Permission_required & Login_required
  • Logging
  • Pytest

Installation

Cách 1:

  • Clone Project
  • Cài đặt Postgresql & Create Database
  • Cài đặt requirements.txt
  • Run project ở cổng 8000
// Tạo postgresql Databases via CLI (Ubuntu 20.04)
$ sudo -u postgres psql
# CREATE DATABASE fastapi_base;
# CREATE USER db_user WITH PASSWORD 'secret123';
# GRANT ALL PRIVILEGES ON DATABASE fastapi_base TO db_user;

// Clone project & run
$ git clone https://github.com/Longdh57/fastapi-base
$ cd fastapi-base
$ virtualenv -p python3 .venv
$ source .venv/bin/activate
$ pip install -r requirements.txt
$ cp env.example .env       // Recheck SQL_DATABASE_URL ở bước này
$ alembic upgrade head
$ uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload

Cách 2: Dùng Docker & Docker Compose - đơn giản hơn nhưng cần có kiến thức Docker

  • Clone Project
  • Run docker-compose
$ git clone https://github.com/Longdh57/fastapi-base
$ cd fastapi-base
$ DOCKER_BUILDKIT=1 docker build -t fastapi-base:latest .
$ docker-compose up -d

Cấu trúc project

.  
├── alembic  
│   ├── versions    // thư mục chứa file migrations  
│   └── env.py  
├── app  
│   ├── api         // các file api được đặt trong này  
│   ├── core        // chứa file config load các biến env & function tạo/verify JWT access-token  
│   ├── db          // file cấu hình make DB session  
│   ├── helpers     // các function hỗ trợ như login_manager, paging  
│   ├── models      // Database model, tích hợp với alembic để auto generate migration  
│   ├── schemas     // Pydantic Schema  
│   ├── services    // Chứa logic CRUD giao tiếp với DB  
│   └── main.py     // cấu hình chính của toàn bộ project  
├── tests  
│   ├── api         // chứa các file test cho từng api  
│   ├── faker       // chứa file cấu hình faker để tái sử dụng  
│   ├── .env        // config DB test  
│   └── conftest.py // cấu hình chung của pytest  
├── .gitignore  
├── alembic.ini  
├── docker-compose.yaml  
├── Dockerfile  
├── env.example  
├── logging.ini     // cấu hình logging  
├── postgresql.conf // file cấu hình postgresql, sử dụng khi run docker-compose  
├── pytest.ini      // file setup cho pytest  
├── README.md  
└── requirements.txt

Demo URL

FASTAPI-BASE

Migration

Migration là một tính năng cho phép bạn thay đổi cả cấu trúc và dữ liệu trong database. Thay vì thay đổi trực tiếp vào database thì FastAPI sử dụng alembic để mô tả việc thay đổi các table

File migration - SAMPLE

# alembic/versions/f9a075ca46e9_.py

...
def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('user',
    sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
    sa.Column('full_name', sa.String(), nullable=True),
    sa.Column('email', sa.String(), nullable=True),
    sa.Column('hashed_password', sa.String(length=255), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_user_email'), 'user', ['email'], unique=True)
    op.create_index(op.f('ix_user_full_name'), 'user', ['full_name'], unique=False)
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index(op.f('ix_user_full_name'), table_name='user')
    op.drop_index(op.f('ix_user_email'), table_name='user')
    op.drop_table('user')
    # ### end Alembic commands ###
...

Guide: Tạo bảng Book quản lý list sách

Trong folder app/models tạo file model_book.py với nội dung

# app/models/model_book.py
from sqlalchemy import Column, String, DateTime

from app.models.model_base import BareBaseModel


class Book(BareBaseModel):
    name = Column(String(200), index=True)
    author = Column(String(255))
    publishing_year = Column(DateTime)

Thêm 1 dòng vào app/models/__init__.py ở dưới

# app/models/____init__.py

...
from app.models.model_book import Book  # noqa

Mở FastAPI Terminal

$ alembic revision --autogenerate   # Create migration versions

Sau bước này, 1 file migration với file name random sẽ được generate tại alembic/versions/

# alembic/versions/6f0df0651d97_.py
...
def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('book',
    sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
    sa.Column('created_at', sa.DateTime(), nullable=True),
    sa.Column('updated_at', sa.DateTime(), nullable=True),
    sa.Column('name', sa.String(length=200), nullable=True),
    sa.Column('author', sa.String(length=255), nullable=True),
    sa.Column('publishing_year', sa.DateTime(), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_book_name'), 'book', ['name'], unique=False)
    op.drop_table('table_name')
    # ### end Alembic commands ###
...

Run migration để update Database

$ alembic upgrade head   # Upgrade to last version migration

Check lại thay đổi trong Database

FastAPI UI

Song song với FastAPI backend, đây là phiên bản Frontend tương thích với project này.

URL: FastAPI Base Frontend

fastapi-base's People

Contributors

longdh-teko avatar longdh57 avatar

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.