Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Django example #11

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
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
7 changes: 7 additions & 0 deletions examples/django/frontend/css/bootstrap.min.css

Large diffs are not rendered by default.

41 changes: 41 additions & 0 deletions examples/django/frontend/css/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
body{
background: #eeeeee;
}

.todo{
padding: 30px 0;
}

.todo-card{
border-radius: 4px;
background: #fff;
height: 100%;
padding: 20px;
}


.todo-box{
padding: 10px;
}

.todo-box h6{
padding: 30px;
border: 2px solid #000;
margin-top: 5px;
}

.todo-box .btn-delete{
padding: 10px;
width: 100px;
height: 80px;
margin-top: 5px;
}

.todo-box .btn-add{
padding: 10px;
width: 100px;
height: 50px;
margin-top: 4px;

}

59 changes: 59 additions & 0 deletions examples/django/frontend/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pyscript Todo</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>


</head>
<body>
<py-env>
- autoclose_loader: true
- runtimes:
-
src: "/pyodide.js"
name: pyodide-0.20
lang: python
- paths:
- script/app.py
</py-env>
<section class="todo">
<div class="container">
<div class="row justify-content-center mt-5">
<div class="col-lg-8 text-center">
<h2 class="lead">Pyscript App</h2>
</div>

<div class="col-lg-6 mt-5">
<div class="todo-card">
<div class="t-line">
<div class="todo-box" >
<div class="row" id="todo-row">
<div class="form-group">
<input type="text" name="addtodo" id="taskadd" class="form-control">
<button pys-onClick="create" id="add" type="button" class="btn shadow-none mt-2 btn-outline-light btn-add btn-primary" >Add</button>
</div>

</div>
</div>
</div>

</div>
</div>

</div>
</div>
</section>
<py-script>
from app import GetTasks,delete,create
from pyodide import create_proxy

</py-script>

</body>
</html>
73 changes: 73 additions & 0 deletions examples/django/frontend/script/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import json
import asyncio
from pyodide.http import pyfetch
from pyodide import JsException,create_proxy
import js



async def GetTasks():
response = await pyfetch(
url="http://127.0.0.1:8000/",
method="GET",
headers={"Content-Type": "application/json"},
)
if response.ok:
data = await response.json()
parent = js.document.querySelector("#todo-row")
js.document.querySelector('#taskadd').value =""
before_child = js.document.querySelectorAll(".task-test")
before_child2 = js.document.querySelectorAll("#del")
if before_child and before_child2:
for b in before_child:
b.remove()
for c in before_child2:
c.remove()
i=0
for t in data:
i +=1
html_data =js.document.createElement("h6")
html_data.className = "task-test col-8"
html_data.innerHTML = t["task"]
parent.appendChild(html_data)
button=js.document.createElement("button")
button.className = "btn btn-delete btn-outline-light btn-danger col-4"
button.innerHTML = "Delete"
button.value = t["id"]
button.setAttribute("id", "del")
button.addEventListener("click", create_proxy(delete))
parent.appendChild(button)





async def create(e):
task = js.document.querySelector('#taskadd').value
response = await pyfetch(
url=f"http://127.0.0.1:8000/",
method="POST",
headers={"Content-Type": "application/json"},
body = json.dumps({
"task":task
})
)
loop = asyncio.get_event_loop()
loop.run_until_complete(GetTasks())


async def delete(e):
id = e.target.value
response = await pyfetch(
url=f"http://127.0.0.1:8000/delete/{id}",
method="DELETE",
headers={"Content-Type": "application/json"},

)
loop = asyncio.get_event_loop()
loop.run_until_complete(GetTasks())



loop = asyncio.get_event_loop()
loop.run_until_complete(GetTasks())
Empty file.
5 changes: 5 additions & 0 deletions examples/django/todo/app/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.contrib import admin
from .models import Todo
# Register your models here.

admin.site.register(Todo)
6 changes: 6 additions & 0 deletions examples/django/todo/app/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class AppConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'app'
22 changes: 22 additions & 0 deletions examples/django/todo/app/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Generated by Django 4.0.5 on 2022-06-30 19:20

from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
migrations.CreateModel(
name='Todo',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('task', models.CharField(max_length=500)),
('created_on', models.DateTimeField(auto_now_add=True)),
],
),
]
Empty file.
11 changes: 11 additions & 0 deletions examples/django/todo/app/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@

from django.db import models

# Create your models here.

class Todo(models.Model):
task = models.CharField(max_length=500)
created_on = models.DateTimeField(auto_now_add=True)

def __str__(self):
return self.task
11 changes: 11 additions & 0 deletions examples/django/todo/app/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@

from pyexpat import model
from rest_framework import serializers
from .models import Todo



class TodoSerializer(serializers.ModelSerializer):
class Meta:
model = Todo
fields = '__all__'
3 changes: 3 additions & 0 deletions examples/django/todo/app/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
7 changes: 7 additions & 0 deletions examples/django/todo/app/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from django.urls import path, include
from . import views

urlpatterns = [
path('', views.GetTodo),
path('delete/<int:id>', views.DeleteTodo),
]
38 changes: 38 additions & 0 deletions examples/django/todo/app/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.http import HttpResponse
from .serializers import TodoSerializer
from .models import Todo
# Create your views here.
@api_view(["GET", "POST"])
def GetTodo(request):
if request.method == "GET":
try:
todo = Todo.objects.all()
except:
return HttpResponse(status = 404)
serializer = TodoSerializer(todo, many=True)
return Response(serializer.data)
if request.method == "POST":
print(request.data)
serializer = TodoSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return HttpResponse(status=201)

@api_view(["DELETE"])
def DeleteTodo(request,id):
if request.method == "DELETE":
try:
todo = Todo.objects.get(pk=id)
except:
return HttpResponse(status = 404)
data ={}
operation = todo.delete()
if operation:
data["success"] = "deleted"
return Response(data)
else:
data["success"] = "error"

Binary file added examples/django/todo/db.sqlite3
Binary file not shown.
22 changes: 22 additions & 0 deletions examples/django/todo/manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/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', 'todo.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)


if __name__ == '__main__':
main()
Empty file.
16 changes: 16 additions & 0 deletions examples/django/todo/todo/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
ASGI config for todo project.

It exposes the ASGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'todo.settings')

application = get_asgi_application()
Loading