The first commit

This commit is contained in:
Andros Fenollosa 2022-03-04 11:33:29 +01:00
commit 9996b1e14c
20 changed files with 600 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
static/admin/
static/django_eventstream/

19
Caddyfile Normal file
View File

@ -0,0 +1,19 @@
sse-fake.andros.dev {
root * /usr/src/app/
@notEvents {
not path /events/
}
encode @notEvents gzip
@notStatic {
not path /static/* /media/*
}
reverse_proxy @notStatic django:8000
file_server /static/*
file_server /media/*
}

16
Dockerfile Normal file
View File

@ -0,0 +1,16 @@
# Image
FROM python:3.10
# Display the Python output through the terminal
ENV PYTHONUNBUFFERED: 1
# Set work directory
WORKDIR /usr/src/app
# Add Python dependencies
## Update pip
RUN pip install --upgrade pip
## Copy requirements
COPY requirements.txt ./requirements.txt
## Install requirements
RUN pip3 install -r requirements.txt

57
README.md Normal file
View File

@ -0,0 +1,57 @@
# SSE Fake
Free fake Server-side Events for testing and prototyping.
## Try it
Run this code in JavaScript or from any site:
``` javascript
const sse = new EventSource("https://sse-fake.andros.dev/events/");
sse.onmessage = function(event) {
console.log(event.data);
}
```
Or from the terminal:
``` bash
curl https://sse-fake.andros.dev/events/
```
## Events
Between 1 to 5 seconds, you will randomly receive one of the following messages:
- User connected
``` javascript
{
"action": "User connected",
"name": [random name]
}
```
- User disconnected
``` javascript
{
"action": "User disconnected",
"name": [random name]
}
```
- New message
``` javascript
{
"action": "New message",
"name": [random name],
"text": [random text]
}
```
Made with ♥️, Django, Channels and Django EventStream.
Author: [Andros Fenollosa](https://andros.dev/)

0
app/website/__init__.py Normal file
View File

5
app/website/apps.py Normal file
View File

@ -0,0 +1,5 @@
from django.apps import AppConfig
class SimpleAppConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "app.website"

View File

@ -0,0 +1,95 @@
{% load static %}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<title>SSE Fake</title>
<meta name="description" content="Free fake Server-side Events for testing and prototyping.">
<!-- PrismJS -->
<link href="{% static 'css/prism.css' %}" rel="stylesheet" />
<script defer src="{% static 'js/prism.js' %}"></script>
<!-- End PrismJS -->
<!-- NotifyJS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/notyf@3/notyf.min.css">
<script defer src="https://cdn.jsdelivr.net/npm/notyf@3/notyf.min.js"></script>
<!-- End NotifyJS -->
<!-- Custom CSS and JS-->
<link rel="stylesheet" href="{% static 'css/main.css' %}">
<script defer src="{% static 'js/index.js' %}"></script>
<!-- End Custom CSS and JS-->
<!-- Matomo -->
<script>
var _paq = window._paq = window._paq || [];
/* tracker methods like "setCustomDimension" should be called before "trackPageView" */
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u="//matomo.andros.dev/";
_paq.push(['setTrackerUrl', u+'matomo.php']);
_paq.push(['setSiteId', '8']);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
})();
</script>
<!-- End Matomo Code -->
</head>
<body>
<div class="container">
<header class="header">
<h1 id="sse-fake">SSE Fake</h1>
<p>Free fake Server-side Events for testing and prototyping.</p>
</header>
<main>
<h2 id="try-it">Try it</h2>
<p>Run this code here, in a console or from any site:</p>
<pre>
<code class="language-javascript">
const sse = new EventSource("https://sse-fake.andros.dev/events/");
sse.onmessage = function(event) {
console.log(event.data);
}</code>
</pre>
<p>Or from the terminal:</p>
<pre>
<code class="language-bash">
curl https://sse-fake.andros.dev/events/</code>
</pre>
<h2 id="events">Events</h2>
<p>Between 1 to 5 seconds, you will randomly receive one of the following messages:</p>
<h3>User connected</h3>
<pre>
<code class="lang-javascript">
{
"action": "User connected",
"name": [random name]
}</code>
</pre>
<h3>User disconnected</h3>
<pre>
<code class="lang-javascript">
{
"action": "User disconnected",
"name": [random name]
}</code>
</pre>
<h3>New message</h3>
<pre>
<code class="lang-javascript">
{
"action": "New message",
"name": [random name],
"text": [random text]
}</code>
</pre>
</main>
<footer class="footer">
<p>Made with ♥️, Django, Channels and Django EventStream.</p>
<p>Source: <a href="https://github.com/tanrax/SSE-Fake" target="_blank">GitHub</a></p>
<p>Author: <a href="https://andros.dev" target="_blank">Andros Fenollosa</a></p>
</footer>
</div>
</body>
</html>

5
app/website/views.py Normal file
View File

@ -0,0 +1,5 @@
from django.shortcuts import render
def index(request):
return render(request, "index.html", {})

12
django-launcher.sh Normal file
View File

@ -0,0 +1,12 @@
#!/bin/sh
# Collect static files
python3 manage.py collectstatic --noinput
# Apply database migrations
python3 manage.py migrate
# Start server with debug mode
#python3 manage.py runserver 0.0.0.0:8000
# Start server with production mode
daphne -b 0.0.0.0 -p 8000 sse_fake.asgi:application

48
docker-compose.yml Normal file
View File

@ -0,0 +1,48 @@
version: '3.3'
services:
django:
restart: always
build:
context: ./
dockerfile: ./Dockerfile
entrypoint: bash ./django-launcher.sh
volumes:
- .:/usr/src/app/
environment:
DEBUG: "False"
ALLOWED_HOSTS: "sse-fake.andros.dev"
SECRET_KEY: mysecret
DOMAIN: sse-fake.andros.dev
DOMAIN_URL: https://sse-fake.andros.dev
DB_ENGINE: django.db.backends.sqlite3
DB_NAME: ":memory:"
REDIS_HOST: redis
REDIS_PORT: 6379
STATIC_URL: /static/
STATIC_ROOT: static
MEDIA_URL: /media/
expose:
- 8000
depends_on:
- redis
redis:
restart: always
image: redis:alpine
expose:
- 6379
caddy:
restart: always
image: caddy:alpine
ports:
- 80:80
- 443:443
volumes:
- .:/usr/src/app/
- ./Caddyfile:/etc/caddy/Caddyfile
- ./caddy_data:/data
depends_on:
- django

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", "sse_fake.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()

20
requirements.txt Normal file
View File

@ -0,0 +1,20 @@
# Django
django===4.0
# Django Server
daphne===3.0.2
asgiref===3.4.1
Twisted[tls,http2]
# Manipulate images
Pillow===8.2.0
# Kit utilities
django-extensions===3.1.3
# PostgreSQL driver
psycopg2===2.9.1
# Django Channels
channels==3.0.4
# Redis Layer
channels_redis===3.2.0
# SSE
django-eventstream===4.4.0
# Fake data
faker===13.2.0

0
sse_fake/__init__.py Normal file
View File

62
sse_fake/asgi.py Normal file
View File

@ -0,0 +1,62 @@
# sse_fake/asgi.py
import os
from django.core.asgi import get_asgi_application
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.urls import re_path
import django_eventstream
from django_eventstream import send_event
from faker import Faker
from random import randint
from time import sleep
import threading
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sse_fake.settings")
application = ProtocolTypeRouter(
{
# Django's ASGI application to handle traditional HTTP requests
"http": URLRouter(
[
re_path(
r"^events/",
AuthMiddlewareStack(
URLRouter(django_eventstream.routing.urlpatterns)
),
{"channels": ["events"]},
),
re_path(r"", get_asgi_application()),
]
),
}
)
def send_random_event():
fake = Faker()
while True:
random_event = randint(0, 2)
random_data = ""
if random_event == 0:
# User connected
random_data = {"action": "User connected", "name": fake.first_name()}
elif random_event == 1:
# User disconnected
random_data = {"action": "User disconnected", "name": fake.first_name()}
elif random_event == 2:
# New message
random_data = {
"action": "New message",
"name": fake.first_name(),
"text": fake.text(),
}
send_event(
"events",
"message"
,
random_data,
)
sleep(randint(1, 5))
# Run in other thread send_random_event()
threading.Thread(target=send_random_event).start()

154
sse_fake/settings.py Normal file
View File

@ -0,0 +1,154 @@
"""
Django settings for sse_fake project.
Generated by 'django-admin startproject' using Django 4.0.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
import os
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/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get("SECRET_KEY")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get("DEBUG", "True") == "True"
ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS").split(",")
# Application definition
INSTALLED_APPS = [
"channels",
"django_eventstream",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"app.website",
]
MIDDLEWARE = [
"django_grip.GripMiddleware",
"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 = "sse_fake.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",
],
},
},
]
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": os.environ.get("DB_ENGINE"),
"NAME": os.environ.get("DB_NAME"),
}
}
# Password validation
# https://docs.djangoproject.com/en/4.0/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/4.0/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_ROOT = os.environ.get("STATIC_ROOT")
STATIC_URL = os.environ.get("STATIC_URL")
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = os.environ.get("MEDIA_URL")
DOMAIN = os.environ.get("DOMAIN")
DOMAIN_URL = os.environ.get("DOMAIN_URL")
CSRF_TRUSTED_ORIGINS = [DOMAIN_URL]
"""EMAIL CONFIG"""
DEFAULT_FROM_EMAIL = os.environ.get("EMAIL_ADDRESS")
EMAIL_USE_TLS = os.environ.get("EMAIL_USE_TLS") == "True"
EMAIL_USE_SSL = os.environ.get("EMAIL_USE_SSL") == "True"
EMAIL_HOST = os.environ.get("EMAIL_HOST")
EMAIL_PORT = os.environ.get("EMAIL_PORT")
EMAIL_HOST_USER = os.environ.get("EMAIL_HOST_USER")
EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_HOST_PASSWORD")
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [(os.environ.get("REDIS_HOST"), os.environ.get("REDIS_PORT"))],
},
},
}
ASGI_APPLICATION = "sse_fake.asgi.application"
EVENTSTREAM_ALLOW_ORIGIN = "*"

23
sse_fake/urls.py Normal file
View File

@ -0,0 +1,23 @@
"""sse_fake URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/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
from app.website import views
urlpatterns = [
path("", views.index, name="index"),
path("admin/", admin.site.urls),
]

24
static/css/main.css Normal file
View File

@ -0,0 +1,24 @@
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
padding: 2rem 0;
}
.container {
max-width: 47rem;
margin: 0 auto;
padding: 0 2rem;
}
.header {
text-align: center;
}
a {
color: #0074d9;
text-decoration: none;
}
.footer {
margin-top: 5rem;
text-align: center;
}

3
static/css/prism.css Normal file
View File

@ -0,0 +1,3 @@
/* PrismJS 1.27.0
https://prismjs.com/download.html#themes=prism&languages=markup+css+clike+javascript+bash */
code[class*=language-],pre[class*=language-]{color:#000;background:0 0;text-shadow:0 1px #fff;font-family:Consolas,Monaco,'Andale Mono','Ubuntu Mono',monospace;font-size:1em;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-hyphens:none;-moz-hyphens:none;-ms-hyphens:none;hyphens:none}code[class*=language-] ::-moz-selection,code[class*=language-]::-moz-selection,pre[class*=language-] ::-moz-selection,pre[class*=language-]::-moz-selection{text-shadow:none;background:#b3d4fc}code[class*=language-] ::selection,code[class*=language-]::selection,pre[class*=language-] ::selection,pre[class*=language-]::selection{text-shadow:none;background:#b3d4fc}@media print{code[class*=language-],pre[class*=language-]{text-shadow:none}}pre[class*=language-]{padding:1em;margin:.5em 0;overflow:auto}:not(pre)>code[class*=language-],pre[class*=language-]{background:#f5f2f0}:not(pre)>code[class*=language-]{padding:.1em;border-radius:.3em;white-space:normal}.token.cdata,.token.comment,.token.doctype,.token.prolog{color:#708090}.token.punctuation{color:#999}.token.namespace{opacity:.7}.token.boolean,.token.constant,.token.deleted,.token.number,.token.property,.token.symbol,.token.tag{color:#905}.token.attr-name,.token.builtin,.token.char,.token.inserted,.token.selector,.token.string{color:#690}.language-css .token.string,.style .token.string,.token.entity,.token.operator,.token.url{color:#9a6e3a;background:hsla(0,0%,100%,.5)}.token.atrule,.token.attr-value,.token.keyword{color:#07a}.token.class-name,.token.function{color:#dd4a68}.token.important,.token.regex,.token.variable{color:#e90}.token.bold,.token.important{font-weight:700}.token.italic{font-style:italic}.token.entity{cursor:help}

24
static/js/index.js Normal file
View File

@ -0,0 +1,24 @@
const notyf = new Notyf({
position: {
x: 'right',
y: 'top',
}
});
const sse = new EventSource("/events/");
sse.onmessage = function(event) {
const data = JSON.parse(event.data);
console.log(data);
switch (data.action) {
case 'User connected':
notyf.success(`Connected: ${data.name}`);
break;
case 'User disconnected':
notyf.error(`Disconnected: ${data.name}`);
break;
case 'New message':
notyf.success(`${data.name}: ${data.text.slice(0, 20)}...`);
break;
}
}

8
static/js/prism.js Normal file

File diff suppressed because one or more lines are too long