Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions backend/app/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@


class AppConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'app'
default_auto_field = "django.db.models.BigAutoField"
name = "app"
8 changes: 4 additions & 4 deletions backend/app/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
from . import views

urlpatterns = [
path('build', views.build, name='build'),
path('download', views.download, name='download'),
path('install_block', views.install_block, name='install_block'),
path('installed_blocks', views.installed_blocks, name='installed_blocks'),
path("build", views.build, name="build"),
path("download", views.download, name="download"),
path("install_block", views.install_block, name="install_block"),
path("installed_blocks", views.installed_blocks, name="installed_blocks"),
]
41 changes: 23 additions & 18 deletions backend/app/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import os
from django.conf import settings


@csrf_exempt
def build(request):
try:
Expand All @@ -19,48 +20,52 @@ def build(request):
return HttpResponseBadRequest(e.msg)



def download(request):
return JsonResponse({'status': 'request received'})
return JsonResponse({"status": "request received"})


@csrf_exempt
def install_block(request):
try:
data = json.loads(request.body)
block_name = data.get('package', {}).get('name') or data.get('name', 'Untitled')
custom_blocks_dir = os.path.join(settings.BASE_DIR, 'custom_blocks')
block_name = data.get("package", {}).get("name") or data.get("name", "Untitled")

custom_blocks_dir = os.path.join(settings.BASE_DIR, "custom_blocks")
if not os.path.exists(custom_blocks_dir):
os.makedirs(custom_blocks_dir)

safe_filename = "".join([c for c in block_name if c.isalpha() or c.isdigit() or c in (' ')]).rstrip()

safe_filename = "".join(
[c for c in block_name if c.isalpha() or c.isdigit() or c in (" ")]
).rstrip()
filepath = os.path.join(custom_blocks_dir, f"{safe_filename}.vc3")
with open(filepath, 'w') as f:

with open(filepath, "w") as f:
json.dump(data, f, indent=4)

return JsonResponse({'status': 'success', 'saved_as': os.path.basename(filepath)})

return JsonResponse(
{"status": "success", "saved_as": os.path.basename(filepath)}
)
except Exception as e:
return HttpResponseBadRequest(str(e))


def installed_blocks(request):
try:
custom_blocks_dir = os.path.join(settings.BASE_DIR, 'custom_blocks')
custom_blocks_dir = os.path.join(settings.BASE_DIR, "custom_blocks")
if not os.path.exists(custom_blocks_dir):
return JsonResponse({'blocks': []})
return JsonResponse({"blocks": []})

blocks = []
for filename in os.listdir(custom_blocks_dir):
if filename.endswith('.vc3'):
if filename.endswith(".vc3"):
filepath = os.path.join(custom_blocks_dir, filename)
try:
with open(filepath, 'r') as f:
with open(filepath, "r") as f:
block_data = json.load(f)
blocks.append(block_data)
except Exception as e:
print(f"Failed to load block {filename}: {e}")
return JsonResponse({'blocks': blocks})

return JsonResponse({"blocks": blocks})
except Exception as e:
return HttpResponseBadRequest(str(e))
2 changes: 1 addition & 1 deletion backend/backend/asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@

from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings")

application = get_asgi_application()
105 changes: 52 additions & 53 deletions backend/backend/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,20 @@
BASE_DIR = Path(__file__).resolve().parent.parent

env = environ.Env()
environ.Env.read_env(str(BASE_DIR / '.env'))
environ.Env.read_env(str(BASE_DIR / ".env"))

# Change this to your desired port number
DESIRED_PORT = 8080
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env.str('DJANGO_SECRET_KEY')
SECRET_KEY = env.str("DJANGO_SECRET_KEY")

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env.bool('DJANGO_DEBUG', default=False)
DEBUG = env.bool("DJANGO_DEBUG", default=False)

ALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS', default=['http://localhost:80'])
ALLOWED_HOSTS = env.list("DJANGO_ALLOWED_HOSTS", default=["http://localhost:80"])
# ALLOWED_HOSTS = [
# 'localhost',
# '127.0.0.1',
Expand All @@ -43,56 +43,55 @@
# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',

'corsheaders',
'app',
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"corsheaders",
"app",
]

MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
"corsheaders.middleware.CorsMiddleware",
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = 'backend.urls'
ROOT_URLCONF = "backend.urls"

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]

WSGI_APPLICATION = 'backend.wsgi.application'
WSGI_APPLICATION = "backend.wsgi.application"


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}

Expand All @@ -102,26 +101,26 @@

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]


# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = "en-us"

TIME_ZONE = 'UTC'
TIME_ZONE = "UTC"

USE_I18N = True

Expand All @@ -133,33 +132,33 @@
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = '/static/'
STATIC_URL = "/static/"

STATICFILES_DIRS = [
BASE_DIR / "staticfiles",
]

STATIC_ROOT = 'static'
STATIC_ROOT = "static"

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

if DEBUG:
# Accept a comma-separated list of frontend hosts (e.g. http://localhost:4000)
# Also automatically append standard fallback ports if the primary port gets busy
base_origins = [origin.strip() for origin in env.str('VISUAL_CIRCUIT_FRONTEND_HOST').split(',')]
base_origins = [
origin.strip() for origin in env.str("VISUAL_CIRCUIT_FRONTEND_HOST").split(",")
]
CORS_ALLOWED_ORIGINS = list(base_origins)

# If using localhost:4000, dynamically add 4001 and 4002 as fallbacks
for origin in base_origins:
if origin.endswith(':4000'):
CORS_ALLOWED_ORIGINS.extend([
origin.replace(':4000', ':4001'),
origin.replace(':4000', ':4002')
])

if origin.endswith(":4000"):
CORS_ALLOWED_ORIGINS.extend(
[origin.replace(":4000", ":4001"), origin.replace(":4000", ":4002")]
)

# Allow frontend to read the Content-Disposition header to get the correct .zip filename
CORS_EXPOSE_HEADERS = ['Content-Disposition']
CORS_EXPOSE_HEADERS = ["Content-Disposition"]
4 changes: 2 additions & 2 deletions backend/backend/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
from django.urls import include, path

urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('app.urls')),
path("admin/", admin.site.urls),
path("api/", include("app.urls")),
]
2 changes: 1 addition & 1 deletion backend/backend/wsgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings")

application = get_wsgi_application()
5 changes: 3 additions & 2 deletions backend/manage.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""

import os
import sys


def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
Expand All @@ -18,5 +19,5 @@ def main():
execute_from_command_line(sys.argv)


if __name__ == '__main__':
if __name__ == "__main__":
main()
1 change: 1 addition & 0 deletions backend/staticfiles/synthesis/lib/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@ class InvalidOutputNameException(Exception):
class InvalidInputNameException(Exception):
"""Raised when Input name has not been declared in ports"""


class InvalidParameterNameException(Exception):
"""Raised when Parameter name has not been declared in ports"""
Loading