feat: универсальный шаблон проектов контура Raisa
- base_templates/: шаблоны платформы fastapi, streamlit, airflow без изменений - contour/: платформа, подтверждённые версии, грабли, профили 4 типов приложений - project-kit/: SDD (S/M/L, delta/spec/plan, constitution, DoR/DoD) + grill, критик тестов, UX gate, handoff; один канон AGENTS.md для Cursor и Claude Code - scripts/init_project.sh: сборка нового проекта или подключение kit к существующему - docs/decisions/0001: что перенесено из elite_vibecoding и dmukp и почему Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0139EkK4ShEj52pM9Z5UCwM1
This commit is contained in:
11
base_templates/fastapi/.gitignore
vendored
Normal file
11
base_templates/fastapi/.gitignore
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
.venv
|
||||
venv
|
||||
__pycache__
|
||||
.vscode
|
||||
.idea
|
||||
files
|
||||
node_modules
|
||||
|
||||
dist
|
||||
web/.npmrc
|
||||
web/package-lock.json
|
||||
9
base_templates/fastapi/.gitlab-ci.yml
Normal file
9
base_templates/fastapi/.gitlab-ci.yml
Normal file
@@ -0,0 +1,9 @@
|
||||
include:
|
||||
- project: 'cicd/ci'
|
||||
file: 'fastapi-app.yml'
|
||||
variables:
|
||||
GIT_STRATEGY: 'clone'
|
||||
APP_VERSION: '1.0.0'
|
||||
APP_PORT: 8501
|
||||
APP_SHARED: 1
|
||||
BASE_IMAGE: 'fastapi-template:1.3.0'
|
||||
163
base_templates/fastapi/README.md
Normal file
163
base_templates/fastapi/README.md
Normal file
@@ -0,0 +1,163 @@
|
||||
[](https://github.com/psf/black) [](https://pycqa.github.io/isort/) [](https://github.com/pylint-dev/pylint)
|
||||
__________________________________________________________________________________________________________
|
||||
# dkr_frm_dev_backend, v 0.0.1
|
||||
____
|
||||
|
||||
| | Исполнитель | Заказчик |
|
||||
|-----------|:----------------------------------------:|:----------------------------------------------:|
|
||||
| Сотрудник | vanyushin-sa | vanyushin-sa |
|
||||
| Отдел | aurora | aurora |
|
||||
| Контакты | vanyushinsa@rshb.ru | vanyushinsa@rshb.ru |
|
||||
-----
|
||||
# Шаблон FastAPI
|
||||
|
||||
## Описание
|
||||
|
||||
Данное шаблон предоставляет проект, в котором приложение состоит из API и UI. При использовании данного типа проекта, Вы можете разрабатывать, как отдельные API сервисы, так и WEB приложения с интерфейсом. Для построения WEB интерфейса используется React. Далее описаны основные иснтрументы предустановленные данным шаблоном:
|
||||
|
||||
### Подготовка к разработке
|
||||
|
||||
Для удобной настройки проекта под разработку. Перейдите в каталог setup и выполните слудеющие команды:
|
||||
|
||||
```bash
|
||||
cd setup
|
||||
chmod +x setup.sh
|
||||
./setup.sh
|
||||
```
|
||||
По итогу успешного выполнения Вы получите сообщение следующего
|
||||
|
||||
```bash
|
||||
complete setup web application
|
||||
To start api, cd to api directory, and use venv, start run_server.py
|
||||
To start api, cd to web directory, and use command npm run start!
|
||||
Happy Hacking! :)
|
||||
```
|
||||
|
||||
Далее просто запускайте проекты и приступайте к разработке
|
||||
|
||||
### Backend
|
||||
|
||||
Исходный код API находится в каталоге api. После клонирования репозитория требуется создать виртуальное окружение и установить зависимости, это достигается следующими командами:
|
||||
|
||||
```bash
|
||||
cd api
|
||||
python -m venv ./.venv
|
||||
cp ./../setup/pip.conf ./.venv/pip.conf
|
||||
source ./.venv/bin/python
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
Запуск приложения осуществляется через файл: run_server.py
|
||||
|
||||
В качестве фреймворка ля api используется FastAPI. (Как понятно из названия шаблона) Подробнее ознакомится с возможностями Fast API вы можете в официальной документации: [Fast API документация](https://fastapi.tiangolo.com/)
|
||||
|
||||
Вы можете дополнительно устанавливать библиотеки необходимые для разработки. Настоятельно не рекомендуется изменять базовые предустановки из файла requirements.txt
|
||||
|
||||
Базовый шаблон предоставляет минимальный функционал по работе с данными. Далее описаны основные моменты влияющие на работу приложения.
|
||||
|
||||
#### Основная структура проекта
|
||||
|
||||
```bash
|
||||
api
|
||||
├── requirements.txt
|
||||
├── run_server.py
|
||||
├── src
|
||||
│ ├── app.py
|
||||
│ ├── __init__.py
|
||||
│ ├── settings
|
||||
│ │ ├── __init__.py
|
||||
│ │ ├── models.py
|
||||
│ │ └── settings.py
|
||||
└── web
|
||||
```
|
||||
|
||||
Вы можете придерживатся любой структуры проекта, главное, чтобы у Вас присутствовал файл run_server.py. Который запускает web сервер uvicorn или gunicorn. Также обязательно Ваш сервер должен подниматся на определенном хосте и порте. Требуемый хост и порт передаются внутрь через переменные окружения SERVER_HOST, SERVER_PORT
|
||||
|
||||
```python
|
||||
uvicorn.run(
|
||||
app,
|
||||
host=settings.server.HOST,
|
||||
port=settings.server.PORT,
|
||||
lifespan="on"
|
||||
)
|
||||
```
|
||||
|
||||
#### Отказ от ui (react)
|
||||
|
||||
Если внутри вашего приложения не требуется добавлять визуальный интерфейс, а Вам требуется исключительно разработать API, то в таком случае не стоит удалять директорию web находящуюся на уровне с директорией api. ТРебуется внести небольшие правки в конфигурацию приложения, в частности в файл: /api/src/app.py, удалив следующее содержимое. В таком случае Fast API сервис не будет обрабатывать статические файлы, от web приложения.
|
||||
|
||||
```python
|
||||
#Подключение собранного web приложения
|
||||
app.mount("/", StaticFiles(directory="web", html=True), name="web")
|
||||
```
|
||||
|
||||
### Frontend
|
||||
|
||||
Исходный код UI находится в каталоге web. После клонирования репозитория требуется установить зависимости, это достигается следующими командами:
|
||||
|
||||
```bash
|
||||
cd web
|
||||
npm install
|
||||
```
|
||||
|
||||
Запуск приложения осуществляется через файл команду:
|
||||
|
||||
```bash
|
||||
npm run start
|
||||
```
|
||||
|
||||
В качестве фреймворка для ui используется React. Подробнее ознакомится с возможностями React вы можете в официальной документации: [React документация](https://react.dev/reference/react)
|
||||
|
||||
Вы можете дополнительно устанавливать библиотеки необходимые для разработки. Настоятельно не рекомендуется изменять базовые предустановки из файла package.json
|
||||
|
||||
Базовый шаблон предоставляет минимальный интерфейс по работе с данными. Далее описаны основные моменты влияющие на работу web приложения.
|
||||
|
||||
#### Основная структура проекта
|
||||
|
||||
```bash
|
||||
web
|
||||
├── biome.json
|
||||
├── .npmrc
|
||||
├── dist
|
||||
├── package.json
|
||||
├── postcss.config.cjs
|
||||
├── public
|
||||
│ └── index.html
|
||||
├── README.md
|
||||
├── rsbuild.config.ts
|
||||
├── src
|
||||
│ ├── App.tsx
|
||||
│ ├── config.ts
|
||||
│ ├── env.d.ts
|
||||
│ ├── index.css
|
||||
│ └── index.tsx
|
||||
├── tailwind.config.js
|
||||
└── tsconfig.json
|
||||
```
|
||||
|
||||
Вы можете придерживатся любой структуры проекта, внутри src. Но на верхнем уровне находятся файлы конфигурации и сборки их требуется изменять только в крайнем случае. Для сборки приложения используется [RSBuild](https://rsbuild.dev/)
|
||||
|
||||
Для создания UI настоятельно рекомендуется использовать предустановленную библиотеку компонентови стилей:
|
||||
|
||||
- tailwindcss
|
||||
- daisy-ui
|
||||
- react-daisy-ui
|
||||
- raisa-ui
|
||||
|
||||
!!! Важно, если внутри web приложения Вы хотите обращатся к API данного проекта, используйте следующую конструкцию:
|
||||
|
||||
```javascript
|
||||
|
||||
fetch(`${Config.API_URL}/api`, {
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
method: 'GET'
|
||||
})
|
||||
|
||||
```
|
||||
|
||||
Речь идет об вызываемом эндпоинте ${Config.API_URL}/api, Обязательно используйте конструкцию данного вида т.к. при сборке приложения статический сайт обращается относительно api и вместо
|
||||
запросов вида http://localhost:8000/api должно быть так: /api
|
||||
|
||||
0
base_templates/fastapi/api/.env
Normal file
0
base_templates/fastapi/api/.env
Normal file
BIN
base_templates/fastapi/api/requirements.txt
Normal file
BIN
base_templates/fastapi/api/requirements.txt
Normal file
Binary file not shown.
11
base_templates/fastapi/api/run_server.py
Normal file
11
base_templates/fastapi/api/run_server.py
Normal file
@@ -0,0 +1,11 @@
|
||||
import uvicorn
|
||||
from src import app, get_settings
|
||||
|
||||
if __name__ == "__main__":
|
||||
settings = get_settings()
|
||||
uvicorn.run(
|
||||
app,
|
||||
host=settings.server.HOST,
|
||||
port=settings.server.PORT,
|
||||
lifespan="on"
|
||||
)
|
||||
7
base_templates/fastapi/api/src/__init__.py
Normal file
7
base_templates/fastapi/api/src/__init__.py
Normal file
@@ -0,0 +1,7 @@
|
||||
from .app import app
|
||||
from .conf import get_settings
|
||||
|
||||
__all__ = [
|
||||
"app",
|
||||
"get_settings"
|
||||
]
|
||||
50
base_templates/fastapi/api/src/app.py
Normal file
50
base_templates/fastapi/api/src/app.py
Normal file
@@ -0,0 +1,50 @@
|
||||
import os
|
||||
|
||||
from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from .conf import get_settings
|
||||
from .routes import api_route
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
VERSION = "1.0.0"
|
||||
UP_TIME = datetime.now(timezone.utc)
|
||||
|
||||
app = FastAPI(
|
||||
title="Fast API",
|
||||
version=VERSION,
|
||||
root_path=settings.ROOT_PATH,
|
||||
)
|
||||
|
||||
@app.get(
|
||||
"/healthcheck",
|
||||
status_code=200
|
||||
)
|
||||
async def healthcheck():
|
||||
return {
|
||||
"uptime": UP_TIME,
|
||||
"version": VERSION
|
||||
}
|
||||
|
||||
app.add_middleware(ProxyHeadersMiddleware, trusted_hosts=["*"])
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
#Создание каталога для web приложения
|
||||
os.makedirs(os.path.join('web'), exist_ok=True)
|
||||
|
||||
#Подключаем все ендпоинты и роуты до маунта статических файлов
|
||||
app.include_router(api_route)
|
||||
|
||||
#Подключение собранного web приложения
|
||||
app.mount("/", StaticFiles(directory="web", html=True), name="web")
|
||||
5
base_templates/fastapi/api/src/conf/__init__.py
Normal file
5
base_templates/fastapi/api/src/conf/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from .settings import get_settings
|
||||
|
||||
__all__ = [
|
||||
"get_settings"
|
||||
]
|
||||
9
base_templates/fastapi/api/src/conf/models.py
Normal file
9
base_templates/fastapi/api/src/conf/models.py
Normal file
@@ -0,0 +1,9 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class ServerSettings(BaseModel):
|
||||
"""
|
||||
Настройки сервера uvicorn
|
||||
"""
|
||||
HOST: str = '0.0.0.0'
|
||||
PORT: int = 8000
|
||||
33
base_templates/fastapi/api/src/conf/settings.py
Normal file
33
base_templates/fastapi/api/src/conf/settings.py
Normal file
@@ -0,0 +1,33 @@
|
||||
from fastapi.logger import logger
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
from .models import ServerSettings
|
||||
from functools import lru_cache
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
""" Настройки приложения """
|
||||
ROOT_PATH: str = '/'
|
||||
|
||||
server: ServerSettings = ServerSettings()
|
||||
|
||||
class Config:
|
||||
extra = 'ignore'
|
||||
env_file = ".env"
|
||||
env_nested_delimiter = '__'
|
||||
nested_model_default_partial_update = False
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
"""
|
||||
Получение настроек приложения
|
||||
:return: Настройки приложения
|
||||
"""
|
||||
try:
|
||||
_ = load_dotenv()
|
||||
except Exception as err:
|
||||
logger.error("Error load settings", exc_info=err)
|
||||
return Settings()
|
||||
5
base_templates/fastapi/api/src/routes/__init__.py
Normal file
5
base_templates/fastapi/api/src/routes/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from .api import api_route
|
||||
|
||||
__all__ = [
|
||||
"api_route"
|
||||
]
|
||||
5
base_templates/fastapi/api/src/routes/api/__init__.py
Normal file
5
base_templates/fastapi/api/src/routes/api/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from .route import route as api_route
|
||||
|
||||
__all__ = [
|
||||
"api_route"
|
||||
]
|
||||
17
base_templates/fastapi/api/src/routes/api/route.py
Normal file
17
base_templates/fastapi/api/src/routes/api/route.py
Normal file
@@ -0,0 +1,17 @@
|
||||
from fastapi import APIRouter
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from .schemas import ApiResponse
|
||||
|
||||
route = APIRouter(prefix="/api",tags=['Base'])
|
||||
|
||||
|
||||
@route.get(
|
||||
"",
|
||||
response_model=ApiResponse
|
||||
)
|
||||
async def get_data():
|
||||
return ApiResponse(
|
||||
date_with_time=datetime.now(timezone.utc),
|
||||
text="Fast API приложение"
|
||||
)
|
||||
7
base_templates/fastapi/api/src/routes/api/schemas.py
Normal file
7
base_templates/fastapi/api/src/routes/api/schemas.py
Normal file
@@ -0,0 +1,7 @@
|
||||
from pydantic import BaseModel
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class ApiResponse(BaseModel):
|
||||
date_with_time: datetime
|
||||
text: str
|
||||
8
base_templates/fastapi/raisa_config.yml
Normal file
8
base_templates/fastapi/raisa_config.yml
Normal file
@@ -0,0 +1,8 @@
|
||||
# Конфигурация ресурсов приложения
|
||||
# Доступные профили: Малый (0.25CPU/1GB), Средний (0.5CPU/2GB), Большой (1CPU/4GB), custom
|
||||
# CPU Cores указывается, только с шагом 0.25
|
||||
# RAM GB указывается, только с шагом 1
|
||||
profile:
|
||||
# Последние данные по наименованию профиля: Средний
|
||||
cpu: 0.5 # значение Cores
|
||||
ram: 2.0 # значение GB
|
||||
1
base_templates/fastapi/roles.json
Normal file
1
base_templates/fastapi/roles.json
Normal file
@@ -0,0 +1 @@
|
||||
{}
|
||||
2
base_templates/fastapi/setup/.npmrc
Normal file
2
base_templates/fastapi/setup/.npmrc
Normal file
@@ -0,0 +1,2 @@
|
||||
registry=http://nexus.dev.raisa.go.rshbank.ru/repository/npm/
|
||||
strict-ssl=false
|
||||
8
base_templates/fastapi/setup/pip.conf
Normal file
8
base_templates/fastapi/setup/pip.conf
Normal file
@@ -0,0 +1,8 @@
|
||||
[global]
|
||||
disable-pip-version-check = True
|
||||
trusted-host = nexus.dev.raisa.go.rshbank.ru
|
||||
index = http://nexus.dev.raisa.go.rshbank.ru/repository/pypi/pypi
|
||||
index-url = http://nexus.dev.raisa.go.rshbank.ru/repository/pypi/simple
|
||||
|
||||
[easy_install]
|
||||
index-url = http://nexus.dev.raisa.go.rshbank.ru/repository/pypi/simple
|
||||
23
base_templates/fastapi/setup/setup.sh
Normal file
23
base_templates/fastapi/setup/setup.sh
Normal file
@@ -0,0 +1,23 @@
|
||||
#!/bin/bash
|
||||
echo "setup project to development"
|
||||
|
||||
echo "create virtual environment to api"
|
||||
|
||||
python -m venv ./../api/.venv
|
||||
cp ./pip.conf ./../api/.venv/pip.conf
|
||||
source ./../api/.venv/bin/activate
|
||||
pip install -r ./../api/requirements.txt
|
||||
|
||||
echo "complete setup development api"
|
||||
|
||||
echo "setup web application"
|
||||
|
||||
cp ./.npmrc ./../web/.npmrc
|
||||
cd ./../web
|
||||
|
||||
npm i
|
||||
|
||||
echo "complete setup web application"
|
||||
echo "To start api, cd to api directory, and use venv, start run_server.py"
|
||||
echo "To start api, cd to web directory, and use command npm run start!"
|
||||
echo "Happy Hacking! :)"
|
||||
1
base_templates/fastapi/users.json
Normal file
1
base_templates/fastapi/users.json
Normal file
@@ -0,0 +1 @@
|
||||
{}
|
||||
1
base_templates/fastapi/web/.env
Normal file
1
base_templates/fastapi/web/.env
Normal file
@@ -0,0 +1 @@
|
||||
REACT_APP_API_URL=http://localhost:8000
|
||||
91
base_templates/fastapi/web/biome.json
Normal file
91
base_templates/fastapi/web/biome.json
Normal file
@@ -0,0 +1,91 @@
|
||||
{
|
||||
"$schema": "https://biomejs.dev/schemas/1.9.4/schema.json",
|
||||
"vcs": {
|
||||
"enabled": true,
|
||||
"clientKind": "git",
|
||||
"useIgnoreFile": true
|
||||
},
|
||||
"files": {
|
||||
"ignoreUnknown": true,
|
||||
"ignore": ["node_modules"]
|
||||
},
|
||||
"formatter": {
|
||||
"enabled": true,
|
||||
"lineWidth": 140,
|
||||
"formatWithErrors": true
|
||||
},
|
||||
"organizeImports": {
|
||||
"enabled": true
|
||||
},
|
||||
"linter": {
|
||||
"ignore": ["*.json"],
|
||||
"enabled": true,
|
||||
"rules": {
|
||||
"recommended": true,
|
||||
"a11y": {
|
||||
"useButtonType": "off",
|
||||
"noSvgWithoutTitle": "off"
|
||||
},
|
||||
"complexity": {
|
||||
"noForEach": "off",
|
||||
"noUselessTypeConstraint": "warn"
|
||||
},
|
||||
"correctness": {
|
||||
"noUnusedVariables": "error",
|
||||
"noUnusedImports": "error",
|
||||
"useExhaustiveDependencies": "info"
|
||||
},
|
||||
"nursery": {
|
||||
"noCommonJs": "error",
|
||||
"noDuplicateElseIf": "error",
|
||||
"noDuplicateProperties": "error",
|
||||
"noNestedTernary": "error",
|
||||
"useAtIndex": "error",
|
||||
"useCollapsedIf": "error",
|
||||
"useConsistentCurlyBraces": "error"
|
||||
},
|
||||
"performance": {
|
||||
"noDelete": "off",
|
||||
"noAccumulatingSpread": "off"
|
||||
},
|
||||
"style": {
|
||||
"useDefaultSwitchClause": "error",
|
||||
"useForOf": "error",
|
||||
"useFragmentSyntax": "error",
|
||||
"useConsistentArrayType": "error",
|
||||
"useShorthandAssign": "error"
|
||||
},
|
||||
"suspicious": {
|
||||
"noConsole": "warn",
|
||||
"noEmptyBlockStatements": "error",
|
||||
"noEvolvingTypes": "error",
|
||||
"noExplicitAny": "warn",
|
||||
"noSkippedTests": "warn",
|
||||
"useAwait": "error"
|
||||
}
|
||||
}
|
||||
},
|
||||
"javascript": {
|
||||
"formatter": {
|
||||
"quoteStyle": "single",
|
||||
"jsxQuoteStyle": "single",
|
||||
"bracketSameLine": true
|
||||
},
|
||||
"linter": {
|
||||
"enabled": true
|
||||
}
|
||||
},
|
||||
"json": {
|
||||
"parser": {
|
||||
"allowComments": true
|
||||
}
|
||||
},
|
||||
"css": {
|
||||
"formatter": {
|
||||
"enabled": true
|
||||
},
|
||||
"parser": {
|
||||
"cssModules": true
|
||||
}
|
||||
}
|
||||
}
|
||||
27
base_templates/fastapi/web/package.json
Normal file
27
base_templates/fastapi/web/package.json
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "rsbuild build",
|
||||
"start": "rsbuild dev --open",
|
||||
"preview": "rsbuild preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"raisa-ui": "^1.0.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-daisyui": "^5.0.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "1.9.4",
|
||||
"@rsbuild/core": "^1.2.4",
|
||||
"@rsbuild/plugin-react": "^1.1.0",
|
||||
"@types/react": "^18.3.1",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"typescript": "^5.7.3",
|
||||
"daisyui": "^4.12.10",
|
||||
"tailwindcss": "^3.4.13"
|
||||
}
|
||||
}
|
||||
5
base_templates/fastapi/web/postcss.config.cjs
Normal file
5
base_templates/fastapi/web/postcss.config.cjs
Normal file
@@ -0,0 +1,5 @@
|
||||
module.exports = {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
}
|
||||
}
|
||||
0
base_templates/fastapi/web/public/.gitkeep
Normal file
0
base_templates/fastapi/web/public/.gitkeep
Normal file
13
base_templates/fastapi/web/public/index.html
Normal file
13
base_templates/fastapi/web/public/index.html
Normal file
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru-RU">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
<title>Пример React-приложения</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
<div id="root"></div>
|
||||
</body>
|
||||
</html>
|
||||
28
base_templates/fastapi/web/rsbuild.config.ts
Normal file
28
base_templates/fastapi/web/rsbuild.config.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { defineConfig, loadEnv } from '@rsbuild/core';
|
||||
import { pluginReact } from '@rsbuild/plugin-react';
|
||||
|
||||
const { publicVars, rawPublicVars } = loadEnv({prefixes: ['REACT_APP_']});
|
||||
|
||||
export default defineConfig({
|
||||
server: {
|
||||
base: (rawPublicVars['REACT_APP_ROOT_PATH'] !== undefined) ? rawPublicVars['REACT_APP_ROOT_PATH'] : '/'
|
||||
},
|
||||
output: {
|
||||
filename: {
|
||||
js: '[name]_script.[contenthash:8].js',
|
||||
css: '[name]_style.[contenthash:8].css',
|
||||
},
|
||||
assetPrefix: (rawPublicVars['REACT_APP_ROOT_PATH'] !== undefined) ? rawPublicVars['REACT_APP_ROOT_PATH'] : './'
|
||||
},
|
||||
html: {
|
||||
template: './public/index.html',
|
||||
},
|
||||
source: {
|
||||
include: [{ not: /[\\/]core-js[\\/]/ }],
|
||||
define: {
|
||||
...publicVars,
|
||||
'process.env': JSON.stringify(rawPublicVars),
|
||||
}
|
||||
},
|
||||
plugins: [pluginReact()],
|
||||
});
|
||||
40
base_templates/fastapi/web/src/App.tsx
Normal file
40
base_templates/fastapi/web/src/App.tsx
Normal file
@@ -0,0 +1,40 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Config } from './conf/config';
|
||||
import { Card } from 'react-daisyui';
|
||||
|
||||
const App = () => {
|
||||
const [apiResponse, setApiResponse] = useState<{
|
||||
date_with_time: string,
|
||||
text: string
|
||||
}|null>(null);
|
||||
|
||||
// Загрузка данных с сервера
|
||||
useEffect(() => {
|
||||
|
||||
fetch(`${Config.API_URL}/api`, {
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
method: 'GET'
|
||||
})
|
||||
.then(async (response) => {
|
||||
setApiResponse(await response.json())
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log('Ошибка при получении данных с api:', error);
|
||||
alert("Ошибка при получении данных с api");
|
||||
})
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className='flex items-center justify-center absolute inset-0'>
|
||||
<Card className="flex flex-col gap-2 border-[2px] items-center justify-center border-primary rounded-md p-6" style={{ width: '50vw', height: '200px' }}>
|
||||
<h1>Шаблон приложения Fast API</h1>
|
||||
<p>Время: {(apiResponse?.date_with_time) ? new Date(apiResponse?.date_with_time).toISOString() : "Нет данных по времени"}, Текст: {apiResponse?.text}</p>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default App;
|
||||
6
base_templates/fastapi/web/src/conf/config.ts
Normal file
6
base_templates/fastapi/web/src/conf/config.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
//@ts-ignore
|
||||
const environment = process.env;
|
||||
|
||||
export class Config {
|
||||
static API_URL: string = environment.REACT_APP_API_URL ?? environment.REACT_APP_ROOT_PATH ?? '';
|
||||
}
|
||||
1
base_templates/fastapi/web/src/env.d.ts
vendored
Normal file
1
base_templates/fastapi/web/src/env.d.ts
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/// <reference types="@rsbuild/core/types" />
|
||||
17
base_templates/fastapi/web/src/index.css
Normal file
17
base_templates/fastapi/web/src/index.css
Normal file
@@ -0,0 +1,17 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
|
||||
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
|
||||
sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
|
||||
monospace;
|
||||
}
|
||||
14
base_templates/fastapi/web/src/index.tsx
Normal file
14
base_templates/fastapi/web/src/index.tsx
Normal file
@@ -0,0 +1,14 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import './index.css';
|
||||
import App from './App';
|
||||
|
||||
const rootEl = document.getElementById('root');
|
||||
if (rootEl) {
|
||||
const root = ReactDOM.createRoot(rootEl);
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
}
|
||||
43
base_templates/fastapi/web/tailwind.config.js
Normal file
43
base_templates/fastapi/web/tailwind.config.js
Normal file
@@ -0,0 +1,43 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
module.exports = {
|
||||
content: [
|
||||
"./src/**/*.{html,js,jsx,ts,tsx}",
|
||||
"node_modules/daisyui/dist/**/*.js",
|
||||
"node_modules/react-daisyui/dist/**/*.js",
|
||||
"node_modules/raisa-ui/dist/**/*.js"
|
||||
],
|
||||
theme: {
|
||||
extend: {},
|
||||
},
|
||||
plugins: [require('daisyui')],
|
||||
daisyui: {
|
||||
themes: [
|
||||
{
|
||||
rshb: {
|
||||
...require('daisyui/src/theming/themes')['light'],
|
||||
|
||||
"primary": "#171A1C",
|
||||
"primary-content": "#fcfcfd",
|
||||
"secondary": "#ECEDEF",
|
||||
"secondary-content": "#687178",
|
||||
"accent": "#8ecaff",
|
||||
"accent-content": "#fcfcfd",
|
||||
"neutral": "#ecedef",
|
||||
"neutral-content": "#171A1C",
|
||||
"base-100": "#FCFCFD",
|
||||
"base-200": "#F6F7F8",
|
||||
"base-300": "#ECEDEF",
|
||||
"base-content": "#171A1C",
|
||||
"info": "#0894FF",
|
||||
"info-content": "#E3E5E8",
|
||||
"success": "#39B33D",
|
||||
"success-content": "#E3E5E8",
|
||||
"warning": "#E6B200",
|
||||
"warning-content": "#fcfcfd",
|
||||
"error": "#FF371A",
|
||||
"error-content": "#fcfcfd",
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
23
base_templates/fastapi/web/tsconfig.json
Normal file
23
base_templates/fastapi/web/tsconfig.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"lib": ["DOM", "ES2020"],
|
||||
"jsx": "react-jsx",
|
||||
"target": "ES2020",
|
||||
"noEmit": true,
|
||||
"skipLibCheck": true,
|
||||
"useDefineForClassFields": true,
|
||||
|
||||
/* modules */
|
||||
"module": "ESNext",
|
||||
"isolatedModules": true,
|
||||
"resolveJsonModule": true,
|
||||
"moduleResolution": "Bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
|
||||
/* type checking */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
Reference in New Issue
Block a user