Skip to content

Commit

Permalink
feat: add ability in robyn cli to scaffold example programs with vari…
Browse files Browse the repository at this point in the history
…ous DBs (sparckles#584)

* use pyinquire and added example files for various databases

* move Docker file to scaffold/dockerfile and update dockerfile generation in main

* move scaffold app.py files and docker files to named directories in scaffold

---------

Co-authored-by: Sanskar Jethi <sansyrox@gmail.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
3 people authored Oct 30, 2023
1 parent f4a9de0 commit 9f0c23d
Show file tree
Hide file tree
Showing 24 changed files with 347 additions and 57 deletions.
12 changes: 6 additions & 6 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

91 changes: 40 additions & 51 deletions robyn/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,77 +4,66 @@
from InquirerPy.base.control import Choice
from .argument_parser import Config
from robyn.robyn import get_version
from pathlib import Path
import shutil


SCAFFOLD_DIR = Path(__file__).parent / "scaffold"
CURRENT_WORKING_DIR = Path.cwd()


def create_robyn_app():
questions = [
{"type": "input", "message": "Enter the name of the project directory:"},
{
"type": "input",
"message": "Directory Path:",
"name": "directory",
},
{
"type": "list",
"message": "Need Docker? (Y/N)",
"choices": [
Choice("Y", name="Y"),
Choice("N", name="N"),
],
"default": None,
"default": Choice("N", name="N"),
"name": "docker",
},
{
"type": "list",
"message": "Please select project type (Mongo/Postgres/Sqlalchemy/Prisma): ",
"choices": [
Choice("no-db", name="No DB"),
Choice("sqlite", name="Sqlite"),
Choice("postgres", name="Postgres"),
Choice("mongo", name="MongoDB"),
Choice("sqlalchemy", name="SqlAlchemy"),
Choice("prisma", name="Prisma"),
],
"default": Choice("no-db", name="No DB"),
"name": "project_type",
},
]
result = prompt(questions=questions)
project_dir = result[0]
docker = result[1]
project_dir_path = Path(result["directory"]).resolve()
docker = result["docker"]
project_type = result["project_type"]

print(f"Creating a new Robyn project '{project_dir}'...")

# Create a new directory for the project
os.makedirs(project_dir, exist_ok=True)
final_project_dir_path = (CURRENT_WORKING_DIR / project_dir_path).resolve()

# Create the main application file
app_file_path = os.path.join(project_dir, "app.py")
with open(app_file_path, "w") as f:
f.write(
"""
from robyn import Robyn
print(f"Creating a new Robyn project '{final_project_dir_path}'...")

app = Robyn(__file__)
@app.get("/")
def index():
return "Hello World!"
if __name__ == "__main__":
app.start()
"""
)

# Dockerfile configuration
if docker == "Y":
print(f"Generating docker configuration for {project_dir}")
dockerfile_path = os.path.join(project_dir, "Dockerfile")
with open(dockerfile_path, "w") as f:
f.write(
"""
FROM ubuntu:22.04
WORKDIR /workspace
RUN apt-get update -y && apt-get install -y python 3.10 python3-pip
RUN pip install --no-cache-dir --upgrade robyn
COPY ./src/workspace/
# Create a new directory for the project
os.makedirs(final_project_dir_path, exist_ok=True)

EXPOSE 8080
selected_project_template = (SCAFFOLD_DIR / Path(project_type)).resolve()
shutil.copytree(str(selected_project_template), str(final_project_dir_path), dirs_exist_ok=True)

CMD ["python3.10", "/workspace/foo/app.py", "--log-level=DEBUG"]
"""
)
elif docker == "N":
print("Docker not included")
else:
print("Unknown Command")
# If docker is not needed, delete the docker file
if docker == "N":
os.remove(f"{final_project_dir_path}/Dockerfile")

print(f"New Robyn project created in '{project_dir}' ")
print(f"New Robyn project created in '{final_project_dir_path}' ")


def docs():
Expand Down
11 changes: 11 additions & 0 deletions robyn/scaffold/mongo/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
FROM python:3.11-bookworm

WORKDIR /workspace

RUN pip install --no-cache-dir --upgrade -r requirements.txt

COPY . .

EXPOSE 8080

CMD ["python3", "app.py", "--log-level=DEBUG"]
42 changes: 42 additions & 0 deletions robyn/scaffold/mongo/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from pymongo import MongoClient
from robyn import Robyn

app = Robyn(__file__)
db = MongoClient("URL HERE")

users = db.users # define a collection


@app.get("/")
def index():
return "Hello World!"


# create a route
@app.get("/users")
async def get_users():
all_users = await users.find().to_list(length=None)
return {"users": all_users}


# create a route to add a new user
@app.post("/users")
async def add_user(request):
user_data = await request.json()
result = await users.insert_one(user_data)
return {"success": True, "inserted_id": str(result.inserted_id)}


# create a route to fetch a single user by ID
@app.get("/users/{user_id}")
async def get_user(request):
user_id = request.path_params["user_id"]
user = await users.find_one({"_id": user_id})
if user:
return user
else:
return {"error": "User not found"}, 404


if __name__ == "__main__":
app.start(host="0.0.0.0", port=8080)
2 changes: 2 additions & 0 deletions robyn/scaffold/mongo/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
robyn
pymongo
11 changes: 11 additions & 0 deletions robyn/scaffold/no-db/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
FROM python:3.11-bookworm

WORKDIR /workspace

RUN pip install --no-cache-dir --upgrade -r requirements.txt

COPY . .

EXPOSE 8080

CMD ["python3", "app.py", "--log-level=DEBUG"]
12 changes: 12 additions & 0 deletions robyn/scaffold/no-db/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from robyn import Robyn

app = Robyn(__file__)


@app.get("/")
def index():
return "Hello World!"


if __name__ == "__main__":
app.start(host="0.0.0.0", port=8080)
1 change: 1 addition & 0 deletions robyn/scaffold/no-db/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
robyn
32 changes: 32 additions & 0 deletions robyn/scaffold/postgres/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# ---- Build the PostgreSQL Base ----
FROM postgres:latest AS postgres-base

ENV POSTGRES_USER=postgres
ENV POSTGRES_PASSWORD=password
ENV POSTGRES_DB=postgresDB

# ---- Build the Python App ----
FROM python:3.11-bookworm

# Install supervisor
RUN apt-get update && apt-get install -y supervisor

WORKDIR /workspace

COPY requirements.txt requirements.txt
RUN pip install --no-cache-dir --upgrade -r requirements.txt

COPY . .

# Copy PostgreSQL binaries from the first stage
COPY --from=postgres-base /usr/local/bin /usr/local/bin
COPY --from=postgres-base /usr/lib/postgresql /usr/lib/postgresql
COPY --from=postgres-base /usr/share/postgresql /usr/share/postgresql
COPY --from=postgres-base /var/lib/postgresql /var/lib/postgresql

# Add supervisord config
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf

EXPOSE 8080 5455

CMD ["/usr/bin/supervisord"]
30 changes: 30 additions & 0 deletions robyn/scaffold/postgres/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import psycopg2
from robyn import Robyn

DB_NAME = "postgresDB"
DB_HOST = "localhost"
DB_USER = "postgres"
DB_PASS = "password"
DB_PORT = "5455"

conn = psycopg2.connect(database=DB_NAME, host=DB_HOST, user=DB_USER, password=DB_PASS, port=DB_PORT)

app = Robyn(__file__)


# create a route to fetch all users
@app.get("/users")
def get_users():
cursor = conn.cursor()
cursor.execute("SELECT * FROM users")
all_users = cursor.fetchall()
return {"users": all_users}


@app.get("/")
def index():
return "Hello World!"


if __name__ == "__main__":
app.start(url="0.0.0.0", port=8080)
3 changes: 3 additions & 0 deletions robyn/scaffold/postgres/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
robyn
psycopg2; platform_system=="Windows"
psycopg2-binary; platform_system!="Windows"
14 changes: 14 additions & 0 deletions robyn/scaffold/postgres/supervisord.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[supervisord]
nodaemon=true

[program:python-app]
command=python3 /workspace/app.py --log-level=DEBUG
autostart=true
autorestart=true
redirect_stderr=true

[program:postgres]
command=postgres -c 'config_file=/etc/postgresql/postgresql.conf'
autostart=true
autorestart=true
redirect_stderr=true
14 changes: 14 additions & 0 deletions robyn/scaffold/prisma/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
FROM python:3.11-bookworm

WORKDIR /workspace

RUN pip install --no-cache-dir --upgrade -r requirements.txt

COPY . .

RUN python3 -m prisma generate
RUN python3 -m prisma migrate dev --name init

EXPOSE 8080

CMD ["python3", "app.py", "--log-level=DEBUG"]
31 changes: 31 additions & 0 deletions robyn/scaffold/prisma/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from robyn import Robyn
from prisma import Prisma
from prisma.models import User

app = Robyn(__file__)
prisma = Prisma(auto_register=True)


@app.startup_handler
async def startup_handler() -> None:
await prisma.connect()


@app.shutdown_handler
async def shutdown_handler() -> None:
if prisma.is_connected():
await prisma.disconnect()


@app.get("/")
async def h():
user = await User.prisma().create(
data={
"name": "Robert",
},
)
return user.json(indent=2)


if __name__ == "__main__":
app.start(host="0.0.0.0", port=8080)
2 changes: 2 additions & 0 deletions robyn/scaffold/prisma/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
robyn
prisma
13 changes: 13 additions & 0 deletions robyn/scaffold/prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
datasource db {
provider = "sqlite"
url = "file:dev.db"
}

generator py {
provider = "prisma-client-py"
}

model User {
id String @id @default(cuid())
name String
}
11 changes: 11 additions & 0 deletions robyn/scaffold/sqlalchemy/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
FROM python:3.11-bookworm

WORKDIR /workspace

RUN pip install --no-cache-dir --upgrade -r requirements.txt

COPY . .

EXPOSE 8080

CMD ["python3", "app.py", "--log-level=DEBUG"]
Empty file.
Loading

0 comments on commit 9f0c23d

Please sign in to comment.