Req2Poetry
I have a simple FastAPI repo with requirements.txt file
I need to convert to poetry and uv based project. Give me the sample project with conversion code in python
I'll help you create a sample project structure and show how to convert from requirements.txt to Poetry with uv. I'll create an artifact with the necessary code and instructions.
# Project Structure
.
├── README.md
├── requirements.txt
├── convert_to_poetry.py
├── pyproject.toml
└── src
└── app
├── __init__.py
└── main.py
# Original requirements.txt
fastapi==0.109.2
uvicorn==0.27.1
pydantic==2.6.1
python-dotenv==1.0.0
sqlalchemy==2.0.25
# convert_to_poetry.py
import subprocess
import tomli_w
import json
from pathlib import Path
def read_requirements(file_path="requirements.txt"):
"""Read requirements.txt and parse dependencies."""
requirements = []
with open(file_path) as f:
for line in f:
line = line.strip()
if line and not line.startswith("#"):
requirements.append(line)
return requirements
def create_pyproject_toml(dependencies):
"""Create pyproject.toml with Poetry configuration."""
project_config = {
"tool": {
"poetry": {
"name": "fastapi-project",
"version": "0.1.0",
"description": "FastAPI project converted to Poetry",
"authors": ["Your Name <your.email@example.com>"],
"dependencies": {},
"group": {
"dev": {
"dependencies": {
"black": "^23.12.1",
"isort": "^5.13.2",
"mypy": "^1.8.0",
"ruff": "^0.1.15"
}
}
}
}
},
"build-system": {
"requires": ["poetry-core"],
"build-backend": "poetry.core.masonry.api"
}
}
# Parse dependencies from requirements.txt
for dep in dependencies:
name, version = dep.split("==")
project_config["tool"]["poetry"]["dependencies"][name] = f"^{version}"
# Add Python dependency
project_config["tool"]["poetry"]["dependencies"]["python"] = "^3.9"
# Write pyproject.toml
with open("pyproject.toml", "wb") as f:
tomli_w.dump(project_config, f)
def main():
# Install required tools
print("Installing Poetry and UV...")
subprocess.run(["pip", "install", "poetry", "uv"], check=True)
# Read requirements
requirements = read_requirements()
# Create pyproject.toml
create_pyproject_toml(requirements)
# Initialize Poetry project
print("Initializing Poetry project...")
subprocess.run(["poetry", "install"], check=True)
# Configure Poetry to use UV as installer
print("Configuring Poetry to use UV...")
subprocess.run(["poetry", "config", "installer.modern-installation", "true"], check=True)
# Create source directory structure
Path("src/app").mkdir(parents=True, exist_ok=True)
# Create main.py
main_py_content = '''from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
'''
with open("src/app/main.py", "w") as f:
f.write(main_py_content)
# Create __init__.py
Path("src/app/__init__.py").touch()
print("Conversion completed successfully!")
if __name__ == "__main__":
main()
# README.md
# FastAPI Poetry Project
This project has been converted from a requirements.txt-based setup to use Poetry with UV as the package installer.
## Setup
1. Make sure you have Python 3.9+ installed
2. Run the conversion script:
```bash
python convert_to_poetry.py
```
## Development
- Install dependencies: `poetry install`
- Run the FastAPI server: `poetry run uvicorn src.app.main:app --reload`
- Format code: `poetry run black .`
- Sort imports: `poetry run isort .`
- Lint code: `poetry run ruff check .`
- Type check: `poetry run mypy .`
## Using UV with Poetry
This project uses UV as the installer backend for Poetry. UV is a fast, reliable Python package installer and resolver written in Rust.
Key benefits:
- Faster dependency resolution
- More reliable installations
- Better handling of pre-built wheels
To update dependencies:
```bash
poetry update
```
To add new dependencies:
```bash
poetry add package-name
```
## Project Structure
The project follows a clean architecture:
```
.
├── pyproject.toml # Project configuration
├── src/ # Source code directory
│ └── app/ # Application package
│ ├── __init__.py
│ └── main.py # FastAPI application
└── README.md
```Last updated