Compare commits

..
17 Commits
25 changed files with 567 additions and 1 deletions

No files matched your search

+7
View File
@@ -102,3 +102,10 @@ venv.bak/
# mypy
.mypy_cache/
# vscode
.vscode/
# merge orig files
*.orig
+2 -1
View File
@@ -1,4 +1,5 @@
#!/usr/bin/env python3
#coding=utf-8
from http import server
from urllib import parse
@@ -31,7 +32,7 @@ class SimpleHandler(server.BaseHTTPRequestHandler):
msg = "Invalid number of Query Components! Two components needed."
else:
if query_components[0][0] != 'von' or query_components[1][0] != 'bis':
msg = "Invalid Query Components! First key has to be 'von', second key 'bis'."
msg = "Invalid Query Components! First key should be 'von', second key 'bis'."
self.wfile.write(msg.encode('utf-8'))
else:
try:
Executable
+21
View File
@@ -0,0 +1,21 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'news.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()
View File
Whitespace-only changes.
+17
View File
@@ -0,0 +1,17 @@
from channels.routing import ProtocolTypeRouter, URLRouter
from django.urls import re_path
from channels.routing import URLRouter
from channels.http import AsgiHandler
from channels.auth import AuthMiddlewareStack
import django_eventstream
urlpatterns = [
re_path(r'^events/',
AuthMiddlewareStack(URLRouter(django_eventstream.routing.urlpatterns)),
{'channels': ['notice']}),
re_path(r'', AsgiHandler),
]
application = ProtocolTypeRouter({
'http': URLRouter(urlpatterns),
})
+129
View File
@@ -0,0 +1,129 @@
"""
Django settings for news project.
Generated by 'django-admin startproject' using Django 2.2.6.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#n@1*#)p6oham=)l^uw!bnwn^$#z2x19do%@97$cwv)ab-8z*e'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'posts.apps.PostsConfig',
'rest_framework',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'channels',
'django_eventstream',
]
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',
'django_grip.GripMiddleware',
'django.middleware.security.SecurityMiddleware',
]
ROOT_URLCONF = 'news.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates')
],
'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 = 'news.wsgi.application'
ASGI_APPLICATION = 'news.routing.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/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/2.2/topics/i18n/
LANGUAGE_CODE = 'de-de'
TIME_ZONE = 'Europe/Berlin'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
+24
View File
@@ -0,0 +1,24 @@
"""news URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/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
from. import views
urlpatterns = [
path('', views.index, name="index"),
path('posts/', include('posts.urls')),
path('admin/', admin.site.urls),
]
+15
View File
@@ -0,0 +1,15 @@
from django.shortcuts import render
from django.http import HttpResponse
logger = None
def init_loger():
global logger
if not logger:
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler)
# Create your views here.
def index(request):
return render(request, 'news/index.html')
+16
View File
@@ -0,0 +1,16 @@
"""
WSGI config for news 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/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'news.settings')
application = get_wsgi_application()
View File
Whitespace-only changes.
+3
View File
@@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.
+5
View File
@@ -0,0 +1,5 @@
from django.apps import AppConfig
class PostsConfig(AppConfig):
name = 'posts'
+29
View File
@@ -0,0 +1,29 @@
from django import forms
import datetime
class NoticeForm(forms.Form):
date_formats = ['%d.%m.%Y', '%d.%m.%y']
title = forms.CharField(label='Titel', max_length=80)
text = forms.CharField(label='Text', max_length=400)
start = forms.DateField(label='Von',
input_formats=date_formats,
initial=datetime.date.today)
end = forms.DateField(label='Bis',
input_formats=date_formats,
initial=datetime.datetime.today() + datetime.timedelta(days=1))
class EditNoticeForm(forms.Form):
def __init__(self, *args, **kwargs):
self.title = forms.CharField(label='Titel',
max_length=80,
initial=kwargs.pop('notice_title'))
self.text = forms.CharField(label='Text',
max_length=400,
initial=kwargs.pop('notice_text'))
self.start = forms.DateField(label='Von',
initial=kwargs.pop('notice.pub_start'),
input_formats=NoticeForm.date_formats)
self.end = forms.DateField(label='Bis',
initial=kwargs.pop('pub_end'),
input_formats=NoticeForm.date_formats)
super(EditNoticeForm, self).__init__(*args, **kwargs)
+24
View File
@@ -0,0 +1,24 @@
# Generated by Django 2.2.6 on 2019-11-19 12:29
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Notice',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('notice_title', models.CharField(max_length=80)),
('notice_text', models.CharField(max_length=400)),
('pub_start', models.DateTimeField()),
('pub_end', models.DateTimeField()),
],
),
]
View File
Whitespace-only changes.
+8
View File
@@ -0,0 +1,8 @@
from django.db import models
# Create your models here.
class Notice(models.Model):
notice_title = models.CharField(max_length=80)
notice_text = models.CharField(max_length=400)
pub_start = models.DateTimeField()
pub_end = models.DateTimeField()
+8
View File
@@ -0,0 +1,8 @@
from rest_framework import serializers
from .models import Notice
class NoticeSerializer(serializers.ModelSerializer):
class Meta:
model = Notice
fields = ('id', 'notice_title', 'notice_text', 'pub_start', 'pub_end')
+3
View File
@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.
+12
View File
@@ -0,0 +1,12 @@
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='posts'),
path('new', views.new, name='new'),
path('delete/<int:deleteId>', views.delete, name='delete'),
path('edit/<int:editId>', views.edit, name='edit'),
path('notices/', views.notice_list),
path('notices/<int:id>/', views.notice_detail),
]
+133
View File
@@ -0,0 +1,133 @@
import logging
from django.shortcuts import render, redirect, render_to_response
from django.http import HttpResponse, JsonResponse
from django.utils import timezone
from django.contrib import messages
from django.views.decorators.csrf import csrf_exempt
from django_eventstream import send_event
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from .models import Notice
from .forms import NoticeForm, EditNoticeForm
from .serializers import NoticeSerializer
logger = None
def init_loger(logger_type):
global logger
if logger == None:
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
# Create your views here.
def index(request):
init_loger('django.db.backends')
notices = Notice.objects.all()
notices = Notice.objects.filter(pub_start__lte=timezone.now(), pub_end__gte=timezone.now())
message = ""
context = {
"notices": notices,
'message': message,
}
return render(request, 'posts/index.html', context)
#@login_required
def new(request):
if request.method == "POST":
form = NoticeForm(request.POST)
if form.is_valid():
newNotice = Notice(notice_title=form.cleaned_data['title'],
notice_text=form.cleaned_data['text'],
pub_start=form.cleaned_data['start'],
pub_end=form.cleaned_data['end'])
newNotice.save()
send_event('notice', 'message', newNotice.id)
return redirect('posts')
context = {'form' : NoticeForm()}
return render(request, 'posts/edit.html', context)
def delete(request, deleteId=None):
init_loger(__name__)
logger.info(deleteId)
message = ""
if deleteId:
delNotice = Notice.objects.get(id=deleteId)
if delNotice:
delNotice.delete()
message = "Notice has been deleted."
send_event('notice', 'message', "Notice has been deleted.")
return redirect('posts')
def edit(request, editId=None):
init_loger(__name__)
logger.debug(editId)
logger.debug(request.method)
editNotice = None
if editId:
editNotice = Notice.objects.get(id=editId)
logger.debug(editNotice)
if editNotice:
form = EditNoticeForm(editNotice)
#form.title = editNotice.notice_title
#form.notice_to_form(editNotice)
logger.info(form)
#if form.is_valid():
# return HttpResponse(status=204)
context = {'form' : form}
return render(request, 'posts/edit.html', context)
"""
newNotice = Notice(notice_title=form.cleaned_data['title'],
notice_text=form.cleaned_data['text'],
pub_start=form.cleaned_data['start'],
pub_end=form.cleaned_data['end'])
newNotice.save()
send_event('notice', 'message', newNotice.id)
return redirect('posts')
"""
@csrf_exempt
def notice_list(request):
if request.method == 'GET':
notices = Notice.objects.all()
serializer = NoticeSerializer(notices, many=True)
return JsonResponse(serializer.data, safe=False)
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = NoticeSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
@csrf_exempt
def notice_detail(request, id):
try:
notice = Notice.objects.get(id=id)
except Notice.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = NoticeSerializer(notice)
return JsonResponse(serializer.data)
elif request.method == 'PUT':
data = JSONParser().parse(request)
serializer = NoticeSerializer(notice, data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=400)
elif request.method == 'DELETE':
notice.delete()
return HttpResponse(status=204)
+20
View File
@@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %} Placeholder {% endblock %}</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
{% load static %}
<script src="{% static 'django_eventstream/eventsource.min.js' %}"></script>
<script src="{% static 'django_eventstream/reconnecting-eventsource.js' %}"></script>
</head>
<body>
{% include 'navbar.html' %}
{% block content %} Placeholder {% endblock %}
</body>
</html>
+19
View File
@@ -0,0 +1,19 @@
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Menu</a>
<div id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="{% url 'index' %}">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'posts' %}">Posts</a>
</li>
<li class="nav-item">
<a class="nav-link" href="https://www.th-nuernberg.de/fakultaeten/efi/">EFI</a>
</li>
<li class="nav-item">
<a class="nav-link" href="https://www.google.com">Google</a>
</li>
</ul>
</div>
</nav>
+13
View File
@@ -0,0 +1,13 @@
{% extends 'base.html' %}
{% block title %}
Index
{% endblock %}
{% block content %}
<div class="jumbotron">
<h1 class="display-4">Index of News App</h1>
<p class="lead">Some placeholder Text</p>
</div>
{% endblock %}
+18
View File
@@ -0,0 +1,18 @@
{% extends 'base.html' %}
{% block title %}
Index
{% endblock %}
{% block content %}
<div class=container>
<h1 class="display-4">New Message</h1>
<form method="POST">
<div class="form-group">
{% csrf_token %}{{ form.as_p }}
</div>
<button type="submit" class="save btn btn-default">Speichern</button>
</form>
</div>
{% endblock %}
+41
View File
@@ -0,0 +1,41 @@
{% extends 'base.html' %}
{% block title %}
Index
{% endblock %}
{% block content %}
<script>
var es = new ReconnectingEventSource('/events/');
es.addEventListener('message', function (e) {console.log(e.data); location.reload();});
</script>
<div class=container>
<h1 class="display-4">Your Posts</h1>
<div class=container>
{% for notice in notices %}
<div class="jumbotron">
<h3>{{ notice.notice_title }}</h3>
<p>{{ notice.notice_text }}</p>
<p>
<a href="{% url 'delete' deleteId=notice.id %}" class="btn btn-danger" role="button">Delete</a>
<a href="{% url 'edit' editId=notice.id %}" class="btn btn-info" role="button">Edit</a>
</p>
{% if message %}
<script>
alert('{{ message }}');
</script>
{% endif %}
</div>
{% endfor %}
<div class=container>
<p><a href="{% url 'new' %}" class="btn btn-info" role="button">Neue Nachricht</a></p>
</div>
</div>
<!--p class="lead">Some placeholder Text</p-->
</div>
{% endblock %}