diff --git a/README.md b/README.md index 5becb7a..7414d68 100644 --- a/README.md +++ b/README.md @@ -7,5 +7,6 @@ into the ungleich clearning circle. * [Balazs](https://code.ungleich.ch/llnu/ungleich-learning-circle-balazs): git@code.ungleich.ch:llnu/ungleich-learning-circle-balazs.git * [Jin-Guk](https://code.ungleich.ch/kjg/ungleich-learning-circle): git@code.ungleich.ch:kjg/ungleich-learning-circle.git +* [Pedro](https://code.ungleich.ch/pedro/ungleich-learning-circle): git@code.ungleich.ch:pedro/ungleich-learning-circle.git * [Sami](https://code.ungleich.ch/samialazar/learning-cicle): git@code.ungleich.ch:samialazar/learning-cicle.git * [Youngjin](https://code.ungleich.ch/youngjin.han/ungleich-learning-circle): git@code.ungleich.ch:youngjin.han/ungleich-learning-circle.git diff --git a/add-remotes.sh b/add-remotes.sh new file mode 100755 index 0000000..e9d870d --- /dev/null +++ b/add-remotes.sh @@ -0,0 +1,9 @@ +#!/bin/sh +# Nico Schottelius, 2020-07-22 + +grep '^* \[' README.md | sed 's/.*\[\(.*\)].*: \(git@.*\)/\1 \2/' | ( + while read name repo; do + name_small=$(echo $name | tr 'A-Z' 'a-z') + git remote add $name_small $repo + done + ) diff --git a/kjg/.emacs b/kjg/.emacs new file mode 100644 index 0000000..fbab1bd --- /dev/null +++ b/kjg/.emacs @@ -0,0 +1,150 @@ +;; Added by Package.el. This must come before configurations of +;; installed packages. Don't delete this line. If you don't want it, +;; just comment it out by adding a semicolon to the start of the line. +;; You may delete these explanatory comments. +(require 'package) +(add-to-list 'package-archives + '("melpa" . "http://melpa.org/packages/") t) +(add-to-list 'package-archives '("org" . "https://orgmode.org/elpa/") t) +(package-initialize) + + + +(global-set-key (kbd "") (lambda () (interactive) (find-file (concat "~/ungleich-learning-circle/kjg/learning-"(system-name)"-"(format-time-string "%Y")".org")))) +(global-set-key (kbd "C-x g") 'magit-status) +(global-set-key (kbd "C-c a") 'org-agenda) +(global-set-key (kbd "") 'org-todo-list) + +(custom-set-variables + ;; custom-set-variables was added by Custom. + ;; If you edit it by hand, you could mess it up, so be careful. + ;; Your init file should contain only one such instance. + ;; If there is more than one, they won't work right. + '(epg-gpg-program "/usr/local/bin/gpg") + '(org-agenda-files + (quote + ("~/ungleich-learning-circle/kjg/todo.org" "~/learning.org"))) + '(package-selected-packages (quote (org org-gnome org-dp ## which-key magit))) + '(python-shell-interpreter "python3") + '(send-mail-function (quote sendmail-send-it))) +(custom-set-faces + ;; custom-set-faces was added by Custom. + ;; If you edit it by hand, you could mess it up, so be careful. + ;; Your init file should contain only one such instance. + ;; If there is more than one, they won't work right. + ) + +(require 'epa-file) + +(epa-file-enable) + +(setq elpy-rpc-virtualenv-path 'current) + +;(use-package elpy +; :ensure t +; :config +; (elpy-enable) +; (setq elpy-rpc-python-command "python3") +; (setq elpy-rpc-backend "jedi") +; (elpy-use-cpython (or (executable-find "python3") +; (executable-find "/usr/bin/python3") +; (executable-find "/usr/local/bin/python3") +; "python3")) + ;; (elpy-use-ipython) +; (setq python-shell-interpreter-args "--simple-prompt -i") +; (add-hook 'python-mode-hook (lambda () (setq indent-tabs-mode nil)))) + +;(use-package ein :ensure t) + +(setq elpy-rpc-python-command "python3") + +(defvar myPackages + '(better-defaults ;; Set up some better Emacs defaults + elpy ;; Emacs Lisp Python Environment + flycheck ;; On the fly syntax checking + py-autopep8 ;; Run autopep8 on save + blacken ;; Black formatting on save + ein ;; Emacs IPython Notebook + material-theme ;; Theme + ) +) + +(elpy-enable) + +;; Use IPython for REPL +;(setq python-shell-interpreter "jupyter" +; python-shell-interpreter-args "console --simple-prompt" +; python-shell-prompt-detect-failure-warning nil) +;(add-to-list 'python-shell-completion-native-disabled-interpreters +; "jupyter") +;; Enable Flycheck +(when (require 'flycheck nil t) + (setq elpy-modules (delq 'elpy-module-flymake elpy-modules)) + (add-hook 'elpy-mode-hook 'flycheck-mode)) + +;(setq mu4e-mu-binary "/usr/local/bin/mu") + +;(add-to-list 'load-path "/usr/local/share/emacs/site-lisp/mu/mu4e") +;(require 'mu4e) + +;(setq +; mue4e-headers-skip-duplicates t +; mu4e-view-show-images t +; mu4e-view-show-addresses t +; mu4e-compose-format-flowed nil +; mu4e-date-format "%y/%m/%d" +; mu4e-headers-date-format "%Y/%m/%d" +; mu4e-change-filenames-when-moving t +; mu4e-attachments-dir "~/Downloads" + +; mu4e-maildir "~/Maildir/ungleich" ;; top-level Maildir + ;; note that these folders below must start with / + ;; the paths are relative to maildir root +; mu4e-refile-folder "/Archive" +; mu4e-sent-folder "/Sent" +; mu4e-drafts-folder "/Drafts" +; mu4e-trash-folder "/Trash" +; mu4e-reply-to-address "jinguk.kwon@ungleich.ch" +; user-mail-address "jinguk.kwon@ungleich.ch" +; user-full-name "kjg") + +;; this setting allows to re-sync and re-index mail +;; by pressing U +;(setq mu4e-get-mail-command "mbsync -a") + +;(setq mail-host-address "mail.ungleich.ch") + + +;(setq send-mail-function 'smtpmail-send-it +; message-send-mail-function 'smtpmail-send-it +; user-mail-address "jinguk.kwon@ungleich.ch" +; smtpmail-starttls-credentials '(("smtp.ungleich.ch" 587 nil nil)) +; smtpmail-auth-credentials "~/.authinfo.gpg" +; smtpmail-default-smtp-server "smtp.ungleich.ch" +; smtpmail-smtp-server "smtp.ungleich.ch" +; smtpmail-smtp-service 587 +; smtpmail-smtp-user "jinguk.kwon@ungleich.ch" +; smtpmail-debug-info t +; smtpmail-debug-verb t) + ;;starttls-extra-arguments nil + ;;starttls-gnutls-program (executable-find "gnutls-cli") + ;;smtpmail-warn-about-unknown-extensions t + ;;starttls-use-gnutls t) + +;(require 'smtpmail) + +;;store org-mode links to messages +;(require 'org-mu4e) + +;(define-key mu4e-headers-mode-map (kbd "C-c c") 'mu4e-org-store-and-capture) +;(define-key mu4e-view-mode-map (kbd "C-c c") 'mu4e-org-store-and-capture) + +(setq org-directory (expand-file-name "~/ungleich-learning-circle/kjg/")) +;;store link to message if in header view, not to header query +(setq org-mu4e-link-query-in-headers-mode nil) + +(setq org-capture-templates + '(("t" "todo" entry (file+headline (lambda() (concat "~/ungleich-learning-circle/kjg/todo-"(system-name)"-"(format-time-string "%Y")".org")) "Tasks") + "* TODO [#A] %?\nSCHEDULED: %(org-insert-time-stamp (org-read-date nil t \"+0d\"))\n%a\n"))) + +(setq org-log-done 'time) \ No newline at end of file diff --git a/kjg/IPv6/.gitignore b/kjg/IPv6/.gitignore new file mode 100644 index 0000000..2a14529 --- /dev/null +++ b/kjg/IPv6/.gitignore @@ -0,0 +1,3 @@ +venv/ +*.pyc +db.* \ No newline at end of file diff --git a/kjg/IPv6/overlap.py b/kjg/IPv6/overlap.py new file mode 100644 index 0000000..1ded373 --- /dev/null +++ b/kjg/IPv6/overlap.py @@ -0,0 +1,21 @@ +from sys import argv +import ipaddress + +# read the argument how to run this +try: + script, ip1, ip2 = argv + a = ip1.split('/') + b = ip2.split('/') + + a = ipaddress.ip_network(a[0]).supernet(new_prefix=int(a[1])) + b = ipaddress.ip_network(b[0]).supernet(new_prefix=int(b[1])) + + test1 = ipaddress.IPv6Network(a).overlaps(ipaddress.IPv6Network(b)) + + if test1 : + print("overlap") + else: + print("no overlap") + +except: + print("wrong inpit") diff --git a/kjg/IPv6/randomnet.py b/kjg/IPv6/randomnet.py new file mode 100644 index 0000000..f0c1326 --- /dev/null +++ b/kjg/IPv6/randomnet.py @@ -0,0 +1,52 @@ +from sys import argv +import argparse +import ipaddress +import random +#import getopt #option function + +parser = argparse.ArgumentParser(description="Generating IPv6 networks") +parser.add_argument('--size', help="size") +parser.add_argument('string', nargs='+', help="network") + +try: + args = parser.parse_args() + + if argv[1] == '--size': + ipnet = argv[3] + size = 128 - int(argv[2]) + else: + if len(argv) > 2 : + ipnet = argv[1] + size = 128 - int(argv[2]) + else: + ipnet = argv[1] + size = 80 + + ip = ipnet.split('/') + ip2 = ipaddress.ip_network(ip[0]).supernet(new_prefix=int(ip[1])) + + # minimum network + minNet = ipaddress.ip_network(ip[0]).supernet(new_prefix=128-size) + + # seperate network + ip2first = ipaddress.IPv6Network(ip2)[0] + ip2last = ipaddress.IPv6Network(ip2)[-1] + minNetlast = ipaddress.IPv6Network(minNet)[-1] + + # calculation network + maxRan = int(ip2last) - int(minNetlast) >> size + result = ipaddress.ip_address((random.randrange(0,maxRan) << size) + int(ip2first) ) + resultNetwork = ipaddress.ip_network(result).supernet(new_prefix=128-size) + + print(resultNetwork) + +except: + info=""" +wrong input +ex) --size 64 2001:db8::/40 + or 2001:db8::/40 64 + or 2001:db8::/40 #default size 48 +""" + print(info) + + diff --git a/kjg/IPv6/ula/manage.py b/kjg/IPv6/ula/manage.py new file mode 100755 index 0000000..2cef8fc --- /dev/null +++ b/kjg/IPv6/ula/manage.py @@ -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', 'ula.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() diff --git a/kjg/IPv6/ula/ula/__init__.py b/kjg/IPv6/ula/ula/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/kjg/IPv6/ula/ula/asgi.py b/kjg/IPv6/ula/ula/asgi.py new file mode 100644 index 0000000..bba5789 --- /dev/null +++ b/kjg/IPv6/ula/ula/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for ula 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.0/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ula.settings') + +application = get_asgi_application() diff --git a/kjg/IPv6/ula/ula/settings.py b/kjg/IPv6/ula/ula/settings.py new file mode 100644 index 0000000..6a2ed8c --- /dev/null +++ b/kjg/IPv6/ula/ula/settings.py @@ -0,0 +1,125 @@ +""" +Django settings for ula project. + +Generated by 'django-admin startproject' using Django 3.0.8. + +For more information on this file, see +https://docs.djangoproject.com/en/3.0/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/3.0/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/3.0/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'fj+%jfo4xd5rb(7w!7feda03q)y4md)*)e_rjw8i_gyab!6#-h' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = ["192.168.0.12", "testjg.django.lab.ungleich.ch", ] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'ularegistry', +] + +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 = 'ula.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 = 'ula.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/3.0/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.postgresql', + 'NAME': 'kjg', + 'USER': 'kjg', + 'PASSWORD': 'kjg#test', + 'HOST': 'localhost', + 'PORT': '', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/3.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/3.0/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.0/howto/static-files/ + +STATIC_URL = '/static/' diff --git a/kjg/IPv6/ula/ula/urls.py b/kjg/IPv6/ula/ula/urls.py new file mode 100644 index 0000000..2268978 --- /dev/null +++ b/kjg/IPv6/ula/ula/urls.py @@ -0,0 +1,27 @@ +"""ula URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/3.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 django.contrib import admin +from django.urls import include, path + +urlpatterns = [ + path('ularegistry/', include('ularegistry.urls')), + path('admin/', admin.site.urls), +] + diff --git a/kjg/IPv6/ula/ula/wsgi.py b/kjg/IPv6/ula/ula/wsgi.py new file mode 100644 index 0000000..44854f1 --- /dev/null +++ b/kjg/IPv6/ula/ula/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for ula 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.0/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ula.settings') + +application = get_wsgi_application() diff --git a/kjg/IPv6/ula/ularegistry/__init__.py b/kjg/IPv6/ula/ularegistry/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/kjg/IPv6/ula/ularegistry/admin.py b/kjg/IPv6/ula/ularegistry/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/kjg/IPv6/ula/ularegistry/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/kjg/IPv6/ula/ularegistry/apps.py b/kjg/IPv6/ula/ularegistry/apps.py new file mode 100644 index 0000000..c19dcc7 --- /dev/null +++ b/kjg/IPv6/ula/ularegistry/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class UlaregistryConfig(AppConfig): + name = 'ularegistry' diff --git a/kjg/IPv6/ula/ularegistry/checkip.py b/kjg/IPv6/ula/ularegistry/checkip.py new file mode 100644 index 0000000..2ebe26b --- /dev/null +++ b/kjg/IPv6/ula/ularegistry/checkip.py @@ -0,0 +1,13 @@ +import ipaddress + +def overlapip(ip1, ip2): + + test1 = ipaddress.IPv6Network(ip1).overlaps(ipaddress.IPv6Network(ip2)) + + if test1 : + print("overlap") + return 0 + else: + print("no overlap") + return 1 + diff --git a/kjg/IPv6/ula/ularegistry/forms.py b/kjg/IPv6/ula/ularegistry/forms.py new file mode 100644 index 0000000..6a01ebb --- /dev/null +++ b/kjg/IPv6/ula/ularegistry/forms.py @@ -0,0 +1,16 @@ +from django import forms +from netfields import CidrAddressField, NetManager + +class ip(forms.Form): + inputIP = forms.CharField() + #inputIP = CidrAddressField() + +class ip_random(forms.Form): + inputNetwork = forms.CharField() + NetworkName = forms.CharField() + NetworkDescription = forms.CharField() + +class new_ip_random(forms.Form): + NetworkName = forms.CharField() + NetworkDescription = forms.CharField() + diff --git a/kjg/IPv6/ula/ularegistry/migrations/0001_initial.py b/kjg/IPv6/ula/ularegistry/migrations/0001_initial.py new file mode 100644 index 0000000..9df6f8a --- /dev/null +++ b/kjg/IPv6/ula/ularegistry/migrations/0001_initial.py @@ -0,0 +1,22 @@ +# Generated by Django 3.0.8 on 2020-07-29 13:34 + +from django.db import migrations, models +import netfields.fields + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='IPs', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('inet', netfields.fields.CidrAddressField(max_length=43)), + ], + ), + ] diff --git a/kjg/IPv6/ula/ularegistry/migrations/0002_ips2.py b/kjg/IPv6/ula/ularegistry/migrations/0002_ips2.py new file mode 100644 index 0000000..a653443 --- /dev/null +++ b/kjg/IPv6/ula/ularegistry/migrations/0002_ips2.py @@ -0,0 +1,23 @@ +# Generated by Django 3.0.8 on 2020-08-03 14:30 + +from django.db import migrations, models +import netfields.fields + + +class Migration(migrations.Migration): + + dependencies = [ + ('ularegistry', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='ips2', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('inet2', netfields.fields.CidrAddressField(max_length=43)), + ('inet2_name', models.CharField(max_length=200)), + ('inet2_descrip', models.CharField(max_length=200)), + ], + ), + ] diff --git a/kjg/IPv6/ula/ularegistry/migrations/__init__.py b/kjg/IPv6/ula/ularegistry/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/kjg/IPv6/ula/ularegistry/models.py b/kjg/IPv6/ula/ularegistry/models.py new file mode 100644 index 0000000..058a0de --- /dev/null +++ b/kjg/IPv6/ula/ularegistry/models.py @@ -0,0 +1,17 @@ +from django.db import models +from netfields import CidrAddressField, NetManager + + +# Create your models here. +class ips(models.Model): + inet = CidrAddressField() + objects = NetManager() + def __str__(self): + st = str(self.inet) + return st + +class ips2(models.Model): + inet2 = CidrAddressField() + inet2_name = models.CharField(max_length=200) + inet2_descrip = models.CharField(max_length=200) + diff --git a/kjg/IPv6/ula/ularegistry/randomcreate.py b/kjg/IPv6/ula/ularegistry/randomcreate.py new file mode 100644 index 0000000..7b39869 --- /dev/null +++ b/kjg/IPv6/ula/ularegistry/randomcreate.py @@ -0,0 +1,29 @@ +from sys import argv +import argparse +import ipaddress +import random + +def createIP(ip): + ipnet = ip + size = 80 + + ip = ipnet.split('/') + ip2 = ipaddress.ip_network(ip[0]).supernet(new_prefix=int(ip[1])) + + # minimum network + minNet = ipaddress.ip_network(ip[0]).supernet(new_prefix=128-size) + + # seperate network + ip2first = ipaddress.IPv6Network(ip2)[0] + ip2last = ipaddress.IPv6Network(ip2)[-1] + minNetlast = ipaddress.IPv6Network(minNet)[-1] + + # calculation network + maxRan = int(ip2last) - int(minNetlast) >> size + result = ipaddress.ip_address((random.randrange(0,maxRan) << size) + int(ip2first) ) + resultNetwork = ipaddress.ip_network(result).supernet(new_prefix=128-size) + + print(resultNetwork) + return resultNetwork + + diff --git a/kjg/IPv6/ula/ularegistry/templates/base.html b/kjg/IPv6/ula/ularegistry/templates/base.html new file mode 100644 index 0000000..937752c --- /dev/null +++ b/kjg/IPv6/ula/ularegistry/templates/base.html @@ -0,0 +1,24 @@ + + + + + + + Document + + + + + {% if user.is_authenticated %} +

{{ user.username }} welcome

+ logout + {% else %} + signup + login + {% endif %} + + + {% block container %} + {% endblock %} + + diff --git a/kjg/IPv6/ula/ularegistry/templates/index.html b/kjg/IPv6/ula/ularegistry/templates/index.html new file mode 100644 index 0000000..6b7ec8f --- /dev/null +++ b/kjg/IPv6/ula/ularegistry/templates/index.html @@ -0,0 +1,14 @@ +
+ {% csrf_token %} + {{ form }} + +
+{% if ips_list %} + +{% else %} +

No registered IP.

+{% endif %} diff --git a/kjg/IPv6/ula/ularegistry/templates/login.html b/kjg/IPv6/ula/ularegistry/templates/login.html new file mode 100644 index 0000000..3482225 --- /dev/null +++ b/kjg/IPv6/ula/ularegistry/templates/login.html @@ -0,0 +1,11 @@ +{% extends 'base.html' %} +{% block container %} +

login

+ +
+ {% csrf_token %} + + {{ login_form }} + +
+{% endblock %} diff --git a/kjg/IPv6/ula/ularegistry/templates/newrandomIP.html b/kjg/IPv6/ula/ularegistry/templates/newrandomIP.html new file mode 100644 index 0000000..4afc020 --- /dev/null +++ b/kjg/IPv6/ula/ularegistry/templates/newrandomIP.html @@ -0,0 +1,19 @@ +{% extends 'base.html' %} +{% block container %} +
+ {% csrf_token %} + + {{ form2 }} +
+ +
+{% if ips_listr %} + +{% else %} +

No registered IP.

+{% endif %} +{% endblock %} diff --git a/kjg/IPv6/ula/ularegistry/templates/randomIP.html b/kjg/IPv6/ula/ularegistry/templates/randomIP.html new file mode 100644 index 0000000..58079b3 --- /dev/null +++ b/kjg/IPv6/ula/ularegistry/templates/randomIP.html @@ -0,0 +1,16 @@ +
+ {% csrf_token %} + + {{ form }} +
+ +
+{% if ips_listr %} + +{% else %} +

No registered IP.

+{% endif %} diff --git a/kjg/IPv6/ula/ularegistry/templates/signup.html b/kjg/IPv6/ula/ularegistry/templates/signup.html new file mode 100644 index 0000000..77c7932 --- /dev/null +++ b/kjg/IPv6/ula/ularegistry/templates/signup.html @@ -0,0 +1,11 @@ +{% extends 'base.html' %} +{% block container %} +

sign-up

+ +
+ {% csrf_token %} + {{ signup_form }} + +
+ +{% endblock %} diff --git a/kjg/IPv6/ula/ularegistry/tests.py b/kjg/IPv6/ula/ularegistry/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/kjg/IPv6/ula/ularegistry/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/kjg/IPv6/ula/ularegistry/urls.py b/kjg/IPv6/ula/ularegistry/urls.py new file mode 100644 index 0000000..d6d270a --- /dev/null +++ b/kjg/IPv6/ula/ularegistry/urls.py @@ -0,0 +1,12 @@ +from django.urls import path + +from . import views + +urlpatterns = [ + path('', views.index, name='index'), + path('randomIP', views.randomIP, name='randomIP'), + path('newrandomIP', views.newrandomIP, name='newrandomIP'), + path('login/', views.login, name='login'), + path('logout/', views.logout, name='logout'), + path('signup/', views.signup, name='signup'), +] diff --git a/kjg/IPv6/ula/ularegistry/views.py b/kjg/IPv6/ula/ularegistry/views.py new file mode 100644 index 0000000..47b45f8 --- /dev/null +++ b/kjg/IPv6/ula/ularegistry/views.py @@ -0,0 +1,172 @@ +from django.shortcuts import render +from django.http import HttpResponse +from .forms import ip_random, new_ip_random, ip +from ularegistry.models import ips, ips2 +from django.shortcuts import redirect +from ularegistry.checkip import * +from ularegistry.randomcreate import * +from django.shortcuts import render, redirect +from django.contrib.auth.forms import UserCreationForm, AuthenticationForm +from django.contrib.auth import login as auth_login +from django.contrib.auth import logout as auth_logout + +# Create your views here. +def index(request): + ips_list = ips.objects.values() + if request.method == "POST": + form = ip(request.POST) + print(form) + if form.is_valid(): + ips_list2 = list(ips_list) + if not ips_list2: + print("test") + q = ips(inet=form.cleaned_data['inputIP']) + q.save() + + overlapchk = 0 + for value in ips_list2: + if overlapip(form.cleaned_data['inputIP'],value['inet']): + overlapchk = 1 + else: + overlapchk = 0 + break + + if overlapchk: + print(overlapchk) + q = ips(inet=form.cleaned_data['inputIP']) + q.save() + + return redirect('index') + + else: + form = ip() + + ctx = { 'form' : form, + 'ips_list' : ips_list, + } + return render(request, 'index.html', ctx) + #return HttpResponse("Hello, world.") + +def randomIP(request): + ips_listr = ips2.objects.values() + if request.method == "POST": + form = ip_random(request.POST) + print(form) + if form.is_valid(): + while True: + newIP = createIP(form.cleaned_data['inputNetwork']) + ips_listr2 = list(ips_listr) + if not ips_listr2: + print("test") + q = ips2(inet2=newIP, inet2_name=form.cleaned_data['NetworkName'], inet2_descrip=form.cleaned_data['NetworkDescription']) + q.save() + break + + overlapchk = 0 + + for value in ips_listr2: + if overlapip(newIP,value['inet2']): + overlapchk = 1 + print(overlapchk) + q = ips2(inet2=newIP, inet2_name=form.cleaned_data['NetworkName'], inet2_descrip=form.cleaned_data['NetworkDescription']) + q.save() + break + else: + overlapchk = 0 + + if overlapchk: + break + + return redirect('randomIP') + + else: + form = ip_random() + + ctx = { 'form' : form, + 'ips_listr' : ips_listr, + } + return render(request, 'randomIP.html', ctx) + + +def newrandomIP(request): + ips_listr = ips2.objects.values() + if request.method == "POST": + form2 = new_ip_random(request.POST) + print(form2) + if form2.is_valid(): + while True: + newIP = createIP("fd00::/8") + print("test3") + ips_listr2 = list(ips_listr) + if not ips_listr2: + print("test2") + q = ips2(inet2=newIP, inet2_name=form2.cleaned_data['NetworkName'], inet2_descrip=form2.cleaned_data['NetworkDescription']) + q.save() + break + + overlapchk = 0 + + for value in ips_listr2: + if overlapip(newIP,value['inet2']): + overlapchk = 1 + print(overlapchk) + q = ips2(inet2=newIP, inet2_name=form2.cleaned_data['NetworkName'], inet2_descrip=form2.cleaned_data['NetworkDescription']) + q.save() + break + else: + overlapchk = 0 + + if overlapchk: + break + + return redirect('newrandomIP') + + else: + form2 = new_ip_random() + + ctx2 = { 'form2' : form2, + 'ips_listr' : ips_listr, + } + return render(request, 'newrandomIP.html', ctx2) + + +def signup(request): + if request.user.is_authenticated: + return redirect('newrandomIP') + + if request.method == 'POST': + signup_form = UserCreationForm(request.POST) + if signup_form.is_valid(): + user = signup_form.save() + auth_login(request, user) + return redirect('login') + else: + print("fail singup") + + else: + signup_form = UserCreationForm() + + return render(request, 'signup.html', {'signup_form':signup_form}) + + +def login(request): + if request.user.is_authenticated: + return redirect('newrandomIP') + + if request.method == 'POST': + login_form = AuthenticationForm(request, request.POST) + if login_form.is_valid(): + auth_login(request, login_form.get_user()) + return redirect('newrandomIP') + else: + print("fail login") + + else: + login_form = AuthenticationForm() + + return render(request, 'login.html', {'login_form' : login_form}) + + +def logout(request): + auth_logout(request) + return redirect('login') diff --git a/kjg/django/django.org b/kjg/django/django.org index 3234861..e59b705 100644 --- a/kjg/django/django.org +++ b/kjg/django/django.org @@ -11,3 +11,5 @@ It is used in some local place start from FC00::/7 L must be 1. Global ID is created randomly. + +*** django #2 diff --git a/kjg/django/mysite/mysite/settings.py b/kjg/django/mysite/mysite/settings.py index 6039908..97b8565 100644 --- a/kjg/django/mysite/mysite/settings.py +++ b/kjg/django/mysite/mysite/settings.py @@ -25,12 +25,13 @@ SECRET_KEY = '2kbmvs@pcbxn)kt#p9$)45=h#i8_b7^^l&l57mbe4%e=+k91-d' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True -ALLOWED_HOSTS = [] - +ALLOWED_HOSTS = [ "[2a0a:e5c1:114::12]", "127.0.0.1", "[2a0a:e5c1:151::12]", "testjg.django.lab.ungleich.ch", "[2a0a:e5c1:114::17]" ] +#ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ + 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', @@ -54,7 +55,7 @@ ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': [], + 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ diff --git a/kjg/django/mysite/mysite/urls.py b/kjg/django/mysite/mysite/urls.py index 8a95eac..2f884d2 100644 --- a/kjg/django/mysite/mysite/urls.py +++ b/kjg/django/mysite/mysite/urls.py @@ -14,8 +14,11 @@ Including another URLconf 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin -from django.urls import path +from django.urls import include, path + urlpatterns = [ + path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] + diff --git a/kjg/django/mysite/polls/admin.py b/kjg/django/mysite/polls/admin.py index 8c38f3f..88e96f7 100644 --- a/kjg/django/mysite/polls/admin.py +++ b/kjg/django/mysite/polls/admin.py @@ -1,3 +1,21 @@ from django.contrib import admin -# Register your models here. +from .models import Question, Choice + +class ChoiceInline(admin.TabularInline): + model = Choice + extra = 3 + + +class QuestionAdmin(admin.ModelAdmin): + fieldsets = [ + (None, {'fields': ['question_text']}), + ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), + ] + inlines = [ChoiceInline] + list_display = ('question_text', 'pub_date', 'was_published_recently') + list_filter = ['pub_date'] + search_fields = ['question_text'] + +admin.site.register(Question, QuestionAdmin) +#admin.site.register(Choice) diff --git a/kjg/django/mysite/polls/migrations/0001_initial.py b/kjg/django/mysite/polls/migrations/0001_initial.py new file mode 100644 index 0000000..f358828 --- /dev/null +++ b/kjg/django/mysite/polls/migrations/0001_initial.py @@ -0,0 +1,32 @@ +# Generated by Django 3.0.8 on 2020-07-06 15:51 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Question', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('question_text', models.CharField(max_length=200)), + ('pub_date', models.DateTimeField(verbose_name='date published')), + ], + ), + migrations.CreateModel( + name='Choice', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('choice_text', models.CharField(max_length=200)), + ('votes', models.IntegerField(default=0)), + ('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Question')), + ], + ), + ] diff --git a/kjg/django/mysite/polls/models.py b/kjg/django/mysite/polls/models.py index 71a8362..06bfcdc 100644 --- a/kjg/django/mysite/polls/models.py +++ b/kjg/django/mysite/polls/models.py @@ -1,3 +1,34 @@ +import datetime + from django.db import models +from django.utils import timezone # Create your models here. + + +class Question(models.Model): + question_text = models.CharField(max_length=200) + pub_date = models.DateTimeField('date published') + def __str__(self): + return self.question_text + + def was_published_recently(self): + now = timezone.now() + return now - datetime.timedelta(days=1) <= self.pub_date <= now + def was_published_recently(self): + now = timezone.now() + return now - datetime.timedelta(days=1) <= self.pub_date <= now + was_published_recently.admin_order_field = 'pub_date' + was_published_recently.boolean = True + was_published_recently.short_description = 'Published recently?' + #def was_published_recently(self): + #return self.pub_date >= timezone.now() - datetime.timedelta(days=1) + + + +class Choice(models.Model): + question = models.ForeignKey(Question, on_delete=models.CASCADE) + choice_text = models.CharField(max_length=200) + votes = models.IntegerField(default=0) + def __str__(self): + return self.choice_text diff --git a/kjg/django/mysite/polls/static/polls/images/background.gif b/kjg/django/mysite/polls/static/polls/images/background.gif new file mode 100644 index 0000000..928417e Binary files /dev/null and b/kjg/django/mysite/polls/static/polls/images/background.gif differ diff --git a/kjg/django/mysite/polls/static/polls/images/background2.png b/kjg/django/mysite/polls/static/polls/images/background2.png new file mode 100644 index 0000000..a22ed9e Binary files /dev/null and b/kjg/django/mysite/polls/static/polls/images/background2.png differ diff --git a/kjg/django/mysite/polls/static/polls/style.css b/kjg/django/mysite/polls/static/polls/style.css new file mode 100644 index 0000000..fa7d42e --- /dev/null +++ b/kjg/django/mysite/polls/static/polls/style.css @@ -0,0 +1,8 @@ +li a { + color: green; +} + +body { + #background-position: center center; + background: white url("images/background2.png") no-repeat fixed center center; +} diff --git a/kjg/django/mysite/polls/templates/admin/base_site.html b/kjg/django/mysite/polls/templates/admin/base_site.html new file mode 100644 index 0000000..9587878 --- /dev/null +++ b/kjg/django/mysite/polls/templates/admin/base_site.html @@ -0,0 +1,9 @@ +{% extends "admin/base.html" %} + +{% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %} + +{% block branding %} +

Polls Administration

+{% endblock %} + +{% block nav-global %}{% endblock %} diff --git a/kjg/django/mysite/polls/templates/polls/detail.html b/kjg/django/mysite/polls/templates/polls/detail.html new file mode 100644 index 0000000..3e55544 --- /dev/null +++ b/kjg/django/mysite/polls/templates/polls/detail.html @@ -0,0 +1,12 @@ +

{{ question.question_text }}

+ +{% if error_message %}

{{ error_message }}

{% endif %} + +
+{% csrf_token %} +{% for choice in question.choice_set.all %} + +
+{% endfor %} + +
diff --git a/kjg/django/mysite/polls/templates/polls/index.html b/kjg/django/mysite/polls/templates/polls/index.html new file mode 100644 index 0000000..366983e --- /dev/null +++ b/kjg/django/mysite/polls/templates/polls/index.html @@ -0,0 +1,13 @@ +{% load static %} + + + +{% if latest_question_list %} + +{% else %} +

No polls are available.

+{% endif %} diff --git a/kjg/django/mysite/polls/templates/polls/results.html b/kjg/django/mysite/polls/templates/polls/results.html new file mode 100644 index 0000000..3b2c74f --- /dev/null +++ b/kjg/django/mysite/polls/templates/polls/results.html @@ -0,0 +1,9 @@ +

{{ question.question_text }}

+ + + +Vote again? diff --git a/kjg/django/mysite/polls/tests.py b/kjg/django/mysite/polls/tests.py index 7ce503c..3604a06 100644 --- a/kjg/django/mysite/polls/tests.py +++ b/kjg/django/mysite/polls/tests.py @@ -1,3 +1,128 @@ -from django.test import TestCase +import datetime -# Create your tests here. +from django.test import TestCase +from django.utils import timezone +from django.urls import reverse + +from .models import Question + + +class QuestionModelTests(TestCase): + + def test_was_published_recently_with_future_question(self): + """ + was_published_recently() returns False for questions whose pub_date + is in the future. + """ + time = timezone.now() + datetime.timedelta(days=30) + future_question = Question(pub_date=time) + self.assertIs(future_question.was_published_recently(), False) + + def test_was_published_recently_with_old_question(self): + """ + was_published_recently() returns False for questions whose pub_date + is older than 1 day. + """ + time = timezone.now() - datetime.timedelta(days=1, seconds=1) + old_question = Question(pub_date=time) + self.assertIs(old_question.was_published_recently(), False) + + def test_was_published_recently_with_recent_question(self): + """ + was_published_recently() returns True for questions whose pub_date + is within the last day. + """ + time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59) + recent_question = Question(pub_date=time) + self.assertIs(recent_question.was_published_recently(), True) + + + +def create_question(question_text, days): + """ + Create a question with the given `question_text` and published the + given number of `days` offset to now (negative for questions published + in the past, positive for questions that have yet to be published). + """ + time = timezone.now() + datetime.timedelta(days=days) + return Question.objects.create(question_text=question_text, pub_date=time) + + +class QuestionIndexViewTests(TestCase): + def test_no_questions(self): + """ + If no questions exist, an appropriate message is displayed. + """ + response = self.client.get(reverse('polls:index')) + self.assertEqual(response.status_code, 200) + self.assertContains(response, "No polls are available.") + self.assertQuerysetEqual(response.context['latest_question_list'], []) + + def test_past_question(self): + """ + Questions with a pub_date in the past are displayed on the + index page. + """ + create_question(question_text="Past question.", days=-30) + response = self.client.get(reverse('polls:index')) + self.assertQuerysetEqual( + response.context['latest_question_list'], + [''] + ) + + def test_future_question(self): + """ + Questions with a pub_date in the future aren't displayed on + the index page. + """ + create_question(question_text="Future question.", days=30) + response = self.client.get(reverse('polls:index')) + self.assertContains(response, "No polls are available.") + self.assertQuerysetEqual(response.context['latest_question_list'], []) + + def test_future_question_and_past_question(self): + """ + Even if both past and future questions exist, only past questions + are displayed. + """ + create_question(question_text="Past question.", days=-30) + create_question(question_text="Future question.", days=30) + response = self.client.get(reverse('polls:index')) + self.assertQuerysetEqual( + response.context['latest_question_list'], + [''] + ) + + def test_two_past_questions(self): + """ + The questions index page may display multiple questions. + """ + create_question(question_text="Past question 1.", days=-30) + create_question(question_text="Past question 2.", days=-5) + response = self.client.get(reverse('polls:index')) + self.assertQuerysetEqual( + response.context['latest_question_list'], + ['', ''] + ) + + +class QuestionDetailViewTests(TestCase): + def test_future_question(self): + """ + The detail view of a question with a pub_date in the future + returns a 404 not found. + """ + future_question = create_question(question_text='Future question.', days=5) + url = reverse('polls:detail', args=(future_question.id,)) + response = self.client.get(url) + self.assertEqual(response.status_code, 404) + + def test_past_question(self): + """ + The detail view of a question with a pub_date in the past + displays the question's text. + """ + past_question = create_question(question_text='Past Question.', days=-5) + url = reverse('polls:detail', args=(past_question.id,)) + response = self.client.get(url) + self.assertContains(response, past_question.question_text) diff --git a/kjg/django/mysite/polls/urls.py b/kjg/django/mysite/polls/urls.py index 88a9cac..eff2be0 100644 --- a/kjg/django/mysite/polls/urls.py +++ b/kjg/django/mysite/polls/urls.py @@ -2,6 +2,10 @@ from django.urls import path from . import views +app_name = 'polls' urlpatterns = [ - path('', views.index, name='index'), + path('', views.IndexView.as_view(), name='index'), + path('/', views.DetailView.as_view(), name='detail'), + path('/results/', views.ResultsView.as_view(), name='results'), + path('/vote/', views.vote, name='vote'), ] diff --git a/kjg/django/mysite/polls/views.py b/kjg/django/mysite/polls/views.py index 91ea44a..68cf7b5 100644 --- a/kjg/django/mysite/polls/views.py +++ b/kjg/django/mysite/polls/views.py @@ -1,3 +1,74 @@ -from django.shortcuts import render +from django.http import HttpResponse, HttpResponseRedirect +#from django.http import Http404 +from django.template import loader +from django.shortcuts import get_object_or_404, render +from django.urls import reverse +from django.views import generic +from django.utils import timezone -# Create your views here. +from .models import Choice, Question + + +#def index(request): +# latest_question_list = Question.objects.order_by('-pub_date')[:5] +# context = {'latest_question_list': latest_question_list} +# return render(request, 'polls/index.html', context) +class IndexView(generic.ListView): + template_name = 'polls/index.html' + context_object_name = 'latest_question_list' + + def get_queryset(self): + """ + Return the last five published questions (not including those set to be + published in the future). + """ + return Question.objects.filter( + pub_date__lte=timezone.now() + ).order_by('-pub_date')[:5] + + #"""Return the last five published questions.""" + #return Question.objects.order_by('-pub_date')[:5] + +#def detail(request, question_id): +# #return HttpResponse("You're looking at question %s." % question_id) +# question = get_object_or_404(Question, pk=question_id) +# return render(request, 'polls/detail.html', {'question': question}) +class DetailView(generic.DetailView): + model = Question + template_name = 'polls/detail.html' + + def get_queryset(self): + """ + Excludes any questions that aren't published yet. + """ + return Question.objects.filter(pub_date__lte=timezone.now()) + + +#def results(request, question_id): +# #response = "You're looking at the results of question %s." +# #return HttpResponse(response % question_id) +# question = get_object_or_404(Question, pk=question_id) +# return render(request, 'polls/results.html', {'question': question}) +class ResultsView(generic.DetailView): + model = Question + template_name = 'polls/results.html' + + +def vote(request, question_id): + #return HttpResponse("You're voting on question %s." % question_id) + question = get_object_or_404(Question, pk=question_id) + try: + selected_choice = question.choice_set.get(pk=request.POST['choice']) + except (KeyError, Choice.DoesNotExist): + # Redisplay the question voting form. + return render(request, 'polls/detail.html', { + 'question': question, + 'error_message': "You didn't select a choice.", + }) + else: + selected_choice.votes += 1 + selected_choice.save() + # Always return an HttpResponseRedirect after successfully dealing + # with POST data. This prevents data from being posted twice if a + # user hits the Back button. + return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) diff --git a/pedro/.gitignore b/pedro/.gitignore new file mode 100644 index 0000000..154d790 --- /dev/null +++ b/pedro/.gitignore @@ -0,0 +1,2 @@ +*pyc +django-tutorial/mysite/db.sqlite3 diff --git a/pedro/django-tutorial/mysite/manage.py b/pedro/django-tutorial/mysite/manage.py new file mode 100755 index 0000000..341863c --- /dev/null +++ b/pedro/django-tutorial/mysite/manage.py @@ -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', 'mysite.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() diff --git a/pedro/django-tutorial/mysite/mysite/__init__.py b/pedro/django-tutorial/mysite/mysite/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/pedro/django-tutorial/mysite/mysite/asgi.py b/pedro/django-tutorial/mysite/mysite/asgi.py new file mode 100644 index 0000000..35d925e --- /dev/null +++ b/pedro/django-tutorial/mysite/mysite/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for mysite 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.0/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') + +application = get_asgi_application() diff --git a/pedro/django-tutorial/mysite/mysite/settings.py b/pedro/django-tutorial/mysite/mysite/settings.py new file mode 100644 index 0000000..1cdaa7e --- /dev/null +++ b/pedro/django-tutorial/mysite/mysite/settings.py @@ -0,0 +1,126 @@ +""" +Django settings for mysite project. + +Generated by 'django-admin startproject' using Django 3.0.8. + +For more information on this file, see +https://docs.djangoproject.com/en/3.0/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/3.0/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/3.0/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = '37jgpv28n1x!f3-48h)4ad99&jz-ek$@e6uf*an5uve6%7atqq' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = [ + +"localhost", +"2a0a-e5c1-011f-0000-0000-0000-0000-0001.has-a.name" + +] + + +# Application definition + +INSTALLED_APPS = [ + 'polls.apps.PollsConfig', + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', +] + +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 = 'mysite.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 = 'mysite.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/3.0/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/3.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/3.0/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'Europe/Madrid' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/3.0/howto/static-files/ + +STATIC_URL = '/static/' diff --git a/pedro/django-tutorial/mysite/mysite/urls.py b/pedro/django-tutorial/mysite/mysite/urls.py new file mode 100644 index 0000000..a3db229 --- /dev/null +++ b/pedro/django-tutorial/mysite/mysite/urls.py @@ -0,0 +1,22 @@ +"""mysite URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/3.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 include, path + +urlpatterns = [ + path('polls/', include('polls.urls')), + path('admin/', admin.site.urls), +] diff --git a/pedro/django-tutorial/mysite/mysite/wsgi.py b/pedro/django-tutorial/mysite/mysite/wsgi.py new file mode 100644 index 0000000..dbe7bb5 --- /dev/null +++ b/pedro/django-tutorial/mysite/mysite/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for mysite 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.0/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') + +application = get_wsgi_application() diff --git a/pedro/django-tutorial/mysite/polls/__init__.py b/pedro/django-tutorial/mysite/polls/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/pedro/django-tutorial/mysite/polls/admin.py b/pedro/django-tutorial/mysite/polls/admin.py new file mode 100644 index 0000000..0ad0944 --- /dev/null +++ b/pedro/django-tutorial/mysite/polls/admin.py @@ -0,0 +1,26 @@ +from django.contrib import admin + +# Register your models here. + +from .models import Choice, Question + +# stacked: that's lot of space +#class ChoiceInline(admin.StackedInline): +class ChoiceInline(admin.TabularInline): + model = Choice + extra = 3 + +class QuestionAdmin(admin.ModelAdmin): + # # this way we changed the order + #fields = ['pub_date', 'question_text'] + # # different organization of fields + fieldsets = [ + (None, {'fields': ['question_text']}), + ('Date information', {'fields': ['pub_date']}), + ] + inlines = [ChoiceInline] + list_display = ('question_text', 'pub_date', 'was_published_recently') + list_filter = ['pub_date'] + search_fields = ['question_text'] + +admin.site.register(Question, QuestionAdmin) diff --git a/pedro/django-tutorial/mysite/polls/apps.py b/pedro/django-tutorial/mysite/polls/apps.py new file mode 100644 index 0000000..d0f109e --- /dev/null +++ b/pedro/django-tutorial/mysite/polls/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class PollsConfig(AppConfig): + name = 'polls' diff --git a/pedro/django-tutorial/mysite/polls/migrations/0001_initial.py b/pedro/django-tutorial/mysite/polls/migrations/0001_initial.py new file mode 100644 index 0000000..330bbb6 --- /dev/null +++ b/pedro/django-tutorial/mysite/polls/migrations/0001_initial.py @@ -0,0 +1,32 @@ +# Generated by Django 3.0.8 on 2020-07-03 12:48 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Question', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('question_text', models.CharField(max_length=200)), + ('pub_date', models.DateTimeField(verbose_name='date published')), + ], + ), + migrations.CreateModel( + name='Choice', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('choice_text', models.CharField(max_length=200)), + ('votes', models.IntegerField(default=0)), + ('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Question')), + ], + ), + ] diff --git a/pedro/django-tutorial/mysite/polls/migrations/__init__.py b/pedro/django-tutorial/mysite/polls/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/pedro/django-tutorial/mysite/polls/models.py b/pedro/django-tutorial/mysite/polls/models.py new file mode 100644 index 0000000..73d22cb --- /dev/null +++ b/pedro/django-tutorial/mysite/polls/models.py @@ -0,0 +1,27 @@ +import datetime + +from django.db import models +from django.utils import timezone + +# Create your models here. + +class Question(models.Model): + question_text = models.CharField(max_length=200) + pub_date = models.DateTimeField('date published') + def __str__(self): + return self.question_text + def was_published_recently(self): + # bug + #return self.pub_date >= timezone.now() - datetime.timedelta(days=1) + now = timezone.now() + return now - datetime.timedelta(days=1) <= self.pub_date <= now + was_published_recently.admin_order_field = 'pub_date' + was_published_recently.boolean = True + was_published_recently.short_description = 'Published recently?' + +class Choice(models.Model): + question = models.ForeignKey(Question, on_delete=models.CASCADE) + choice_text = models.CharField(max_length=200) + votes = models.IntegerField(default=0) + def __str__(self): + return self.choice_text diff --git a/pedro/django-tutorial/mysite/polls/static/polls/images/background.gif b/pedro/django-tutorial/mysite/polls/static/polls/images/background.gif new file mode 100644 index 0000000..60507ba Binary files /dev/null and b/pedro/django-tutorial/mysite/polls/static/polls/images/background.gif differ diff --git a/pedro/django-tutorial/mysite/polls/static/polls/style.css b/pedro/django-tutorial/mysite/polls/static/polls/style.css new file mode 100644 index 0000000..4db5255 --- /dev/null +++ b/pedro/django-tutorial/mysite/polls/static/polls/style.css @@ -0,0 +1,10 @@ +li a { + color: green; +} + +body { + /* thanks: https://stackoverflow.com/questions/12605908/change-background-image-opacity/40366996#40366996 */ + background-image: url("images/background.gif"); + background-color: rgba(255,255,255,0.6); + background-blend-mode: lighten; +} diff --git a/pedro/django-tutorial/mysite/polls/templates/polls/detail.html b/pedro/django-tutorial/mysite/polls/templates/polls/detail.html new file mode 100644 index 0000000..3e55544 --- /dev/null +++ b/pedro/django-tutorial/mysite/polls/templates/polls/detail.html @@ -0,0 +1,12 @@ +

{{ question.question_text }}

+ +{% if error_message %}

{{ error_message }}

{% endif %} + +
+{% csrf_token %} +{% for choice in question.choice_set.all %} + +
+{% endfor %} + +
diff --git a/pedro/django-tutorial/mysite/polls/templates/polls/index.html b/pedro/django-tutorial/mysite/polls/templates/polls/index.html new file mode 100644 index 0000000..9ac8451 --- /dev/null +++ b/pedro/django-tutorial/mysite/polls/templates/polls/index.html @@ -0,0 +1,15 @@ +{% load static %} + +{% if latest_question_list %} + +{% else %} +

No polls are available.

+{% endif %} diff --git a/pedro/django-tutorial/mysite/polls/templates/polls/results.html b/pedro/django-tutorial/mysite/polls/templates/polls/results.html new file mode 100644 index 0000000..bc78e2b --- /dev/null +++ b/pedro/django-tutorial/mysite/polls/templates/polls/results.html @@ -0,0 +1,9 @@ +

{{ question.question_text }}

+ +
    +{% for choice in question.choice_set.all %} +
  • {{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}
  • +{% endfor %} +
+ +Vote again? diff --git a/pedro/django-tutorial/mysite/polls/tests.py b/pedro/django-tutorial/mysite/polls/tests.py new file mode 100644 index 0000000..c123f37 --- /dev/null +++ b/pedro/django-tutorial/mysite/polls/tests.py @@ -0,0 +1,128 @@ +import datetime + +from django.test import TestCase + +from django.utils import timezone + +from .models import Question + +from django.urls import reverse + + +class QuestionModelTests(TestCase): + + def test_was_published_recently_with_future_question(self): + """ + was_published_recently() returns False for questions whose pub_date + is in the future. + """ + time = timezone.now() + datetime.timedelta(days=30) + future_question = Question(pub_date=time) + self.assertIs(future_question.was_published_recently(), False) + + def test_was_published_recently_with_old_question(self): + """ + was_published_recently() returns False for questions whose pub_date + is older than 1 day. + """ + time = timezone.now() - datetime.timedelta(days=1, seconds=1) + old_question = Question(pub_date=time) + self.assertIs(old_question.was_published_recently(), False) + + def test_was_published_recently_with_recent_question(self): + """ + was_published_recently() returns True for questions whose pub_date + is within the last day. + """ + time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59) + recent_question = Question(pub_date=time) + self.assertIs(recent_question.was_published_recently(), True) + + + +def create_question(question_text, days): + """ + Create a question with the given `question_text` and published the + given number of `days` offset to now (negative for questions published + in the past, positive for questions that have yet to be published). + """ + time = timezone.now() + datetime.timedelta(days=days) + return Question.objects.create(question_text=question_text, pub_date=time) + +class QuestionIndexViewTests(TestCase): + def test_no_questions(self): + """ + If no questions exist, an appropriate message is displayed. + """ + response = self.client.get(reverse('polls:index')) + self.assertEqual(response.status_code, 200) + self.assertContains(response, "No polls are available.") + self.assertQuerysetEqual(response.context['latest_question_list'], []) + + def test_past_question(self): + """ + Questions with a pub_date in the past are displayed on the + index page. + """ + create_question(question_text="Past question.", days=-30) + response = self.client.get(reverse('polls:index')) + self.assertQuerysetEqual( + response.context['latest_question_list'], + [''] + ) + + def test_future_question(self): + """ + Questions with a pub_date in the future aren't displayed on + the index page. + """ + create_question(question_text="Future question.", days=30) + response = self.client.get(reverse('polls:index')) + self.assertContains(response, "No polls are available.") + self.assertQuerysetEqual(response.context['latest_question_list'], []) + + def test_future_question_and_past_question(self): + """ + Even if both past and future questions exist, only past questions + are displayed. + """ + create_question(question_text="Past question.", days=-30) + create_question(question_text="Future question.", days=30) + response = self.client.get(reverse('polls:index')) + self.assertQuerysetEqual( + response.context['latest_question_list'], + [''] + ) + + def test_two_past_questions(self): + """ + The questions index page may display multiple questions. + """ + create_question(question_text="Past question 1.", days=-30) + create_question(question_text="Past question 2.", days=-5) + response = self.client.get(reverse('polls:index')) + self.assertQuerysetEqual( + response.context['latest_question_list'], + ['', ''] + ) + +class QuestionDetailViewTests(TestCase): + def test_future_question(self): + """ + The detail view of a question with a pub_date in the future + returns a 404 not found. + """ + future_question = create_question(question_text='Future question.', days=5) + url = reverse('polls:detail', args=(future_question.id,)) + response = self.client.get(url) + self.assertEqual(response.status_code, 404) + + def test_past_question(self): + """ + The detail view of a question with a pub_date in the past + displays the question's text. + """ + past_question = create_question(question_text='Past Question.', days=-5) + url = reverse('polls:detail', args=(past_question.id,)) + response = self.client.get(url) + self.assertContains(response, past_question.question_text) diff --git a/pedro/django-tutorial/mysite/polls/urls.py b/pedro/django-tutorial/mysite/polls/urls.py new file mode 100644 index 0000000..8aa1a75 --- /dev/null +++ b/pedro/django-tutorial/mysite/polls/urls.py @@ -0,0 +1,17 @@ +from django.urls import path + +from . import views + +# namespacing URLs +app_name = 'polls' +urlpatterns = [ + # ex: /polls/ + #path('', views.index, name='index'), + path('', views.IndexView.as_view(), name='index'), + # ex: /polls/5/ + path('/', views.DetailView.as_view(), name='detail'), + # ex: /polls/5/results/ + path('/results/', views.ResultsView.as_view(), name='results'), + # ex: /polls/5/vote/ + path('/vote/', views.vote, name='vote'), +] diff --git a/pedro/django-tutorial/mysite/polls/views.py b/pedro/django-tutorial/mysite/polls/views.py new file mode 100644 index 0000000..89b1196 --- /dev/null +++ b/pedro/django-tutorial/mysite/polls/views.py @@ -0,0 +1,125 @@ +from django.shortcuts import get_object_or_404, render + +# Create your views here. + +from django.http import HttpResponse, HttpResponseRedirect +from django.template import loader +from django.urls import reverse +from django.views import generic + +from .models import Choice, Question + +from django.http import Http404 + +from django.utils import timezone + +## simple index +#def index(request): +# return HttpResponse("Hello, world. You're at the polls index.") + +## meaningful index +#def index(request): +# latest_question_list = Question.objects.order_by('-pub_date')[:5] +# output = ', '.join([q.question_text for q in latest_question_list]) +# return HttpResponse(output) + +## meaningful and templated index +#def index(request): +# latest_question_list = Question.objects.order_by('-pub_date')[:5] +# template = loader.get_template('polls/index.html') +# context = { +# 'latest_question_list': latest_question_list, +# } +# return HttpResponse(template.render(context, request)) + +## meaningful, templated and easy to write index +## and then we no longer need to import loader and HttpResponse +#def index(request): +# latest_question_list = Question.objects.order_by('-pub_date')[:5] +# context = { +# 'latest_question_list': latest_question_list, +# } +# return render(request, 'polls/index.html', context) + +class IndexView(generic.ListView): + template_name = 'polls/index.html' + context_object_name = 'latest_question_list' + +## has bug +# def get_queryset(self): +# """Return the last five published questions.""" +# return Question.objects.order_by('-pub_date')[:5] + +# refactor + def get_queryset(self): + """ + Return the last five published questions (not including those set to be + published in the future). + """ + return Question.objects.filter( + pub_date__lte=timezone.now() + ).order_by('-pub_date')[:5] + +## simple detail +#def detail(request, question_id): +# return HttpResponse("You're looking at question %s." % question_id) + +## meaningful detail +#def detail(request, question_id): +# try: +# question = Question.objects.get(pk=question_id) +# except Question.DoesNotExist: +# raise Http404("Question does not exist") +# return render(request, 'polls/detail.html', {'question': question}) + +## meaningful and easy to write detail +#def detail(request, question_id): +# question = get_object_or_404(Question, pk=question_id) +# return render(request, 'polls/detail.html', {'question': question}) + +## refactor detail view +class DetailView(generic.DetailView): + model = Question + template_name = 'polls/detail.html' + def get_queryset(self): + """ + Excludes any questions that aren't published yet. + """ + return Question.objects.filter(pub_date__lte=timezone.now()) + +#def results(request, question_id): +# response = "You're looking at the results of question %s." +# return HttpResponse(response % question_id) + +# # real implementation of results +#def results(request, question_id): +# question = get_object_or_404(Question, pk=question_id) +# return render(request, 'polls/results.html', {'question': question}) + +# # refactor results view +class ResultsView(generic.DetailView): + model = Question + template_name = 'polls/results.html' + +#def vote(request, question_id): +# return HttpResponse("You're voting on question %s." % question_id) + + +# #real implementation of vote +def vote (request, question_id): + question = get_object_or_404(Question, pk=question_id) + try: + selected_choice = question.choice_set.get(pk=request.POST['choice']) + except (KeyError, Choice.DoesNotExist): + # Redisplay the question voting form. + return render(request, 'polls/detail.html', { + 'question': question, + 'error_message': "You didn't select a choice.", + }) + else: + selected_choice.votes += 1 + selected_choice.save() + # Always return an HttpResponseRedirect after successfully dealing + # with POST data. This prevents data from being posted twice if a + # user hits the Back button + return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) diff --git a/pedro/django-tutorial/mysite/templates/admin/base_site.html b/pedro/django-tutorial/mysite/templates/admin/base_site.html new file mode 100644 index 0000000..2a7be39 --- /dev/null +++ b/pedro/django-tutorial/mysite/templates/admin/base_site.html @@ -0,0 +1,9 @@ +{% extends "admin/base.html" %} + +{% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %} + +{% block branding %} +

Polls +{% endblock %} + +{% block nav-global %}{% endblock %} diff --git a/pedro/ipv6-stuff/overlap.py b/pedro/ipv6-stuff/overlap.py new file mode 100644 index 0000000..4559091 --- /dev/null +++ b/pedro/ipv6-stuff/overlap.py @@ -0,0 +1,53 @@ +import ipaddress +import argparse +# for exit codes +import sys + +def proc_args(): + # src https://docs.python.org/3/library/argparse.html#description + parser = argparse.ArgumentParser(description='Compare two IPs and check if they are overlapped or not') + parser.add_argument('ip1', type=str, + help='IPv6 number 1') + parser.add_argument('ip2', type=str, + help='IPv6 number 2') + args = parser.parse_args() + return args + + # - Write a python script that checks whether two IPv6 networks are overlapping + # - *overlap.py ip1 ip2* + +def parse_ip(ip_arg): + if('/' in ip_arg): + ip_arg = ip_arg.split('/')[0] + else: + # if no network specified, assume a netmask of /48 for all of them + ip_arg = ip_arg + '/48' + # strict false to avoid -> https://stackoverflow.com/questions/40839147/ipaddress-module-valueerrors-has-host-bits-set-self + # strict is passed to IPv4Network or IPv6Network constructor. A ValueError is + # raised if address does not represent a valid IPv4 or IPv6 address, or if + # the network has host bits set. -> src https://docs.python.org/3/library/ipaddress.html#ipaddress.ip_network + return ipaddress.IPv6Network(ip_arg, False) + +def main(): + + is_overlap=False + + args = proc_args() + try: + ip1 = parse_ip(args.ip1) + ip2 = parse_ip(args.ip2) + except: + print('incorrect IPv6 address') + + # src https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv4Network.overlaps + is_overlap = ip1.overlaps(ip2) + + if(is_overlap): + print('overlap') + sys.exit(1) + else: + print('no overlap') + sys.exit(0) + +if __name__ == "__main__": + main() diff --git a/pedro/ipv6-stuff/overlap_run.sh b/pedro/ipv6-stuff/overlap_run.sh new file mode 100755 index 0000000..1e0d0c9 --- /dev/null +++ b/pedro/ipv6-stuff/overlap_run.sh @@ -0,0 +1,32 @@ +#!/bin/sh + +run_program() { + echo "args:\n ip1: ${1}\n ip2: ${2}" + printf 'output: ' + python3 overlap.py ${1} ${2} + echo "exit code: $?" + echo '----------------' +} + +# - Use the following test IPv6 addresses: +# - 2001:db8:: +# - 2001:db8:0:2:: +# - 2001:db8:1:: +# - Step 2: Make your script parse ipv6 networks (like +# 2001:db8::/48 and 2001:db8::/64) ) and check whether they overlap + +ip1='2001:db8::' +ip2='2001:db8:0:2::' +run_program $ip1 $ip2 + +ip1='2001:db8::' +ip2='2001:db8:1::' +run_program $ip1 $ip2 + +ip1='2001:db8:0:2::' +ip2='2001:db8:1::' +run_program $ip1 $ip2 + +ip1='2001:db8::/48' +ip2='2001:db8::/64' +run_program $ip1 $ip2 diff --git a/sami/django/mysite/db.sqlite3 b/sami/django/mysite/db.sqlite3 new file mode 100644 index 0000000..93a0f5a Binary files /dev/null and b/sami/django/mysite/db.sqlite3 differ diff --git a/sami/django/mysite/manage.py b/sami/django/mysite/manage.py new file mode 100755 index 0000000..577e446 --- /dev/null +++ b/sami/django/mysite/manage.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python3 +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.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() diff --git a/sami/django/mysite/mysite/__init__.py b/sami/django/mysite/mysite/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/sami/django/mysite/mysite/settings.py b/sami/django/mysite/mysite/settings.py new file mode 100644 index 0000000..dd259dc --- /dev/null +++ b/sami/django/mysite/mysite/settings.py @@ -0,0 +1,130 @@ +""" +Django settings for mysite project. + +Generated by 'django-admin startproject' using Django 2.2.12. + +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 = 'p+k-n&d40pt2yi@yyq1(u%+b!b4#yloa%1ct%#jibl41x9z1b@' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = [] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', +] + +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 = 'mysite.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 = 'mysite.wsgi.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 = 'en-us' + +TIME_ZONE = 'UTC' + +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/' + +INSTALLED_APPS = [ + 'polls.apps.PollsConfig', + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', +] diff --git a/sami/django/mysite/mysite/urls.py b/sami/django/mysite/mysite/urls.py new file mode 100644 index 0000000..cba3a35 --- /dev/null +++ b/sami/django/mysite/mysite/urls.py @@ -0,0 +1,22 @@ +"""mysite 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 include, path + +urlpatterns = [ + path('polls/', include('polls.urls')), + path('admin/', admin.site.urls), +] diff --git a/sami/django/mysite/mysite/wsgi.py b/sami/django/mysite/mysite/wsgi.py new file mode 100644 index 0000000..45e28c9 --- /dev/null +++ b/sami/django/mysite/mysite/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for mysite 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', 'mysite.settings') + +application = get_wsgi_application() diff --git a/sami/django/mysite/polls/__init__.py b/sami/django/mysite/polls/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/sami/django/mysite/polls/admin.py b/sami/django/mysite/polls/admin.py new file mode 100644 index 0000000..3f3d36e --- /dev/null +++ b/sami/django/mysite/polls/admin.py @@ -0,0 +1,7 @@ +# Register your models here. + +from django.contrib import admin + +from .models import Question + +admin.site.register(Question) diff --git a/sami/django/mysite/polls/apps.py b/sami/django/mysite/polls/apps.py new file mode 100644 index 0000000..d0f109e --- /dev/null +++ b/sami/django/mysite/polls/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class PollsConfig(AppConfig): + name = 'polls' diff --git a/sami/django/mysite/polls/migrations/0001_initial.py b/sami/django/mysite/polls/migrations/0001_initial.py new file mode 100644 index 0000000..88946ea --- /dev/null +++ b/sami/django/mysite/polls/migrations/0001_initial.py @@ -0,0 +1,32 @@ +# Generated by Django 2.2.12 on 2020-07-03 14:26 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Question', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('question_text', models.CharField(max_length=200)), + ('pub_date', models.DateTimeField(verbose_name='date published')), + ], + ), + migrations.CreateModel( + name='Choice', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('choice_text', models.CharField(max_length=200)), + ('votes', models.IntegerField(default=0)), + ('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Question')), + ], + ), + ] diff --git a/sami/django/mysite/polls/migrations/__init__.py b/sami/django/mysite/polls/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/sami/django/mysite/polls/models.py b/sami/django/mysite/polls/models.py new file mode 100644 index 0000000..0570fbb --- /dev/null +++ b/sami/django/mysite/polls/models.py @@ -0,0 +1,40 @@ +from django.db import models + +# Create your models here. + +class Question(models.Model): + question_text = models.CharField(max_length=200) + pub_date = models.DateTimeField('date published') + + +class Choice(models.Model): + question = models.ForeignKey(Question, on_delete=models.CASCADE) + choice_text = models.CharField(max_length=200) + + votes = models.IntegerField(default=0) + + +from django.db import models + +class Question(models.Model): + # ... + def __str__(self): + return self.question_text + +class Choice(models.Model): + # ... + def __str__(self): + return self.choice_text + + + +import datetime + +from django.db import models +from django.utils import timezone + + +class Question(models.Model): + # ... + def was_published_recently(self): + return self.pub_date >= timezone.now() - datetime.timedelta(days=1) diff --git a/sami/django/mysite/polls/tests.py b/sami/django/mysite/polls/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/sami/django/mysite/polls/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/sami/django/mysite/polls/urls.py b/sami/django/mysite/polls/urls.py new file mode 100644 index 0000000..88a9cac --- /dev/null +++ b/sami/django/mysite/polls/urls.py @@ -0,0 +1,7 @@ +from django.urls import path + +from . import views + +urlpatterns = [ + path('', views.index, name='index'), +] diff --git a/sami/django/mysite/polls/views.py b/sami/django/mysite/polls/views.py new file mode 100644 index 0000000..8531097 --- /dev/null +++ b/sami/django/mysite/polls/views.py @@ -0,0 +1,17 @@ +# from django.shortcuts import render + +# Create your views here. + +#from django.urls import path + +#from . import views + +#urlpatterns = [ + # path('', views.index, name='index'), +#] + +from django.http import HttpResponse + + +def index(request): + return HttpResponse("Hello, world. You're at the polls index.") diff --git a/sami/django/mysite2/db.sqlite3 b/sami/django/mysite2/db.sqlite3 new file mode 100644 index 0000000..95016af Binary files /dev/null and b/sami/django/mysite2/db.sqlite3 differ diff --git a/sami/django/mysite2/manage.py b/sami/django/mysite2/manage.py new file mode 100755 index 0000000..f7bf114 --- /dev/null +++ b/sami/django/mysite2/manage.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python3 +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite2.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() diff --git a/sami/django/mysite2/mysite2/__init__.py b/sami/django/mysite2/mysite2/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/sami/django/mysite2/mysite2/settings.py b/sami/django/mysite2/mysite2/settings.py new file mode 100644 index 0000000..a23a153 --- /dev/null +++ b/sami/django/mysite2/mysite2/settings.py @@ -0,0 +1,121 @@ +""" +Django settings for mysite2 project. + +Generated by 'django-admin startproject' using Django 2.2.12. + +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 = 'sb1cbc!m_esjnb381eh8!+(1$zi-%$h@ewu#3=cog+ls)d%)3z' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = ['2a0a-e5c0-10-bee-7994-d023-5c29-7091.has-a.name'] + + +# Application definition + +INSTALLED_APPS = [ + 'polls.apps.PollsConfig', + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', +] + +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 = 'mysite2.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 = 'mysite2.wsgi.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 = 'en-us' + +TIME_ZONE = 'Europe/Zurich' + +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/' diff --git a/sami/django/mysite2/mysite2/urls.py b/sami/django/mysite2/mysite2/urls.py new file mode 100644 index 0000000..e7a42d7 --- /dev/null +++ b/sami/django/mysite2/mysite2/urls.py @@ -0,0 +1,23 @@ + +"""mysite2 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 include, path + +urlpatterns = [ + path('polls/', include('polls.urls')), + path('admin/', admin.site.urls), +] diff --git a/sami/django/mysite2/mysite2/wsgi.py b/sami/django/mysite2/mysite2/wsgi.py new file mode 100644 index 0000000..916825e --- /dev/null +++ b/sami/django/mysite2/mysite2/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for mysite2 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', 'mysite2.settings') + +application = get_wsgi_application() diff --git a/sami/django/mysite2/polls/__init__.py b/sami/django/mysite2/polls/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/sami/django/mysite2/polls/admin.py b/sami/django/mysite2/polls/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/sami/django/mysite2/polls/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/sami/django/mysite2/polls/apps.py b/sami/django/mysite2/polls/apps.py new file mode 100644 index 0000000..d0f109e --- /dev/null +++ b/sami/django/mysite2/polls/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class PollsConfig(AppConfig): + name = 'polls' diff --git a/sami/django/mysite2/polls/migrations/0001_initial.py b/sami/django/mysite2/polls/migrations/0001_initial.py new file mode 100644 index 0000000..3826812 --- /dev/null +++ b/sami/django/mysite2/polls/migrations/0001_initial.py @@ -0,0 +1,32 @@ +# Generated by Django 2.2.12 on 2020-07-10 14:30 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Question', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('question_text', models.CharField(max_length=200)), + ('pub_date', models.DateTimeField(verbose_name='date published')), + ], + ), + migrations.CreateModel( + name='Choice', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('choice_text', models.CharField(max_length=200)), + ('votes', models.IntegerField(default=0)), + ('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Question')), + ], + ), + ] diff --git a/sami/django/mysite2/polls/migrations/__init__.py b/sami/django/mysite2/polls/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/sami/django/mysite2/polls/models.py b/sami/django/mysite2/polls/models.py new file mode 100644 index 0000000..a7c5580 --- /dev/null +++ b/sami/django/mysite2/polls/models.py @@ -0,0 +1,28 @@ +import datetime + +from django.db import models +from django.utils import timezone + +# Create your models here. + + +class Question(models.Model): + question_text = models.CharField(max_length=200) + pub_date = models.DateTimeField('date published') + def __str__(self): + return self.question_text + + def was_published_recently(self): + now = timezone.now() + return now - datetime.timedelta(days=1) <= self.pub_date <= now + #def was_published_recently(self): + #return self.pub_date >= timezone.now() - datetime.timedelta(days=1) + + + +class Choice(models.Model): + question = models.ForeignKey(Question, on_delete=models.CASCADE) + choice_text = models.CharField(max_length=200) + votes = models.IntegerField(default=0) + def __str__(self): + return self.choice_text diff --git a/sami/django/mysite2/polls/templates/admin/base_site.html b/sami/django/mysite2/polls/templates/admin/base_site.html new file mode 100644 index 0000000..cae0a69 --- /dev/null +++ b/sami/django/mysite2/polls/templates/admin/base_site.html @@ -0,0 +1,9 @@ +{% extends "admin/base.html" %} + +{% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %} + +{% block branding %} +

{{ site_header|default:_('Django administration') }}

+{% endblock %} + +{% block nav-global %}{% endblock %} diff --git a/sami/django/mysite2/polls/templates/detail.html b/sami/django/mysite2/polls/templates/detail.html new file mode 100644 index 0000000..c225d49 --- /dev/null +++ b/sami/django/mysite2/polls/templates/detail.html @@ -0,0 +1,13 @@ +

{{ question.question_text }}

+ +{% if error_message %}

{{ error_message }}

{% endif %} + +
+{% csrf_token %} +{% for choice in question.choice_set.all %} + +
+{% endfor %} + +
+p diff --git a/sami/django/mysite2/polls/templates/polls/detail.html b/sami/django/mysite2/polls/templates/polls/detail.html new file mode 100644 index 0000000..3e55544 --- /dev/null +++ b/sami/django/mysite2/polls/templates/polls/detail.html @@ -0,0 +1,12 @@ +

{{ question.question_text }}

+ +{% if error_message %}

{{ error_message }}

{% endif %} + +
+{% csrf_token %} +{% for choice in question.choice_set.all %} + +
+{% endfor %} + +
diff --git a/sami/django/mysite2/polls/templates/polls/index.html b/sami/django/mysite2/polls/templates/polls/index.html new file mode 100644 index 0000000..4560139 --- /dev/null +++ b/sami/django/mysite2/polls/templates/polls/index.html @@ -0,0 +1,9 @@ +{% if latest_question_list %} + +{% else %} +

No polls are available.

+{% endif %} diff --git a/sami/django/mysite2/polls/templates/polls/results.html b/sami/django/mysite2/polls/templates/polls/results.html new file mode 100644 index 0000000..3b2c74f --- /dev/null +++ b/sami/django/mysite2/polls/templates/polls/results.html @@ -0,0 +1,9 @@ +

{{ question.question_text }}

+ +
    +{% for choice in question.choice_set.all %} +
  • {{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}
  • +{% endfor %} +
+ +Vote again? diff --git a/sami/django/mysite2/polls/tests.py b/sami/django/mysite2/polls/tests.py new file mode 100644 index 0000000..3604a06 --- /dev/null +++ b/sami/django/mysite2/polls/tests.py @@ -0,0 +1,128 @@ +import datetime + +from django.test import TestCase +from django.utils import timezone +from django.urls import reverse + +from .models import Question + + +class QuestionModelTests(TestCase): + + def test_was_published_recently_with_future_question(self): + """ + was_published_recently() returns False for questions whose pub_date + is in the future. + """ + time = timezone.now() + datetime.timedelta(days=30) + future_question = Question(pub_date=time) + self.assertIs(future_question.was_published_recently(), False) + + def test_was_published_recently_with_old_question(self): + """ + was_published_recently() returns False for questions whose pub_date + is older than 1 day. + """ + time = timezone.now() - datetime.timedelta(days=1, seconds=1) + old_question = Question(pub_date=time) + self.assertIs(old_question.was_published_recently(), False) + + def test_was_published_recently_with_recent_question(self): + """ + was_published_recently() returns True for questions whose pub_date + is within the last day. + """ + time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59) + recent_question = Question(pub_date=time) + self.assertIs(recent_question.was_published_recently(), True) + + + +def create_question(question_text, days): + """ + Create a question with the given `question_text` and published the + given number of `days` offset to now (negative for questions published + in the past, positive for questions that have yet to be published). + """ + time = timezone.now() + datetime.timedelta(days=days) + return Question.objects.create(question_text=question_text, pub_date=time) + + +class QuestionIndexViewTests(TestCase): + def test_no_questions(self): + """ + If no questions exist, an appropriate message is displayed. + """ + response = self.client.get(reverse('polls:index')) + self.assertEqual(response.status_code, 200) + self.assertContains(response, "No polls are available.") + self.assertQuerysetEqual(response.context['latest_question_list'], []) + + def test_past_question(self): + """ + Questions with a pub_date in the past are displayed on the + index page. + """ + create_question(question_text="Past question.", days=-30) + response = self.client.get(reverse('polls:index')) + self.assertQuerysetEqual( + response.context['latest_question_list'], + [''] + ) + + def test_future_question(self): + """ + Questions with a pub_date in the future aren't displayed on + the index page. + """ + create_question(question_text="Future question.", days=30) + response = self.client.get(reverse('polls:index')) + self.assertContains(response, "No polls are available.") + self.assertQuerysetEqual(response.context['latest_question_list'], []) + + def test_future_question_and_past_question(self): + """ + Even if both past and future questions exist, only past questions + are displayed. + """ + create_question(question_text="Past question.", days=-30) + create_question(question_text="Future question.", days=30) + response = self.client.get(reverse('polls:index')) + self.assertQuerysetEqual( + response.context['latest_question_list'], + [''] + ) + + def test_two_past_questions(self): + """ + The questions index page may display multiple questions. + """ + create_question(question_text="Past question 1.", days=-30) + create_question(question_text="Past question 2.", days=-5) + response = self.client.get(reverse('polls:index')) + self.assertQuerysetEqual( + response.context['latest_question_list'], + ['', ''] + ) + + +class QuestionDetailViewTests(TestCase): + def test_future_question(self): + """ + The detail view of a question with a pub_date in the future + returns a 404 not found. + """ + future_question = create_question(question_text='Future question.', days=5) + url = reverse('polls:detail', args=(future_question.id,)) + response = self.client.get(url) + self.assertEqual(response.status_code, 404) + + def test_past_question(self): + """ + The detail view of a question with a pub_date in the past + displays the question's text. + """ + past_question = create_question(question_text='Past Question.', days=-5) + url = reverse('polls:detail', args=(past_question.id,)) + response = self.client.get(url) + self.assertContains(response, past_question.question_text) diff --git a/sami/django/mysite2/polls/urls.py b/sami/django/mysite2/polls/urls.py new file mode 100644 index 0000000..eff2be0 --- /dev/null +++ b/sami/django/mysite2/polls/urls.py @@ -0,0 +1,11 @@ +from django.urls import path + +from . import views + +app_name = 'polls' +urlpatterns = [ + path('', views.IndexView.as_view(), name='index'), + path('/', views.DetailView.as_view(), name='detail'), + path('/results/', views.ResultsView.as_view(), name='results'), + path('/vote/', views.vote, name='vote'), +] diff --git a/sami/django/mysite2/polls/views.py b/sami/django/mysite2/polls/views.py new file mode 100644 index 0000000..68cf7b5 --- /dev/null +++ b/sami/django/mysite2/polls/views.py @@ -0,0 +1,74 @@ +from django.http import HttpResponse, HttpResponseRedirect +#from django.http import Http404 +from django.template import loader +from django.shortcuts import get_object_or_404, render +from django.urls import reverse +from django.views import generic +from django.utils import timezone + +from .models import Choice, Question + + +#def index(request): +# latest_question_list = Question.objects.order_by('-pub_date')[:5] +# context = {'latest_question_list': latest_question_list} +# return render(request, 'polls/index.html', context) +class IndexView(generic.ListView): + template_name = 'polls/index.html' + context_object_name = 'latest_question_list' + + def get_queryset(self): + """ + Return the last five published questions (not including those set to be + published in the future). + """ + return Question.objects.filter( + pub_date__lte=timezone.now() + ).order_by('-pub_date')[:5] + + #"""Return the last five published questions.""" + #return Question.objects.order_by('-pub_date')[:5] + +#def detail(request, question_id): +# #return HttpResponse("You're looking at question %s." % question_id) +# question = get_object_or_404(Question, pk=question_id) +# return render(request, 'polls/detail.html', {'question': question}) +class DetailView(generic.DetailView): + model = Question + template_name = 'polls/detail.html' + + def get_queryset(self): + """ + Excludes any questions that aren't published yet. + """ + return Question.objects.filter(pub_date__lte=timezone.now()) + + +#def results(request, question_id): +# #response = "You're looking at the results of question %s." +# #return HttpResponse(response % question_id) +# question = get_object_or_404(Question, pk=question_id) +# return render(request, 'polls/results.html', {'question': question}) +class ResultsView(generic.DetailView): + model = Question + template_name = 'polls/results.html' + + +def vote(request, question_id): + #return HttpResponse("You're voting on question %s." % question_id) + question = get_object_or_404(Question, pk=question_id) + try: + selected_choice = question.choice_set.get(pk=request.POST['choice']) + except (KeyError, Choice.DoesNotExist): + # Redisplay the question voting form. + return render(request, 'polls/detail.html', { + 'question': question, + 'error_message': "You didn't select a choice.", + }) + else: + selected_choice.votes += 1 + selected_choice.save() + # Always return an HttpResponseRedirect after successfully dealing + # with POST data. This prevents data from being posted twice if a + # user hits the Back button. + return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) diff --git a/sami/ipv6/.#randomnet.py b/sami/ipv6/.#randomnet.py new file mode 120000 index 0000000..fcbec7b --- /dev/null +++ b/sami/ipv6/.#randomnet.py @@ -0,0 +1 @@ +sami@afro-linux-lenovo-b50-30.25798:1595421094 \ No newline at end of file diff --git a/sami/ipv6/randomnet.py b/sami/ipv6/randomnet.py new file mode 100644 index 0000000..80a39ba --- /dev/null +++ b/sami/ipv6/randomnet.py @@ -0,0 +1,25 @@ +#import random +#from netaddr.ip import IPNetwork, IPAddress +#import string +#random.seed() +#ip_a = IPAddress('2001::cafe:0') + random.getrandbits(16) +#ip_n = IPNetwork(ip_a) +#ip_n.prefixlen = 64 + +#print (ip_a) +#print (ip_n) + +""" +Generate a random IPv6 address for a specified subnet +""" + +from random import seed, getrandbits +from ipaddress import IPv6Network, IPv6Address + +subnet = 'fd00::/8' + +seed() +network = IPv6Network(subnet) +address = IPv6Address(network.network_address + getrandbits(network.max_prefixlen - network.prefixlen)) + +print(address) diff --git a/sami/ipv6/test.py b/sami/ipv6/test.py new file mode 100644 index 0000000..208f7ad --- /dev/null +++ b/sami/ipv6/test.py @@ -0,0 +1,17 @@ +#import random +#from ipaddress import IPv6Network, IPv6Address + +#ip_a = IPv6Network('2001:db8::/48') + random.getrandbits +#ip_n = IPv6Network(ip_a) +#ip_n.prefixlen = 64 + +#print (ip_a) +#print (ip_n) + +from ipaddress import IPv6Network +import random + +ula = IPv6Network("fd00::/8") +random_network = IPv6Network(( + ula.network_address + (random.getrandbits(64 - ula.prefixlen) << 64 ), + 64)) diff --git a/sami/learn-python-the-hard-way/__pycache__/Question.cpython-37.pyc b/sami/learn-python-the-hard-way/__pycache__/Question.cpython-37.pyc deleted file mode 100644 index 059710a..0000000 Binary files a/sami/learn-python-the-hard-way/__pycache__/Question.cpython-37.pyc and /dev/null differ diff --git a/sami/learn-python-the-hard-way/ex32.py b/sami/learn-python-the-hard-way/ex32.py index 9e9ab6a..8cb910b 100644 --- a/sami/learn-python-the-hard-way/ex32.py +++ b/sami/learn-python-the-hard-way/ex32.py @@ -2,12 +2,9 @@ the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] - # this first kind of for-loop goes through a listLOOPS AND LISTS for number in the_count: -print(f"This is count {number}") - - + print(f"This is count {number}") #same as above for fruit in fruits: @@ -21,13 +18,11 @@ for i in change: # we can also build lists, first start with an empty one elements = [] - # then use the range function to do 0 to 5 counts for i in range(0, 6): print(f"Adding {i} to the list.") - -# append is a function that lists understand -elements.append(i) + # append is a function that lists understand + elements.append(i) # now we can print them out too for i in elements: diff --git a/sami/learn-python-the-hard-way/overlap.py b/sami/learn-python-the-hard-way/overlap.py new file mode 100644 index 0000000..60e5a2a --- /dev/null +++ b/sami/learn-python-the-hard-way/overlap.py @@ -0,0 +1,29 @@ + +def overlapping(string1, string2): + for i in string1: + for e in string2: + if i == e: + return True + return False + + + + + + + + + + + + + + + + + + +#if address in network: + # do something + # ipaddress.ip_address('2001:DB8::1') +#IPv6Address('2001:db8::1') diff --git a/sami/learn-python-the-hard-way/ungleich-learning-circle b/sami/learn-python-the-hard-way/ungleich-learning-circle deleted file mode 160000 index a0012ef..0000000 --- a/sami/learn-python-the-hard-way/ungleich-learning-circle +++ /dev/null @@ -1 +0,0 @@ -Subproject commit a0012ef6c4d44c875a3173fc746ab0a9259bc531 diff --git a/youngjin.han/django/.gitignore b/youngjin.han/django/.gitignore new file mode 100644 index 0000000..09dd1da --- /dev/null +++ b/youngjin.han/django/.gitignore @@ -0,0 +1 @@ +venv/* diff --git a/youngjin.han/django/django.org b/youngjin.han/django/django.org new file mode 100644 index 0000000..1c79eb5 --- /dev/null +++ b/youngjin.han/django/django.org @@ -0,0 +1,25 @@ +* 2020-07-13 +** note + - none +* 2020-07-10 +** note + - none +* 2020-07-08 +** note + - none +* 2020-07-06 +** note + - none +* 2020-07-04 +** note + - none +* 2020-06-28 +** note + - Research and answer the following questions: (1/2 of the time) + - What is IPv6 ULA? + : unique local address + : prefix is fc00::/7 + - Which registries did exist historically? + : RIR, LIR, NIR, AFRINIC, APNIC, ARIN, LACNIC, RIPE NCC + - How should an IPv6 ULA registry work? + :I do not have a idea. diff --git a/youngjin.han/django/mysite/db.sqlite3 b/youngjin.han/django/mysite/db.sqlite3 new file mode 100644 index 0000000..555268d Binary files /dev/null and b/youngjin.han/django/mysite/db.sqlite3 differ diff --git a/youngjin.han/django/mysite/manage.py b/youngjin.han/django/mysite/manage.py new file mode 100755 index 0000000..afbc784 --- /dev/null +++ b/youngjin.han/django/mysite/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +import os +import sys + +if __name__ == "__main__": + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") + try: + from django.core.management import execute_from_command_line + except ImportError: + # The above import may fail for some other reason. Ensure that the + # issue is really that Django is missing to avoid masking other + # exceptions on Python 2. + try: + import django + except ImportError: + 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?" + ) + raise + execute_from_command_line(sys.argv) diff --git a/youngjin.han/django/mysite/mysite/__init__.py b/youngjin.han/django/mysite/mysite/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/youngjin.han/django/mysite/mysite/__init__.pyc b/youngjin.han/django/mysite/mysite/__init__.pyc new file mode 100644 index 0000000..49b363a Binary files /dev/null and b/youngjin.han/django/mysite/mysite/__init__.pyc differ diff --git a/youngjin.han/django/mysite/mysite/__pycache__/__init__.cpython-37.pyc b/youngjin.han/django/mysite/mysite/__pycache__/__init__.cpython-37.pyc new file mode 100644 index 0000000..787ab4e Binary files /dev/null and b/youngjin.han/django/mysite/mysite/__pycache__/__init__.cpython-37.pyc differ diff --git a/youngjin.han/django/mysite/mysite/__pycache__/settings.cpython-37.pyc b/youngjin.han/django/mysite/mysite/__pycache__/settings.cpython-37.pyc new file mode 100644 index 0000000..47950c9 Binary files /dev/null and b/youngjin.han/django/mysite/mysite/__pycache__/settings.cpython-37.pyc differ diff --git a/youngjin.han/django/mysite/mysite/__pycache__/urls.cpython-37.pyc b/youngjin.han/django/mysite/mysite/__pycache__/urls.cpython-37.pyc new file mode 100644 index 0000000..3995e19 Binary files /dev/null and b/youngjin.han/django/mysite/mysite/__pycache__/urls.cpython-37.pyc differ diff --git a/youngjin.han/django/mysite/mysite/__pycache__/wsgi.cpython-37.pyc b/youngjin.han/django/mysite/mysite/__pycache__/wsgi.cpython-37.pyc new file mode 100644 index 0000000..7e24142 Binary files /dev/null and b/youngjin.han/django/mysite/mysite/__pycache__/wsgi.cpython-37.pyc differ diff --git a/youngjin.han/django/mysite/mysite/settings.py b/youngjin.han/django/mysite/mysite/settings.py new file mode 100644 index 0000000..1c8d420 --- /dev/null +++ b/youngjin.han/django/mysite/mysite/settings.py @@ -0,0 +1,127 @@ +""" +Django settings for mysite project. + +Generated by 'django-admin startproject' using Django 1.11.29. + +For more information on this file, see +https://docs.djangoproject.com/en/1.11/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/1.11/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/1.11/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 't0zf1c_!6i!ul3rgh@)nyd_0i4j%vlvm!slhytg_^s@zp6#w!%' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = [ + "[2a0a:e5c1:120::35]", + "192.168.0.20", + "127.0.0.1", + "2a0a-e5c1-0120-0000-0000-0000-0000-0035.has-a.name", +] + + +# Application definition + +INSTALLED_APPS = [ + 'polls.apps.PollsConfig', + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', +] + +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 = 'mysite.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 = 'mysite.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/1.11/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/1.11/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/1.11/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +#TIME_ZONE = 'UTC' +TIME_ZONE = 'Asia/Seoul' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/1.11/howto/static-files/ + +STATIC_URL = '/static/' diff --git a/youngjin.han/django/mysite/mysite/settings.pyc b/youngjin.han/django/mysite/mysite/settings.pyc new file mode 100644 index 0000000..0773e2d Binary files /dev/null and b/youngjin.han/django/mysite/mysite/settings.pyc differ diff --git a/youngjin.han/django/mysite/mysite/urls.py b/youngjin.han/django/mysite/mysite/urls.py new file mode 100644 index 0000000..7ae405d --- /dev/null +++ b/youngjin.han/django/mysite/mysite/urls.py @@ -0,0 +1,31 @@ +"""mysite URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/1.11/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.conf.urls import url, include + 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) +""" +""" +from django.conf.urls import url +from django.contrib import admin + +urlpatterns = [ + url(r'^admin/', admin.site.urls), +] +""" + +from django.contrib import admin +from django.urls import include, path + +urlpatterns = [ + path('polls/', include('polls.urls')), + path('admin/', admin.site.urls), + ] diff --git a/youngjin.han/django/mysite/mysite/urls.pyc b/youngjin.han/django/mysite/mysite/urls.pyc new file mode 100644 index 0000000..2aa9842 Binary files /dev/null and b/youngjin.han/django/mysite/mysite/urls.pyc differ diff --git a/youngjin.han/django/mysite/mysite/wsgi.py b/youngjin.han/django/mysite/mysite/wsgi.py new file mode 100644 index 0000000..74e7dae --- /dev/null +++ b/youngjin.han/django/mysite/mysite/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for mysite 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/1.11/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") + +application = get_wsgi_application() diff --git a/youngjin.han/django/mysite/polls/__init__.py b/youngjin.han/django/mysite/polls/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/youngjin.han/django/mysite/polls/__init__.pyc b/youngjin.han/django/mysite/polls/__init__.pyc new file mode 100644 index 0000000..a6c1773 Binary files /dev/null and b/youngjin.han/django/mysite/polls/__init__.pyc differ diff --git a/youngjin.han/django/mysite/polls/__pycache__/__init__.cpython-37.pyc b/youngjin.han/django/mysite/polls/__pycache__/__init__.cpython-37.pyc new file mode 100644 index 0000000..c28de56 Binary files /dev/null and b/youngjin.han/django/mysite/polls/__pycache__/__init__.cpython-37.pyc differ diff --git a/youngjin.han/django/mysite/polls/__pycache__/admin.cpython-37.pyc b/youngjin.han/django/mysite/polls/__pycache__/admin.cpython-37.pyc new file mode 100644 index 0000000..773cbe3 Binary files /dev/null and b/youngjin.han/django/mysite/polls/__pycache__/admin.cpython-37.pyc differ diff --git a/youngjin.han/django/mysite/polls/__pycache__/apps.cpython-37.pyc b/youngjin.han/django/mysite/polls/__pycache__/apps.cpython-37.pyc new file mode 100644 index 0000000..ad851ae Binary files /dev/null and b/youngjin.han/django/mysite/polls/__pycache__/apps.cpython-37.pyc differ diff --git a/youngjin.han/django/mysite/polls/__pycache__/models.cpython-37.pyc b/youngjin.han/django/mysite/polls/__pycache__/models.cpython-37.pyc new file mode 100644 index 0000000..b443b18 Binary files /dev/null and b/youngjin.han/django/mysite/polls/__pycache__/models.cpython-37.pyc differ diff --git a/youngjin.han/django/mysite/polls/__pycache__/tests.cpython-37.pyc b/youngjin.han/django/mysite/polls/__pycache__/tests.cpython-37.pyc new file mode 100644 index 0000000..6277b12 Binary files /dev/null and b/youngjin.han/django/mysite/polls/__pycache__/tests.cpython-37.pyc differ diff --git a/youngjin.han/django/mysite/polls/__pycache__/urls.cpython-37.pyc b/youngjin.han/django/mysite/polls/__pycache__/urls.cpython-37.pyc new file mode 100644 index 0000000..27ccfc6 Binary files /dev/null and b/youngjin.han/django/mysite/polls/__pycache__/urls.cpython-37.pyc differ diff --git a/youngjin.han/django/mysite/polls/__pycache__/views.cpython-37.pyc b/youngjin.han/django/mysite/polls/__pycache__/views.cpython-37.pyc new file mode 100644 index 0000000..fc65d7a Binary files /dev/null and b/youngjin.han/django/mysite/polls/__pycache__/views.cpython-37.pyc differ diff --git a/youngjin.han/django/mysite/polls/admin.py b/youngjin.han/django/mysite/polls/admin.py new file mode 100644 index 0000000..74eb2f9 --- /dev/null +++ b/youngjin.han/django/mysite/polls/admin.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.contrib import admin + +# Register your models here. +from .models import Choice, Question + +#admin.site.register(Question) + +#class QuestionAdmin(admin.ModelAdmin): +# fields = ['pub_date', 'question_text'] + +#class QuestionAdmin(admin.ModelAdmin): +# fieldsets = [ +# (None, {'fields': ['question_text']}), +# ('Date information', {'fields': ['pub_date']}), +# ] + +#class ChoiceInline(admin.StackedInline): +class ChoiceInline(admin.TabularInline): + model = Choice + extra = 3 + +class QuestionAdmin(admin.ModelAdmin): + fieldsets = [ + (None, {'fields': ['question_text']}), + ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), + ] + inlines = [ChoiceInline] + #list_display = ('question_text', 'pub_date') + list_display = ('question_text', 'pub_date', 'was_published_recently') + list_filter = ['pub_date'] + search_fields = ['question_text'] + +admin.site.register(Question, QuestionAdmin) +admin.site.register(Choice) diff --git a/youngjin.han/django/mysite/polls/admin.pyc b/youngjin.han/django/mysite/polls/admin.pyc new file mode 100644 index 0000000..7a2fa1a Binary files /dev/null and b/youngjin.han/django/mysite/polls/admin.pyc differ diff --git a/youngjin.han/django/mysite/polls/apps.py b/youngjin.han/django/mysite/polls/apps.py new file mode 100644 index 0000000..9642f78 --- /dev/null +++ b/youngjin.han/django/mysite/polls/apps.py @@ -0,0 +1,8 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.apps import AppConfig + + +class PollsConfig(AppConfig): + name = 'polls' diff --git a/youngjin.han/django/mysite/polls/apps.pyc b/youngjin.han/django/mysite/polls/apps.pyc new file mode 100644 index 0000000..8d2e596 Binary files /dev/null and b/youngjin.han/django/mysite/polls/apps.pyc differ diff --git a/youngjin.han/django/mysite/polls/migrations/0001_initial.py b/youngjin.han/django/mysite/polls/migrations/0001_initial.py new file mode 100644 index 0000000..f05cf0a --- /dev/null +++ b/youngjin.han/django/mysite/polls/migrations/0001_initial.py @@ -0,0 +1,32 @@ +# Generated by Django 3.0.8 on 2020-07-03 12:33 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Question', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('question_text', models.CharField(max_length=200)), + ('pub_date', models.DateTimeField(verbose_name='date published')), + ], + ), + migrations.CreateModel( + name='Choice', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('choice_text', models.CharField(max_length=200)), + ('votes', models.IntegerField(default=0)), + ('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Question')), + ], + ), + ] diff --git a/youngjin.han/django/mysite/polls/migrations/__init__.py b/youngjin.han/django/mysite/polls/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/youngjin.han/django/mysite/polls/migrations/__pycache__/0001_initial.cpython-37.pyc b/youngjin.han/django/mysite/polls/migrations/__pycache__/0001_initial.cpython-37.pyc new file mode 100644 index 0000000..3497e74 Binary files /dev/null and b/youngjin.han/django/mysite/polls/migrations/__pycache__/0001_initial.cpython-37.pyc differ diff --git a/youngjin.han/django/mysite/polls/migrations/__pycache__/__init__.cpython-37.pyc b/youngjin.han/django/mysite/polls/migrations/__pycache__/__init__.cpython-37.pyc new file mode 100644 index 0000000..dc491d7 Binary files /dev/null and b/youngjin.han/django/mysite/polls/migrations/__pycache__/__init__.cpython-37.pyc differ diff --git a/youngjin.han/django/mysite/polls/models.py b/youngjin.han/django/mysite/polls/models.py new file mode 100644 index 0000000..ab1b487 --- /dev/null +++ b/youngjin.han/django/mysite/polls/models.py @@ -0,0 +1,31 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models + +# Create your models here. +import datetime + +from django.db import models +from django.utils import timezone + + +class Question(models.Model): + question_text = models.CharField(max_length=200) + pub_date = models.DateTimeField('date published') + def __str__(self): + return self.question_text + def was_published_recently(self): +# return self.pub_date >= timezone.now() - datetime.timedelta(days=1) + now = timezone.now() + return now - datetime.timedelta(days=1) <= self.pub_date <= now + was_published_recently.admin_order_field = 'pub_date' + was_published_recently.boolean = True + was_published_recently.short_description = 'Published recently?' + +class Choice(models.Model): + question = models.ForeignKey(Question, on_delete=models.CASCADE) + choice_text = models.CharField(max_length=200) + votes = models.IntegerField(default=0) + def __str__(self): + return self.choice_text diff --git a/youngjin.han/django/mysite/polls/models.pyc b/youngjin.han/django/mysite/polls/models.pyc new file mode 100644 index 0000000..15dca98 Binary files /dev/null and b/youngjin.han/django/mysite/polls/models.pyc differ diff --git a/youngjin.han/django/mysite/polls/static/polls/images/background.jpg b/youngjin.han/django/mysite/polls/static/polls/images/background.jpg new file mode 100644 index 0000000..0337b06 Binary files /dev/null and b/youngjin.han/django/mysite/polls/static/polls/images/background.jpg differ diff --git a/youngjin.han/django/mysite/polls/static/polls/style.css b/youngjin.han/django/mysite/polls/static/polls/style.css new file mode 100644 index 0000000..8c79e5e --- /dev/null +++ b/youngjin.han/django/mysite/polls/static/polls/style.css @@ -0,0 +1,7 @@ +li a { + color: green; +} + +body { + background: white url("images/background.jpg") no-repeat; +} diff --git a/youngjin.han/django/mysite/polls/templates/admin/base_site.html b/youngjin.han/django/mysite/polls/templates/admin/base_site.html new file mode 100644 index 0000000..e1b6a8a --- /dev/null +++ b/youngjin.han/django/mysite/polls/templates/admin/base_site.html @@ -0,0 +1,10 @@ +{% extends "admin/base.html" %} + +{% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %} + +{% block branding %} +

Polls Administration +

+{% endblock %} + +{% block nav-global %}{% endblock %} diff --git a/youngjin.han/django/mysite/polls/templates/polls/detail.html b/youngjin.han/django/mysite/polls/templates/polls/detail.html new file mode 100644 index 0000000..3e55544 --- /dev/null +++ b/youngjin.han/django/mysite/polls/templates/polls/detail.html @@ -0,0 +1,12 @@ +

{{ question.question_text }}

+ +{% if error_message %}

{{ error_message }}

{% endif %} + +
+{% csrf_token %} +{% for choice in question.choice_set.all %} + +
+{% endfor %} + +
diff --git a/youngjin.han/django/mysite/polls/templates/polls/index.html b/youngjin.han/django/mysite/polls/templates/polls/index.html new file mode 100644 index 0000000..366983e --- /dev/null +++ b/youngjin.han/django/mysite/polls/templates/polls/index.html @@ -0,0 +1,13 @@ +{% load static %} + + + +{% if latest_question_list %} + +{% else %} +

No polls are available.

+{% endif %} diff --git a/youngjin.han/django/mysite/polls/templates/polls/results.html b/youngjin.han/django/mysite/polls/templates/polls/results.html new file mode 100644 index 0000000..3faf8e4 --- /dev/null +++ b/youngjin.han/django/mysite/polls/templates/polls/results.html @@ -0,0 +1,9 @@ +

{{ question.question_text }}

+ +
    + {% for choice in question.choice_set.all %} +
  • {{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}
  • + {% endfor %} +
+ +Vote again? diff --git a/youngjin.han/django/mysite/polls/tests.py b/youngjin.han/django/mysite/polls/tests.py new file mode 100644 index 0000000..99dd7d0 --- /dev/null +++ b/youngjin.han/django/mysite/polls/tests.py @@ -0,0 +1,134 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.test import TestCase + +# Create your tests here. +import datetime + +from django.test import TestCase +from django.utils import timezone +from django.urls import reverse + +from .models import Question + + +class QuestionModelTests(TestCase): + + def test_was_published_recently_with_future_question(self): + """ + was_published_recently() returns False for questions whose pub_date + is in the future. + """ + time = timezone.now() + datetime.timedelta(days=30) + future_question = Question(pub_date=time) + self.assertIs(future_question.was_published_recently(), False) + + + def test_was_published_recently_with_old_question(self): + """ + was_published_recently() returns False for questions whose pub_date + is older than 1 day. + """ + time = timezone.now() - datetime.timedelta(days=1, seconds=1) + old_question = Question(pub_date=time) + self.assertIs(old_question.was_published_recently(), False) + + def test_was_published_recently_with_recent_question(self): + """ + was_published_recently() returns True for questions whose pub_date + is within the last day. + """ + time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59) + recent_question = Question(pub_date=time) + self.assertIs(recent_question.was_published_recently(), True) + + +def create_question(question_text, days): + """ + Create a question with the given `question_text` and published the + given number of `days` offset to now (negative for questions published + in the past, positive for questions that have yet to be published). + """ + time = timezone.now() + datetime.timedelta(days=days) + return Question.objects.create(question_text=question_text, pub_date=time) + + +class QuestionIndexViewTests(TestCase): + def test_no_questions(self): + """ + If no questions exist, an appropriate message is displayed. + """ + response = self.client.get(reverse('polls:index')) + self.assertEqual(response.status_code, 200) + self.assertContains(response, "No polls are available.") + self.assertQuerysetEqual(response.context['latest_question_list'], []) + + def test_past_question(self): + """ + Questions with a pub_date in the past are displayed on the + index page. + """ + create_question(question_text="Past question.", days=-30) + response = self.client.get(reverse('polls:index')) + self.assertQuerysetEqual( + response.context['latest_question_list'], + [''] + ) + + def test_future_question(self): + """ + Questions with a pub_date in the future aren't displayed on + the index page. + """ + create_question(question_text="Future question.", days=30) + response = self.client.get(reverse('polls:index')) + self.assertContains(response, "No polls are available.") + self.assertQuerysetEqual(response.context['latest_question_list'], []) + + def test_future_question_and_past_question(self): + """ + Even if both past and future questions exist, only past questions + are displayed. + """ + create_question(question_text="Past question.", days=-30) + create_question(question_text="Future question.", days=30) + response = self.client.get(reverse('polls:index')) + self.assertQuerysetEqual( + response.context['latest_question_list'], + [''] + ) + + def test_two_past_questions(self): + """ + The questions index page may display multiple questions. + """ + create_question(question_text="Past question 1.", days=-30) + create_question(question_text="Past question 2.", days=-5) + response = self.client.get(reverse('polls:index')) + self.assertQuerysetEqual( + response.context['latest_question_list'], + ['', ''] + ) + + +class QuestionDetailViewTests(TestCase): + def test_future_question(self): + """ + The detail view of a question with a pub_date in the future + returns a 404 not found. + """ + future_question = create_question(question_text='Future question.', days=5) + url = reverse('polls:detail', args=(future_question.id,)) + response = self.client.get(url) + self.assertEqual(response.status_code, 404) + + def test_past_question(self): + """ + The detail view of a question with a pub_date in the past + displays the question's text. + """ + past_question = create_question(question_text='Past Question.', days=-5) + url = reverse('polls:detail', args=(past_question.id,)) + response = self.client.get(url) + self.assertContains(response, past_question.question_text) diff --git a/youngjin.han/django/mysite/polls/urls.py b/youngjin.han/django/mysite/polls/urls.py new file mode 100644 index 0000000..6eebdcb --- /dev/null +++ b/youngjin.han/django/mysite/polls/urls.py @@ -0,0 +1,19 @@ +from django.urls import path + +from . import views + +app_name = 'polls' +urlpatterns = [ + # ex: /polls/ + #path('', views.index, name='index'), + path('', views.IndexView.as_view(), name='index'), + # ex: /polls/5/ + #path('/', views.detail, name='detail'), + path('/', views.DetailView.as_view(), name='detail'), + # ex: /polls/5/results/ + #path('/results/', views.results, name='results'), + path('/results/', views.ResultsView.as_view(), name='results'), + # ex: /polls/5/vote/ + #path('/vote/', views.vote, name='vote'), + path('/vote/', views.vote, name='vote'), +] diff --git a/youngjin.han/django/mysite/polls/views.py b/youngjin.han/django/mysite/polls/views.py new file mode 100644 index 0000000..427bf61 --- /dev/null +++ b/youngjin.han/django/mysite/polls/views.py @@ -0,0 +1,111 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.shortcuts import render + +# Create your views here. +from django.http import HttpResponse, HttpResponseRedirect +from django.template import loader +from django.http import Http404 +from django.shortcuts import get_object_or_404, render +from django.urls import reverse +from django.views import generic +from django.utils import timezone + +from .models import Choice, Question + + +#def index(request): +# return HttpResponse("Hello, world. You're at the polls index.") + +#def index(request): +# latest_question_list = Question.objects.order_by('-pub_date')[:5] +# output = ', '.join([q.question_text for q in latest_question_list]) +# return HttpResponse(output) + +#def index(request): +# latest_question_list = Question.objects.order_by('-pub_date')[:5] +# template = loader.get_template('polls/index.html') +# context = { +# 'latest_question_list': latest_question_list, +# } +# return HttpResponse(template.render(context, request)) + +#def index(request): +# latest_question_list = Question.objects.order_by('-pub_date')[:5] +# context = {'latest_question_list': latest_question_list} +# return render(request, 'polls/index.html', context) + +class IndexView(generic.ListView): + template_name = 'polls/index.html' + context_object_name = 'latest_question_list' + +# def get_queryset(self): +# """Return the last five published questions.""" +# return Question.objects.order_by('-pub_date')[:5] + + def get_queryset(self): + """ + Return the last five published questions (not including those set to be + published in the future). + """ + return Question.objects.filter( + pub_date__lte=timezone.now() + ).order_by('-pub_date')[:5] + +#def detail(request, question_id): +# return HttpResponse("You're looking at question %s." % question_id) + +#def detail(request, question_id): +# try: +# question = Question.objects.get(pk=question_id) +# except Question.DoesNotExist: +# raise Http404("Question does not exist") +# return render(request, 'polls/detail.html', {'question': question}) + +#def detail(request, question_id): +# question = get_object_or_404(Question, pk=question_id) +# return render(request, 'polls/detail.html', {'question': question}) + +class DetailView(generic.DetailView): + model = Question + template_name = 'polls/detail.html' + + def get_queryset(self): + """ + Excludes any questions that aren't published yet. + """ + return Question.objects.filter(pub_date__lte=timezone.now()) + +#def results(request, question_id): +# response = "You're looking at the results of question %s." +# return HttpResponse(response % question_id) + +#def results(request, question_id): +# question = get_object_or_404(Question, pk=question_id) +# return render(request, 'polls/results.html', {'question': question}) + +class ResultsView(generic.DetailView): + model = Question + template_name = 'polls/results.html' + +#def vote(request, question_id): +# return HttpResponse("You're voting on question %s." % question_id) + +def vote(request, question_id): + question = get_object_or_404(Question, pk=question_id) + try: + selected_choice = question.choice_set.get(pk=request.POST['choice']) + except (KeyError, Choice.DoesNotExist): + # Redisplay the question voting form. + return render(request, 'polls/detail.html', { + 'question': question, + 'error_message': "You didn't select a choice.", + }) + else: + selected_choice.votes += 1 + selected_choice.save() + # Always return an HttpResponseRedirect after successfully dealing + # with POST data. This prevents data from being posted twice if a + # user hits the Back button. + return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) diff --git a/youngjin.han/ipv6/ipv6.org b/youngjin.han/ipv6/ipv6.org new file mode 100644 index 0000000..c72bae3 --- /dev/null +++ b/youngjin.han/ipv6/ipv6.org @@ -0,0 +1,6 @@ +* 2020-07-24 +** note + - none +* 2020-07-22 +** note + - none diff --git a/youngjin.han/ipv6/source/overlap.py b/youngjin.han/ipv6/source/overlap.py new file mode 100644 index 0000000..506ed71 --- /dev/null +++ b/youngjin.han/ipv6/source/overlap.py @@ -0,0 +1,17 @@ +from sys import argv +import ipaddress + +script, ip1, ip2 = argv + + +network_1 = ipaddress.ip_network(ip1) +network_2 = ipaddress.ip_network(ip2) + +#print(list(network_1)) +#print(list(network_2)) + +if True == network_1.overlaps(network_2): + print('overlap') +else: + print('no overlap') + diff --git a/youngjin.han/ipv6/source/randomnet.py b/youngjin.han/ipv6/source/randomnet.py new file mode 100644 index 0000000..2cc835e --- /dev/null +++ b/youngjin.han/ipv6/source/randomnet.py @@ -0,0 +1,59 @@ +# from sys import argv +import argparse +import ipaddress +import random + +# script, prefix = argv + +def main(ipv6net_list, size_list): + """ + 메인 함수 + """ + if 2 == len(ipv6net_list): + ipv6net_src = ipaddress.IPv6Interface(ipv6net_list[0]) + size = ipv6net_list[1] + print('Input : {}'.format(ipv6net_src)) + print('Size : {}'.format(size)) + elif 2 > len(ipv6net_list): + ipv6net_src = ipaddress.IPv6Interface(ipv6net_list[0]) + size = size_list + print('Input : {}'.format(ipv6net_list)) + print('Size : {}'.format(size)) + else: + ipv6net_src = [] + size = size_list + print('Please, Read Help') + + ipv6_rand = 0 + size_rand = int(size)-int(str(ipv6net_src)[str(ipv6net_src).find('/')+1:]) + while size_rand != 0: + if 16 <= size_rand: + ipv6_rand = ipv6_rand << 16 + ipv6_rand += random.randint(0, (2**16)-1) + size_rand -= 16 + else: + ipv6_rand = ipv6_rand << size_rand + ipv6_rand += random.randint(0, (2**size_rand)-1) + size_rand = 0 + +# print('{}'.format(ipaddress.IPv6Network((ipv6net_src)))) +# print('{}'.format(str(ipaddress.IPv6Address((ipv6_rand<<(128-int(size)))))+'/'+size)) +# print('{}'.format(int(size)-int(str(ipv6net_src)[str(ipv6net_src).find('/')+1:]))) + print('Output : {}'.format(str(ipaddress.IPv6Address(int(ipv6net_src)+(ipv6_rand <<(128 - int(size)))))+'/'+size)) + +def get_arguments(): + """ + argument를 파싱해서 가져옴 + """ + parser = argparse.ArgumentParser() + parser.add_argument('ipv6net', nargs='+', help='Example) 2001:db8::/40 or 2001:db8::/40 64', type=str) + parser.add_argument('--size', nargs='?', help='Example) 64...0', default='48', type=str) + + ipv6net_list = parser.parse_args().ipv6net + size_list = parser.parse_args().size + + return ipv6net_list, size_list + +if __name__ == '__main__': + ipv6net_list, size_list = get_arguments() + main(ipv6net_list, size_list) diff --git a/youngjin.han/learning-node02-2020.org b/youngjin.han/learning-node02-2020.org index 0f5c6aa..69a7f6f 100644 --- a/youngjin.han/learning-node02-2020.org +++ b/youngjin.han/learning-node02-2020.org @@ -1,3 +1,165 @@ +* 2020-07-24 +*** IPv6 #2: Generating IPv6 networks +**** DONE Lecture content + CLOSED: [2020-07-30 목 00:43] + - Objective/Problem that we are trying to solve: + - You got one bigger prefix (the one that you get as a + parameter) and you want to create a random subnetwork in it + - Create a random /48 network within a prefix + - Create a python script named *randomnet.py* that accepts 1 + parameter: *prefix* + - The prefix must be an IPv6 network + - The netmask of the prefix should be /48 or smaller (/48.../0) + - Prefixes to be used for testing: + - 2001:db8::/48 + - 2001:db8::/40 + - 2001:db8::/32 + - fd00::/8 + - Possible output: + - 2001:db8:1231::/48 + - Optional + - Allow to specify second parameter that gives the size of the subnetwork +* 2020-07-22 +*** IPv6 #1: IPv6 address uniqueness +**** DONE Lecture content + CLOSED: [2020-07-23 목 00:06] + - Ensure Uniqueness + - Every IPv6 address we register should REPRESENT a /48 + - We need to ensure that we don't register overlapping networks + - Write a python script that checks whether two IPv6 networks are overlapping + - *overlap.py ip1 ip2* + - It should output "overlap" or "no overlap" + - Use the following test IPv6 addresses: + - 2001:db8:: + - 2001:db8:0:2:: + - 2001:db8:1:: + - Assume a netmask of /48 for all of them + - Step 2: Make your script parse ipv6 networks (like + 2001:db8::/48 and 2001:db8::/64) ) and check whether they overlap + - Make use of the python3 module *ipaddress* +* 2020-07-15 +*** Django #7: Tutorial 6 +**** DONE Lecture content + CLOSED: [2020-07-22 수 22:25] + - Environment like in Django 1 and Django 3 + - Ensure your nginx is working + - Paste the URL of your Django server into the chat + - Ensure you can reach the other Django servers + - Follow steps on https://docs.djangoproject.com/en/3.0/intro/tutorial06/ +*** Django #8: Tutorial 7 +**** DONE Lecture content + CLOSED: [2020-07-22 수 22:25] + - Environment like in Django 1 and Django 3 + - Ensure your nginx is working + - Paste the URL of your Django server into the chat + - Ensure you can reach the other Django servers + - Follow steps on https://docs.djangoproject.com/en/3.0/intro/tutorial07/ +* 2020-07-13 +*** Django #6: Tutorial 5 +**** DONE Lecture content + CLOSED: [2020-07-14 화 00:25] + - Environment like in Django 1 and Django 3 + - Ensure your nginx is working + - Follow steps on https://docs.djangoproject.com/en/3.0/intro/tutorial05/ + +* 2020-07-10 +*** Django #5: Tutorial 4 +**** DONE Lecture content + CLOSED: [2020-07-14 화 00:19] + - Environment like in Django 1 and Django 3 + - Ensure your nginx is working + - Follow steps on https://docs.djangoproject.com/en/3.0/intro/tutorial04/ + +* 2020-07-08 +*** Django #4: Tutorial 3 +**** DONE Lecture content + CLOSED: [2020-07-14 화 00:18] + - Environment like in Django 1 and Django 3 + - Ensure your nginx is working + - Follow steps on https://docs.djangoproject.com/en/3.0/intro/tutorial03/ +* 2020-07-06 +*** Django #3: using http and https +**** DONE Lecture content + CLOSED: [2020-07-14 화 00:17] + - We want expose our Django app via https to the world + - We want to allow IPv6 world wide access + - Steps IPv6 + - Ensure you have IPv6 connectivity + - Get a VPN from IPv6VPN.ch if you don't have IPv6 + - Ensure that your firewall allows access to ports 80 and 443 + to your machine + - Coordinate with another participant to test your connection + - The square brackets are needed in the following examples + - curl -vv http://[your ipv6 address] + - curl -vv https://[your ipv6 address] + - Both examples should return "connection refused" + - Find out your Domain name + - We will install an letsencrypt certificate + - Certificates need a name + - The website https://has-a.name provides you with a name + - Find out your name + - Have somebody else ping your name + - Steps webserver + - Install nginx + - Have somebody else run curl -v http://.has-a.name + - Install certbot + - Use certbot to request a certificate for your name + - Use the nginx plugin of certbot + - Have somebody else run curl -v https://.has-a.name + (with httpS!) + - Proxy configuration + - We want nginx to forward the HTTPS requests to django + - We run django on the IPv6 localhost + - python manage.py runserver '[::1]:8000' + - Note: this is different from last session! + - We configure nginx to proxy to django + - Locate the configuration file for the https server (usually + somewhere below /etc/nginx) + - Add a proxy configuration to it + - The proxy block looks similar to this: + location / { + proxy_pass http://localhost:8000; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + } + - Test with the other participants to reach you! + - Add your nginx configuration +* 2020-07-04 +*** Django #2: Tutorial 2 +**** DONE Lecture content + CLOSED: [2020-07-04 토 01:03] + - Tutorial 2 of Django + - Environment like in Django 1 + - https://docs.djangoproject.com/en/3.0/intro/tutorial02/ + - If you have IPv6, allow others to acces your Django server + with: + - python manage.py runserver '[::]:8000' +* 2020-06-28 +*** Django #1: Introduction +**** Objective + - We will build a IPv6 ULA registry with Django in the + next lectures +**** DONE Lecture content + CLOSED: [2020-07-04 토 01:03] + - Create a new directory in your learning cirle repository named "django" + - Write down the answers to the following questions in django/django.org + - Research and answer the following questions: (1/2 of the time) + - What is IPv6 ULA? + - Which registries did exist historically? + - How should an IPv6 ULA registry work? + - Get started with Django + - Create a new python virtual env using `python3 -m venv` + - Create the venv in django/venv + - Create a file .gitignore in django/ + - Add 'venv/' (without the quotes to that file + - Use magit to verify that the venv is being ignored + - Add and commit the .gitignore file + - Inside this virtual env, install django using `pip` + - Go to https://www.djangoproject.com/ + - Finish tutorial 1: https://docs.djangoproject.com/en/3.0/intro/tutorial01/ + - Commit the django code to your repository + - Exclude '*.pyc' in the .gitignore + - Also exclude the sqlite database * 2020-06-17 *** Python #11: **** DONE Lecture content diff --git a/youngjin.han/python-the-hard-way/__pycache__/mystuff.cpython-38.pyc b/youngjin.han/python-the-hard-way/__pycache__/mystuff.cpython-38.pyc new file mode 100644 index 0000000..aa138ca Binary files /dev/null and b/youngjin.han/python-the-hard-way/__pycache__/mystuff.cpython-38.pyc differ