initialized frontend and api

This commit is contained in:
Rushil Umaretiya 2020-12-30 21:37:04 -05:00
commit 2238bd403c
No known key found for this signature in database
GPG Key ID: 4E8FAF9C926AF959
40 changed files with 3789 additions and 0 deletions

155
.gitignore vendored Normal file
View File

@ -0,0 +1,155 @@
ngo #
*.log
*.pot
*.pyc
__pycache__
db.sqlite3
media
# Backup files #
*.bak
# If you are using PyCharm #
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/dictionaries
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.xml
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/gradle.xml
.idea/**/libraries
*.iws /out/
# Python #
*.py[cod]
*$py.class
# Distribution / packaging
.Python build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
.pytest_cache/
nosetests.xml
coverage.xml
*.cover
.hypothesis/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery
celerybeat-schedule.*
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# mkdocs documentation
/site
# mypy
.mypy_cache/
# Sublime Text #
*.tmlanguage.cache
*.tmPreferences.cache
*.stTheme.cache
*.sublime-workspace
*.sublime-project
# sftp configuration file
sftp-config.json
# Package control specific files Package
Control.last-run
Control.ca-list
Control.ca-bundle
Control.system-ca-bundle
GitHub.sublime-settings
# Visual Studio Code #
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history
.DS_STORE
node_modules
scripts/flow/*/.flowconfig
.flowconfig
*~
*.pyc
.grunt
_SpecRunner.html
__benchmarks__
build/
remote-repo/
coverage/
.module-cache
fixtures/dom/public/react-dom.js
fixtures/dom/public/react.js
test/the-files-to-test.generated.js
*.log*
chrome-user-data
*.sublime-project
*.sublime-workspace
.idea
*.iml
.vscode
*.swp
*.swo
packages/react-devtools-core/dist
packages/react-devtools-extensions/chrome/build
packages/react-devtools-extensions/chrome/*.crx
packages/react-devtools-extensions/chrome/*.pem
packages/react-devtools-extensions/firefox/build
packages/react-devtools-extensions/firefox/*.xpi
packages/react-devtools-extensions/firefox/*.pem
packages/react-devtools-extensions/shared/build
packages/react-devtools-extensions/.tempUserDataDir
packages/react-devtools-inline/dist
packages/react-devtools-shell/dist
packages/react-devtools-scheduling-profiler/dist

13
Pipfile Normal file
View File

@ -0,0 +1,13 @@
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true
[dev-packages]
[packages]
django = "*"
djangorestframework = "*"
[requires]
python_version = "3.8"

59
Pipfile.lock generated Normal file
View File

@ -0,0 +1,59 @@
{
"_meta": {
"hash": {
"sha256": "b890b2061eb6fc1d8bf94ed78d77990ac519683b06b3819184b0effc5cedbd47"
},
"pipfile-spec": 6,
"requires": {
"python_version": "3.8"
},
"sources": [
{
"name": "pypi",
"url": "https://pypi.org/simple",
"verify_ssl": true
}
]
},
"default": {
"asgiref": {
"hashes": [
"sha256:5ee950735509d04eb673bd7f7120f8fa1c9e2df495394992c73234d526907e17",
"sha256:7162a3cb30ab0609f1a4c95938fd73e8604f63bdba516a7f7d64b83ff09478f0"
],
"markers": "python_version >= '3.5'",
"version": "==3.3.1"
},
"django": {
"hashes": [
"sha256:5c866205f15e7a7123f1eec6ab939d22d5bde1416635cab259684af66d8e48a2",
"sha256:edb10b5c45e7e9c0fb1dc00b76ec7449aca258a39ffd613dbd078c51d19c9f03"
],
"index": "pypi",
"version": "==3.1.4"
},
"djangorestframework": {
"hashes": [
"sha256:0209bafcb7b5010fdfec784034f059d512256424de2a0f084cb82b096d6dd6a7"
],
"index": "pypi",
"version": "==3.12.2"
},
"pytz": {
"hashes": [
"sha256:3e6b7dd2d1e0a59084bcee14a17af60c5c562cdc16d828e8eba2e683d3a7e268",
"sha256:5c55e189b682d420be27c6995ba6edce0c0a77dd67bfbe2ae6607134d5851ffd"
],
"version": "==2020.4"
},
"sqlparse": {
"hashes": [
"sha256:017cde379adbd6a1f15a61873f43e8274179378e95ef3fede90b5aa64d304ed0",
"sha256:0f91fd2e829c44362cbcfab3e9ae12e22badaa8a29ad5ff599f9ec109f0454e8"
],
"markers": "python_version >= '3.5'",
"version": "==0.4.1"
}
},
"develop": {}
}

0
api/__init__.py Normal file
View File

5
api/admin.py Normal file
View File

@ -0,0 +1,5 @@
from django.contrib import admin
from . import models
# Register your models here.
admin.site.register(models.Room)

5
api/apps.py Normal file
View File

@ -0,0 +1,5 @@
from django.apps import AppConfig
class ApiConfig(AppConfig):
name = 'api'

View File

@ -0,0 +1,25 @@
# Generated by Django 3.1.4 on 2020-12-19 18:02
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Room',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('code', models.CharField(default='', max_length=8, unique=True)),
('host', models.CharField(max_length=50, unique=True)),
('guest_can_pause', models.BooleanField(default=False)),
('votes_to_skip', models.IntegerField(default=0)),
('created_at', models.DateTimeField(auto_now_add=True)),
],
),
]

View File

24
api/models.py Normal file
View File

@ -0,0 +1,24 @@
from django.db import models
import string
import random
def generate_unique_code():
length = 6
while True:
code = ''.join(random.choices(string.ascii_uppercase, k=length))
if Room.objects.filter(code=code).count() == 0:
break
return code
# Create your models here.
class Room(models.Model):
code = models.CharField(max_length=8, default="", unique=True)
host = models.CharField(max_length=50, unique=True)
guest_can_pause = models.BooleanField(null=False, default=False)
votes_to_skip = models.IntegerField(null=False, default=0)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'Room ({self.code}'

7
api/serializers.py Normal file
View File

@ -0,0 +1,7 @@
from rest_framework import serializers
from .models import Room
class RoomSerializer(serializers.ModelSerializer):
class Meta:
model = Room
fields = ('id', 'code', 'host', 'guest_can_pause', 'votes_to_skip', 'created_at')

3
api/tests.py Normal file
View File

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

6
api/urls.py Normal file
View File

@ -0,0 +1,6 @@
from django.urls import path
from . import views
urlpatterns = [
path('rooms', views.RoomView.as_view(), name="rooms")
]

16
api/views.py Normal file
View File

@ -0,0 +1,16 @@
from django.shortcuts import render
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from .serializers import RoomSerializer
from .models import Room
# Create your views here.
class RoomView(CreateAPIView):
queryset = Room.objects.all()
serializer_class = RoomSerializer
def get(self, request, format=None):
rooms = Room.objects.all()
serializer = RoomSerializer(rooms, many=True)
return Response(serializer.data)

0
config/__init__.py Normal file
View File

16
config/asgi.py Normal file
View File

@ -0,0 +1,16 @@
"""
ASGI config for config 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/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
application = get_asgi_application()

125
config/settings.py Normal file
View File

@ -0,0 +1,125 @@
"""
Django settings for config project.
Generated by 'django-admin startproject' using Django 3.1.4.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'j3vvnw0w=s-5c^(-(w7dy#8%c)7rj3@i@-ik5b_u)da!@3h6t('
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'api',
'frontend',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
]
MIDDLEWARE = [
'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 = 'config.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',
],
},
},
]
WSGI_APPLICATION = 'config.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'

23
config/urls.py Normal file
View File

@ -0,0 +1,23 @@
"""config URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('api.urls')),
path('', include('frontend.urls'))
]

16
config/wsgi.py Normal file
View File

@ -0,0 +1,16 @@
"""
WSGI config for config project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
application = get_wsgi_application()

0
frontend/__init__.py Normal file
View File

3
frontend/admin.py Normal file
View File

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

5
frontend/apps.py Normal file
View File

@ -0,0 +1,5 @@
from django.apps import AppConfig
class FrontendConfig(AppConfig):
name = 'frontend'

View File

@ -0,0 +1,14 @@
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": "10"
}
}
],
"@babel/preset-react"
],
"plugins": ["@babel/plugin-proposal-class-properties"]
}

View File

3
frontend/models.py Normal file
View File

@ -0,0 +1,3 @@
from django.db import models
# Create your models here.

36
frontend/package.json Normal file
View File

@ -0,0 +1,36 @@
{
"name": "frontend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "webpack --mode development --watch",
"build": "webpack --mode production"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.12.10",
"@babel/preset-env": "^7.12.11",
"@babel/preset-react": "^7.12.10",
"babel-loader": "^8.2.2",
"eslint": "^7.16.0",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"webpack": "^5.11.0",
"webpack-cli": "^4.2.0"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"dependencies": {
"@babel/plugin-proposal-class-properties": "^7.12.1",
"@material-ui/core": "^4.11.2",
"@material-ui/icons": "^4.11.2",
"react-router-dom": "^5.2.0"
}
}

47
frontend/src/App.js Normal file
View File

@ -0,0 +1,47 @@
import React, { useEffect, useState } from "react";
import Hello from "./components/Hello";
import { useFetch } from "./useFetch";
import { useForm } from "./useForm";
const App = (props) => {
const [values, handleChange] = useForm({
firstName: "",
email: "",
password: "",
});
const [count, setCount] = useState(0);
const { data, loading } = useFetch(`http://numbersapi.com/${count}/math`);
return (
<>
<div>{!data ? "loading..." : data}</div>
<div>count = {count}</div>
<button onClick={() => setCount((c) => c + 1)}>increment</button>
{/* <button onClick={() => setShowHello(!showHello)}>show/hide</button> */}
{/* {showHello && <Hello />} */}
<div>
<input
name="email"
placeholder="email"
value={values.email}
onChange={handleChange}
/>
<input
name="firstName"
placeholder="first name"
value={values.firstName}
onChange={handleChange}
/>
<input
type="password"
placeholder="password"
name="password"
value={values.password}
onChange={handleChange}
/>
</div>
</>
);
};
export default App;

View File

@ -0,0 +1,15 @@
import React, { useEffect } from "react";
function Hello(props) {
useEffect(() => {
console.log("bruh");
return () => {
console.log("unmounted!");
};
}, []);
return <div>Hey!</div>;
}
export default Hello;

5
frontend/src/index.js Normal file
View File

@ -0,0 +1,5 @@
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
ReactDOM.render(<App />, document.getElementById("root"));

15
frontend/src/useFetch.js Normal file
View File

@ -0,0 +1,15 @@
import { useEffect, useState } from "react";
export const useFetch = (url) => {
const [state, setState] = useState({ data: null, loading: true });
useEffect(() => {
setState((state) => ({ data: state.data, loading: true }));
fetch(url)
.then((x) => x.text())
.then((y) => {
setState({ data: y, loading: false });
});
}, []);
return state;
};

15
frontend/src/useForm.js Normal file
View File

@ -0,0 +1,15 @@
import { useState } from "react";
export const useForm = (initialValues) => {
const [values, setValues] = useState(initialValues);
return [
values,
(e) => {
setValues({
...values,
[e.target.name]: e.target.value,
});
},
];
};

View File

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,47 @@
/*!********************!*\
!*** ./src/App.js ***!
\********************/
/*!**********************!*\
!*** ./src/index.js ***!
\**********************/
/*!************************!*\
!*** ./src/useForm.js ***!
\************************/
/*!*************************!*\
!*** ./src/useFetch.js ***!
\*************************/
/*!*********************************!*\
!*** ./src/components/Hello.js ***!
\*********************************/
/*!*************************************!*\
!*** ./node_modules/react/index.js ***!
\*************************************/
/*!*****************************************!*\
!*** ./node_modules/react-dom/index.js ***!
\*****************************************/
/*!*****************************************!*\
!*** ./node_modules/scheduler/index.js ***!
\*****************************************/
/*!*********************************************!*\
!*** ./node_modules/object-assign/index.js ***!
\*********************************************/
/*!********************************************************!*\
!*** ./node_modules/react/cjs/react.production.min.js ***!
\********************************************************/
/*!****************************************************************!*\
!*** ./node_modules/react-dom/cjs/react-dom.production.min.js ***!
\****************************************************************/
/*!****************************************************************!*\
!*** ./node_modules/scheduler/cjs/scheduler.production.min.js ***!
\****************************************************************/

View File

@ -0,0 +1,35 @@
{% load static %}
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]> <html class="no-js"> <!--<![endif]-->
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>House Party</title>
<meta name="description" content="House Party music controller." />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
rel="stylesheet"
type="text/css"
href="{% static 'css/index.css' %}"
/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
/>
</head>
<body>
<!--[if lt IE 7]>
<p class="browsehappy">
You are using an <strong>outdated</strong> browser. Please
<a href="#">upgrade your browser</a> to improve your experience.
</p>
<![endif]-->
<div id="root"></div>
<script src="{% static 'frontend/main.js' %}"></script>
</body>
</html>

3
frontend/tests.py Normal file
View File

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

6
frontend/urls.py Normal file
View File

@ -0,0 +1,6 @@
from django.urls import path
from . import views
urlpatterns = [
path('', views.index)
]

6
frontend/views.py Normal file
View File

@ -0,0 +1,6 @@
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return render(request, 'frontend/index.html')

View File

@ -0,0 +1,32 @@
const path = require("path");
const webpack = require("webpack");
module.exports = {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "./static/frontend"),
filename: "[name].js",
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
],
},
optimization: {
minimize: true,
},
plugins: [
new webpack.DefinePlugin({
"process.env": {
// This has effect on the react lib size
NODE_ENV: JSON.stringify("production"),
},
}),
],
};

2980
frontend/yarn.lock Normal file

File diff suppressed because it is too large Load Diff

22
manage.py Executable file
View File

@ -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', 'config.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()