Skip to content

Commit 1dc7f0e

Browse files
committed
[FEAT] add & edit venv creation and apply deps at startup + startproject cli operations, edit templates
1 parent b94037d commit 1dc7f0e

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

51 files changed

+484
-444
lines changed

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[project]
22
name = "FastAPI-fastkit"
3-
version = "0.1.0"
3+
version = "0.1.1"
44
description = "Fast, easy-to-use starter kit for new users of Python and FastAPI"
55
authors = [
66
{name = "bnbong", email = "bbbong9@gmail.com"},

src/fastapi_fastkit/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
__version__ = "0.0.1"
1+
__version__ = "0.1.1"
22

33
import os
44

src/fastapi_fastkit/backend.py

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
# --------------------------------------------------------------------------
66
import os
77
import re
8+
import subprocess
89
from logging import getLogger
910
from typing import Any
1011

@@ -14,7 +15,7 @@
1415
from rich.table import Table
1516
from rich.text import Text
1617

17-
from fastapi_fastkit.core.exceptions import TemplateExceptions
18+
from fastapi_fastkit.core.exceptions import BackendExceptions, TemplateExceptions
1819

1920
from . import console
2021

@@ -88,6 +89,7 @@ def inject_project_metadata(
8889
author_email: str,
8990
description: str,
9091
) -> None:
92+
# TODO : add main.py location at parameter
9193
"""Inject project metadata."""
9294
try:
9395
main_py_path = os.path.join(target_dir, "main.py")
@@ -115,6 +117,51 @@ def inject_project_metadata(
115117
raise TemplateExceptions("Failed to inject metadata")
116118

117119

120+
def create_venv(project_dir: str) -> str:
121+
"""Create a virtual environment."""
122+
try:
123+
with console.status("[bold green]Setting up project environment..."):
124+
console.print("[yellow]Creating virtual environment...[/yellow]")
125+
venv_path = os.path.join(project_dir, ".venv")
126+
subprocess.run(["python", "-m", "venv", venv_path], check=True)
127+
128+
if os.name == "nt":
129+
activate_venv = f" {os.path.join(venv_path, 'Scripts', 'activate.bat')}"
130+
else:
131+
activate_venv = f" source {os.path.join(venv_path, 'bin', 'activate')}"
132+
print_info(
133+
"venv created at "
134+
+ venv_path
135+
+ "\nTo activate the virtual environment, run:\n\n"
136+
+ activate_venv,
137+
)
138+
return venv_path
139+
140+
except Exception as e:
141+
print_error(f"Error during venv creation: {e}")
142+
raise BackendExceptions("Failed to create venv")
143+
144+
145+
def install_dependencies(project_dir: str, venv_path: str) -> None:
146+
"""Install project dependencies in the virtual environment."""
147+
try:
148+
if os.name == "nt": # Windows
149+
pip_path = os.path.join(venv_path, "Scripts", "pip")
150+
else: # Linux/Mac
151+
pip_path = os.path.join(venv_path, "bin", "pip")
152+
153+
with console.status("[bold green]Installing dependencies..."):
154+
subprocess.run(
155+
[pip_path, "install", "-r", "requirements.txt"],
156+
cwd=project_dir,
157+
check=True,
158+
)
159+
160+
except Exception as e:
161+
print_error(f"Error during dependency installation: {e}")
162+
raise BackendExceptions("Failed to install dependencies")
163+
164+
118165
# TODO : modify this function
119166
# def read_template_stack() -> Union[list, None]:
120167
# pass

src/fastapi_fastkit/cli.py

Lines changed: 9 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,10 @@
2222
from . import __version__, console
2323
from .backend import (
2424
create_info_table,
25+
create_venv,
2526
inject_project_metadata,
27+
install_dependencies,
2628
print_error,
27-
print_info,
2829
print_success,
2930
print_warning,
3031
validate_email,
@@ -220,6 +221,9 @@ def startup(
220221
project_dir, project_name, author, author_email, description
221222
)
222223

224+
venv_path = create_venv(project_dir)
225+
install_dependencies(project_dir, venv_path)
226+
223227
print_success(
224228
f"FastAPI project '{project_name}' from '{template}' has been created and saved to {user_local}!"
225229
)
@@ -236,7 +240,7 @@ def startup(
236240
)
237241
def startproject(project_name: str) -> None:
238242
"""
239-
Start a new FastAPI project.
243+
Start a empty FastAPI project setup.
240244
This command will automatically create a new FastAPI project directory and a python virtual environment.
241245
Dependencies will be automatically installed based on the selected stack at venv.
242246
@@ -294,33 +298,11 @@ def startproject(project_name: str) -> None:
294298

295299
console.print(table)
296300

297-
with console.status("[bold green]Setting up project environment..."):
298-
console.print("[yellow]Creating virtual environment...[/yellow]")
299-
venv_path = os.path.join(project_dir, "venv")
300-
subprocess.run(["python", "-m", "venv", venv_path], check=True)
301-
302-
if os.name == "nt": # Windows
303-
pip_path = os.path.join(venv_path, "Scripts", "pip")
304-
else: # Linux/Mac
305-
pip_path = os.path.join(venv_path, "bin", "pip")
306-
307-
console.print("[yellow]Installing dependencies...[/yellow]")
308-
subprocess.run(
309-
[pip_path, "install", "-r", "requirements.txt"],
310-
cwd=project_dir,
311-
check=True,
312-
)
301+
venv_path = create_venv(project_dir)
302+
install_dependencies(project_dir, venv_path)
313303

314304
print_success(f"Project '{project_name}' has been created successfully!")
315305

316-
if os.name == "nt":
317-
activate_venv = f" {os.path.join(venv_path, 'Scripts', 'activate.bat')}"
318-
else:
319-
activate_venv = f" source {os.path.join(venv_path, 'bin', 'activate')}"
320-
print_info(
321-
"To activate the virtual environment, run:\n\n" + activate_venv,
322-
)
323-
324306
except Exception as e:
325307
print_error(f"Error during project creation: {e}")
326308
shutil.rmtree(project_dir, ignore_errors=True)
@@ -418,6 +400,7 @@ def runserver(
418400
reload: bool = True,
419401
workers: int = 1,
420402
) -> None:
403+
# TODO : check where main.py is located and run it
421404
"""
422405
Run the FastAPI server for the current project.
423406
[1.1.0 update TODO] Alternative Point : using FastAPI-fastkit's 'fastapi dev' command
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# SECRET_KEY for testing (random string)
2+
SERVER_DOMAIN=localhost
3+
SECRET_KEY=jhnsavNAjHSMx0YBvL92wbM9K8FJEVDN
Lines changed: 191 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,191 @@
1+
### venv template
2+
# Virtualenv
3+
# http://iamzed.com/2009/05/07/a-primer-on-virtualenv/
4+
.Python
5+
[Bb]in
6+
[Ii]nclude
7+
[Ll]ib
8+
[Ll]ib64
9+
[Ll]ocal
10+
[Ss]cripts
11+
pyvenv.cfg
12+
.venv
13+
pip-selfcheck.json
14+
15+
### dotenv template
16+
.env
17+
18+
### VirtualEnv template
19+
# Virtualenv
20+
# http://iamzed.com/2009/05/07/a-primer-on-virtualenv/
21+
.Python
22+
[Bb]in
23+
[Ii]nclude
24+
[Ll]ib
25+
[Ll]ib64
26+
[Ll]ocal
27+
pyvenv.cfg
28+
.venv
29+
pip-selfcheck.json
30+
31+
### Python template
32+
# Byte-compiled / optimized / DLL files
33+
__pycache__/
34+
*.py[cod]
35+
*$py.class
36+
37+
# C extensions
38+
*.so
39+
40+
# Distribution / packaging
41+
.Python
42+
build/
43+
develop-eggs/
44+
dist/
45+
downloads/
46+
eggs/
47+
.eggs/
48+
lib/
49+
lib64/
50+
parts/
51+
sdist/
52+
var/
53+
wheels/
54+
share/python-wheels/
55+
*.egg-info/
56+
.installed.cfg
57+
*.egg
58+
MANIFEST
59+
60+
# PyInstaller
61+
# Usually these files are written by a python script from a template
62+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
63+
*.manifest
64+
*.spec
65+
66+
# Installer logs
67+
pip-log.txt
68+
pip-delete-this-directory.txt
69+
70+
# Unit test / coverage reports
71+
htmlcov/
72+
.tox/
73+
.nox/
74+
.coverage
75+
.coverage.*
76+
.cache
77+
nosetests.xml
78+
coverage.xml
79+
*.cover
80+
*.py,cover
81+
.hypothesis/
82+
.pytest_cache/
83+
cover/
84+
85+
# Translations
86+
*.mo
87+
*.pot
88+
89+
# Django stuff:
90+
*.log
91+
local_settings.py
92+
db.sqlite3
93+
db.sqlite3-journal
94+
95+
# Flask stuff:
96+
instance/
97+
.webassets-cache
98+
99+
# Scrapy stuff:
100+
.scrapy
101+
102+
# Sphinx documentation
103+
docs/_build/
104+
105+
# PyBuilder
106+
.pybuilder/
107+
target/
108+
109+
# Jupyter Notebook
110+
.ipynb_checkpoints
111+
112+
# IPython
113+
profile_default/
114+
ipython_config.py
115+
116+
# pyenv
117+
# For a library or package, you might want to ignore these files since the code is
118+
# intended to run in multiple environments; otherwise, check them in:
119+
# .python-version
120+
121+
# pipenv
122+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
123+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
124+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
125+
# install all needed dependencies.
126+
#Pipfile.lock
127+
128+
# poetry
129+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
130+
# This is especially recommended for binary packages to ensure reproducibility, and is more
131+
# commonly ignored for libraries.
132+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
133+
# poetry.lock
134+
135+
# pdm
136+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
137+
#pdm.lock
138+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
139+
# in version control.
140+
# https://pdm.fming.dev/#use-with-ide
141+
.pdm.toml
142+
143+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
144+
__pypackages__/
145+
146+
# Celery stuff
147+
celerybeat-schedule
148+
celerybeat.pid
149+
150+
# SageMath parsed files
151+
*.sage.py
152+
153+
# Environments
154+
.env
155+
.venv
156+
env/
157+
venv/
158+
ENV/
159+
env.bak/
160+
venv.bak/
161+
162+
# Spyder project settings
163+
.spyderproject
164+
.spyproject
165+
166+
# Rope project settings
167+
.ropeproject
168+
169+
# mkdocs documentation
170+
/site
171+
172+
# mypy
173+
.mypy_cache/
174+
.dmypy.json
175+
dmypy.json
176+
177+
# Pyre type checker
178+
.pyre/
179+
180+
# pytype static type analyzer
181+
.pytype/
182+
183+
# Cython debug symbols
184+
cython_debug/
185+
186+
# PyCharm
187+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
188+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
189+
# and can be added to the global gitignore or merged into this file. For a more nuclear
190+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
191+
.idea/
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Simple FastAPI Project
2+
3+
This is a test project using FastAPI. It is a RESTful API server with user management functionality.
4+
5+
## Features
6+
7+
- User Creation, Read, Update, Delete (CRUD) functionality
8+
- Automatic OpenAPI documentation generation (Swagger UI, ReDoc)
9+
- Custom exception handling
10+
- Test environment with mock data
11+
12+
## Stack
13+
14+
- Python 3.11+
15+
- FastAPI 0.111.1
16+
- Pydantic 2.8.2
17+
- pytest 8.2.2

0 commit comments

Comments
 (0)