Yoonjunhyeon

HW5-1, 5-2 코드

Showing 76 changed files with 1318 additions and 0 deletions
1 +
2 +# Created by https://www.gitignore.io/api/django
3 +# Edit at https://www.gitignore.io/?templates=django
4 +
5 +### Django ###
6 +*.log
7 +*.pot
8 +*.pyc
9 +__pycache__/
10 +local_settings.py
11 +db.sqlite3
12 +db.sqlite3-journal
13 +media
14 +
15 +# If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/
16 +# in your Git repository. Update and uncomment the following line accordingly.
17 +# <django-project-name>/staticfiles/
18 +
19 +### Django.Python Stack ###
20 +# Byte-compiled / optimized / DLL files
21 +*.py[cod]
22 +*$py.class
23 +
24 +# C extensions
25 +*.so
26 +
27 +# Distribution / packaging
28 +.Python
29 +build/
30 +develop-eggs/
31 +dist/
32 +downloads/
33 +eggs/
34 +.eggs/
35 +lib/
36 +lib64/
37 +parts/
38 +sdist/
39 +var/
40 +wheels/
41 +pip-wheel-metadata/
42 +share/python-wheels/
43 +*.egg-info/
44 +.installed.cfg
45 +*.egg
46 +MANIFEST
47 +
48 +# PyInstaller
49 +# Usually these files are written by a python script from a template
50 +# before PyInstaller builds the exe, so as to inject date/other infos into it.
51 +*.manifest
52 +*.spec
53 +
54 +# Installer logs
55 +pip-log.txt
56 +pip-delete-this-directory.txt
57 +
58 +# Unit test / coverage reports
59 +htmlcov/
60 +.tox/
61 +.nox/
62 +.coverage
63 +.coverage.*
64 +.cache
65 +nosetests.xml
66 +coverage.xml
67 +*.cover
68 +.hypothesis/
69 +.pytest_cache/
70 +
71 +# Translations
72 +*.mo
73 +
74 +# Scrapy stuff:
75 +.scrapy
76 +
77 +# Sphinx documentation
78 +docs/_build/
79 +
80 +# PyBuilder
81 +target/
82 +
83 +# pyenv
84 +.python-version
85 +
86 +# pipenv
87 +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
88 +# However, in case of collaboration, if having platform-specific dependencies or dependencies
89 +# having no cross-platform support, pipenv may install dependencies that don't work, or not
90 +# install all needed dependencies.
91 +#Pipfile.lock
92 +
93 +# celery beat schedule file
94 +celerybeat-schedule
95 +
96 +# SageMath parsed files
97 +*.sage.py
98 +
99 +# Spyder project settings
100 +.spyderproject
101 +.spyproject
102 +
103 +# Rope project settings
104 +.ropeproject
105 +
106 +# Mr Developer
107 +.mr.developer.cfg
108 +.project
109 +.pydevproject
110 +
111 +# mkdocs documentation
112 +/site
113 +
114 +# mypy
115 +.mypy_cache/
116 +.dmypy.json
117 +dmypy.json
118 +
119 +# Pyre type checker
120 +.pyre/
121 +
122 +# End of https://www.gitignore.io/api/django
...\ No newline at end of file ...\ No newline at end of file
1 +# This file must be used with "source bin/activate" *from bash*
2 +# you cannot run it directly
3 +
4 +deactivate () {
5 + # reset old environment variables
6 + if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then
7 + PATH="${_OLD_VIRTUAL_PATH:-}"
8 + export PATH
9 + unset _OLD_VIRTUAL_PATH
10 + fi
11 + if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then
12 + PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}"
13 + export PYTHONHOME
14 + unset _OLD_VIRTUAL_PYTHONHOME
15 + fi
16 +
17 + # This should detect bash and zsh, which have a hash command that must
18 + # be called to get it to forget past commands. Without forgetting
19 + # past commands the $PATH changes we made may not be respected
20 + if [ -n "${BASH:-}" -o -n "${ZSH_VERSION:-}" ] ; then
21 + hash -r
22 + fi
23 +
24 + if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then
25 + PS1="${_OLD_VIRTUAL_PS1:-}"
26 + export PS1
27 + unset _OLD_VIRTUAL_PS1
28 + fi
29 +
30 + unset VIRTUAL_ENV
31 + if [ ! "$1" = "nondestructive" ] ; then
32 + # Self destruct!
33 + unset -f deactivate
34 + fi
35 +}
36 +
37 +# unset irrelevant variables
38 +deactivate nondestructive
39 +
40 +VIRTUAL_ENV="/home/jun/documents/Univ/drf_tutorial/env"
41 +export VIRTUAL_ENV
42 +
43 +_OLD_VIRTUAL_PATH="$PATH"
44 +PATH="$VIRTUAL_ENV/bin:$PATH"
45 +export PATH
46 +
47 +# unset PYTHONHOME if set
48 +# this will fail if PYTHONHOME is set to the empty string (which is bad anyway)
49 +# could use `if (set -u; : $PYTHONHOME) ;` in bash
50 +if [ -n "${PYTHONHOME:-}" ] ; then
51 + _OLD_VIRTUAL_PYTHONHOME="${PYTHONHOME:-}"
52 + unset PYTHONHOME
53 +fi
54 +
55 +if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then
56 + _OLD_VIRTUAL_PS1="${PS1:-}"
57 + if [ "x(env) " != x ] ; then
58 + PS1="(env) ${PS1:-}"
59 + else
60 + if [ "`basename \"$VIRTUAL_ENV\"`" = "__" ] ; then
61 + # special case for Aspen magic directories
62 + # see http://www.zetadev.com/software/aspen/
63 + PS1="[`basename \`dirname \"$VIRTUAL_ENV\"\``] $PS1"
64 + else
65 + PS1="(`basename \"$VIRTUAL_ENV\"`)$PS1"
66 + fi
67 + fi
68 + export PS1
69 +fi
70 +
71 +# This should detect bash and zsh, which have a hash command that must
72 +# be called to get it to forget past commands. Without forgetting
73 +# past commands the $PATH changes we made may not be respected
74 +if [ -n "${BASH:-}" -o -n "${ZSH_VERSION:-}" ] ; then
75 + hash -r
76 +fi
1 +# This file must be used with "source bin/activate.csh" *from csh*.
2 +# You cannot run it directly.
3 +# Created by Davide Di Blasi <davidedb@gmail.com>.
4 +# Ported to Python 3.3 venv by Andrew Svetlov <andrew.svetlov@gmail.com>
5 +
6 +alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; test "\!:*" != "nondestructive" && unalias deactivate'
7 +
8 +# Unset irrelevant variables.
9 +deactivate nondestructive
10 +
11 +setenv VIRTUAL_ENV "/home/jun/documents/Univ/drf_tutorial/env"
12 +
13 +set _OLD_VIRTUAL_PATH="$PATH"
14 +setenv PATH "$VIRTUAL_ENV/bin:$PATH"
15 +
16 +
17 +set _OLD_VIRTUAL_PROMPT="$prompt"
18 +
19 +if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then
20 + if ("env" != "") then
21 + set env_name = "env"
22 + else
23 + if (`basename "VIRTUAL_ENV"` == "__") then
24 + # special case for Aspen magic directories
25 + # see http://www.zetadev.com/software/aspen/
26 + set env_name = `basename \`dirname "$VIRTUAL_ENV"\``
27 + else
28 + set env_name = `basename "$VIRTUAL_ENV"`
29 + endif
30 + endif
31 + set prompt = "[$env_name] $prompt"
32 + unset env_name
33 +endif
34 +
35 +alias pydoc python -m pydoc
36 +
37 +rehash
1 +# This file must be used with ". bin/activate.fish" *from fish* (http://fishshell.org)
2 +# you cannot run it directly
3 +
4 +function deactivate -d "Exit virtualenv and return to normal shell environment"
5 + # reset old environment variables
6 + if test -n "$_OLD_VIRTUAL_PATH"
7 + set -gx PATH $_OLD_VIRTUAL_PATH
8 + set -e _OLD_VIRTUAL_PATH
9 + end
10 + if test -n "$_OLD_VIRTUAL_PYTHONHOME"
11 + set -gx PYTHONHOME $_OLD_VIRTUAL_PYTHONHOME
12 + set -e _OLD_VIRTUAL_PYTHONHOME
13 + end
14 +
15 + if test -n "$_OLD_FISH_PROMPT_OVERRIDE"
16 + functions -e fish_prompt
17 + set -e _OLD_FISH_PROMPT_OVERRIDE
18 + functions -c _old_fish_prompt fish_prompt
19 + functions -e _old_fish_prompt
20 + end
21 +
22 + set -e VIRTUAL_ENV
23 + if test "$argv[1]" != "nondestructive"
24 + # Self destruct!
25 + functions -e deactivate
26 + end
27 +end
28 +
29 +# unset irrelevant variables
30 +deactivate nondestructive
31 +
32 +set -gx VIRTUAL_ENV "/home/jun/documents/Univ/drf_tutorial/env"
33 +
34 +set -gx _OLD_VIRTUAL_PATH $PATH
35 +set -gx PATH "$VIRTUAL_ENV/bin" $PATH
36 +
37 +# unset PYTHONHOME if set
38 +if set -q PYTHONHOME
39 + set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME
40 + set -e PYTHONHOME
41 +end
42 +
43 +if test -z "$VIRTUAL_ENV_DISABLE_PROMPT"
44 + # fish uses a function instead of an env var to generate the prompt.
45 +
46 + # save the current fish_prompt function as the function _old_fish_prompt
47 + functions -c fish_prompt _old_fish_prompt
48 +
49 + # with the original prompt function renamed, we can override with our own.
50 + function fish_prompt
51 + # Save the return status of the last command
52 + set -l old_status $status
53 +
54 + # Prompt override?
55 + if test -n "(env) "
56 + printf "%s%s" "(env) " (set_color normal)
57 + else
58 + # ...Otherwise, prepend env
59 + set -l _checkbase (basename "$VIRTUAL_ENV")
60 + if test $_checkbase = "__"
61 + # special case for Aspen magic directories
62 + # see http://www.zetadev.com/software/aspen/
63 + printf "%s[%s]%s " (set_color -b blue white) (basename (dirname "$VIRTUAL_ENV")) (set_color normal)
64 + else
65 + printf "%s(%s)%s" (set_color -b blue white) (basename "$VIRTUAL_ENV") (set_color normal)
66 + end
67 + end
68 +
69 + # Restore the return status of the previous command.
70 + echo "exit $old_status" | .
71 + _old_fish_prompt
72 + end
73 +
74 + set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"
75 +end
1 +#!/home/jun/documents/Univ/drf_tutorial/env/bin/python3
2 +# EASY-INSTALL-ENTRY-SCRIPT: 'autopep8==1.5.2','console_scripts','autopep8'
3 +__requires__ = 'autopep8==1.5.2'
4 +import re
5 +import sys
6 +from pkg_resources import load_entry_point
7 +
8 +if __name__ == '__main__':
9 + sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
10 + sys.exit(
11 + load_entry_point('autopep8==1.5.2', 'console_scripts', 'autopep8')()
12 + )
1 +#!/home/jun/documents/Univ/drf_tutorial/env/bin/python
2 +
3 +# -*- coding: utf-8 -*-
4 +import re
5 +import sys
6 +
7 +from django.core.management import execute_from_command_line
8 +
9 +if __name__ == '__main__':
10 + sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
11 + sys.exit(execute_from_command_line())
1 +#!/home/jun/documents/Univ/drf_tutorial/env/bin/python
2 +from django.core import management
3 +
4 +if __name__ == "__main__":
5 + management.execute_from_command_line()
1 +#!/home/jun/documents/Univ/drf_tutorial/env/bin/python
2 +
3 +# -*- coding: utf-8 -*-
4 +import re
5 +import sys
6 +
7 +from setuptools.command.easy_install import main
8 +
9 +if __name__ == '__main__':
10 + sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
11 + sys.exit(main())
1 +#!/home/jun/documents/Univ/drf_tutorial/env/bin/python
2 +
3 +# -*- coding: utf-8 -*-
4 +import re
5 +import sys
6 +
7 +from setuptools.command.easy_install import main
8 +
9 +if __name__ == '__main__':
10 + sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
11 + sys.exit(main())
1 +#!/home/jun/documents/Univ/drf_tutorial/env/bin/python
2 +
3 +# -*- coding: utf-8 -*-
4 +import re
5 +import sys
6 +
7 +from pip import main
8 +
9 +if __name__ == '__main__':
10 + sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
11 + sys.exit(main())
1 +#!/home/jun/documents/Univ/drf_tutorial/env/bin/python
2 +
3 +# -*- coding: utf-8 -*-
4 +import re
5 +import sys
6 +
7 +from pip import main
8 +
9 +if __name__ == '__main__':
10 + sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
11 + sys.exit(main())
1 +#!/home/jun/documents/Univ/drf_tutorial/env/bin/python
2 +
3 +# -*- coding: utf-8 -*-
4 +import re
5 +import sys
6 +
7 +from pip import main
8 +
9 +if __name__ == '__main__':
10 + sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
11 + sys.exit(main())
1 +#!/home/jun/documents/Univ/drf_tutorial/env/bin/python3
2 +
3 +# -*- coding: utf-8 -*-
4 +import re
5 +import sys
6 +
7 +from pycodestyle import _main
8 +
9 +if __name__ == '__main__':
10 + sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
11 + sys.exit(_main())
1 +#!/home/jun/documents/Univ/drf_tutorial/env/bin/python
2 +
3 +# -*- coding: utf-8 -*-
4 +import re
5 +import sys
6 +
7 +from pygments.cmdline import main
8 +
9 +if __name__ == '__main__':
10 + sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
11 + sys.exit(main())
1 +/usr/bin/python
...\ No newline at end of file ...\ No newline at end of file
1 +python
...\ No newline at end of file ...\ No newline at end of file
1 +#!/home/jun/documents/Univ/drf_tutorial/env/bin/python
2 +
3 +# -*- coding: utf-8 -*-
4 +import re
5 +import sys
6 +
7 +from sqlparse.__main__ import main
8 +
9 +if __name__ == '__main__':
10 + sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
11 + sys.exit(main())
1 +lib
...\ No newline at end of file ...\ No newline at end of file
1 +home = /usr/bin
2 +include-system-site-packages = false
3 +version = 3.6.9
1 +#!/usr/bin/env python
2 +"""Django's command-line utility for administrative tasks."""
3 +import os
4 +import sys
5 +
6 +
7 +def main():
8 + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tutorial.settings')
9 + try:
10 + from django.core.management import execute_from_command_line
11 + except ImportError as exc:
12 + raise ImportError(
13 + "Couldn't import Django. Are you sure it's installed and "
14 + "available on your PYTHONPATH environment variable? Did you "
15 + "forget to activate a virtual environment?"
16 + ) from exc
17 + execute_from_command_line(sys.argv)
18 +
19 +
20 +if __name__ == '__main__':
21 + main()
File mode changed
1 +from django.contrib import admin
2 +
3 +# Register your models here.
1 +from django.apps import AppConfig
2 +
3 +
4 +class QuickstartConfig(AppConfig):
5 + name = 'quickstart'
1 +from django.db import models
2 +
3 +# Create your models here.
1 +from django.contrib.auth.models import User, Group
2 +from rest_framework import serializers
3 +
4 +
5 +class UserSerializer(serializers.HyperlinkedModelSerializer):
6 + class Meta:
7 + model = User
8 + fields = ['url', 'username', 'email', 'groups']
9 +
10 +
11 +class GroupSerializer(serializers.HyperlinkedModelSerializer):
12 + class Meta:
13 + model = Group
14 + fields = ['url', 'name']
...\ No newline at end of file ...\ No newline at end of file
1 +from django.test import TestCase
2 +
3 +# Create your tests here.
1 +from django.contrib.auth.models import User, Group
2 +from rest_framework import viewsets
3 +from rest_framework import permissions
4 +from quickstart.serializers import UserSerializer, GroupSerializer
5 +
6 +
7 +class UserViewSet(viewsets.ModelViewSet):
8 + """
9 + API endpoint that allows users to be viewed or edited.
10 + """
11 + queryset = User.objects.all().order_by('-date_joined')
12 + serializer_class = UserSerializer
13 + permission_classes = [permissions.IsAuthenticated]
14 +
15 +
16 +class GroupViewSet(viewsets.ModelViewSet):
17 + """
18 + API endpoint that allows groups to be viewed or edited.
19 + """
20 + queryset = Group.objects.all()
21 + serializer_class = GroupSerializer
22 + permission_classes = [permissions.IsAuthenticated]
23 +
1 +appdirs==1.4.3
2 +asgiref==3.2.7
3 +asn1crypto==0.24.0
4 +attrs==17.4.0
5 +Automat==0.6.0
6 +autopep8==1.5.2
7 +blinker==1.4
8 +certifi==2020.4.5.1
9 +chardet==3.0.4
10 +click==6.7
11 +cloud-init==19.4
12 +colorama==0.3.7
13 +command-not-found==0.3
14 +configobj==5.0.6
15 +constantly==15.1.0
16 +coreapi==2.3.3
17 +coreschema==0.0.4
18 +cryptography==2.1.4
19 +distlib==0.3.0
20 +distro-info===0.18ubuntu0.18.04.1
21 +Django==3.0.5
22 +django-cors-headers==3.2.1
23 +django-rest-swagger==2.2.0
24 +djangorestframework==3.11.0
25 +filelock==3.0.12
26 +httpie==0.9.8
27 +httplib2==0.9.2
28 +hyperlink==17.3.1
29 +idna==2.9
30 +importlib-metadata==1.6.0
31 +importlib-resources==1.4.0
32 +incremental==16.10.1
33 +itypes==1.2.0
34 +Jinja2==2.11.2
35 +jsonpatch==1.16
36 +jsonpointer==1.10
37 +jsonschema==2.6.0
38 +keyring==10.6.0
39 +keyrings.alt==3.0
40 +language-selector==0.1
41 +MarkupSafe==1.1.1
42 +netifaces==0.10.4
43 +oauthlib==2.0.6
44 +openapi-codec==1.3.2
45 +PAM==0.4.2
46 +pyasn1==0.4.2
47 +pyasn1-modules==0.2.1
48 +pycodestyle==2.5.0
49 +pycrypto==2.6.1
50 +Pygments==2.6.1
51 +pygobject==3.26.1
52 +PyJWT==1.5.3
53 +pyOpenSSL==17.5.0
54 +pyserial==3.4
55 +python-apt==1.6.5+ubuntu0.2
56 +python-debian==0.1.32
57 +pytz==2020.1
58 +pyxdg==0.25
59 +PyYAML==3.12
60 +requests==2.23.0
61 +requests-unixsocket==0.1.5
62 +SecretStorage==2.3.1
63 +service-identity==16.0.0
64 +simplejson==3.17.0
65 +six==1.14.0
66 +sqlparse==0.3.1
67 +ssh-import-id==5.7
68 +systemd-python==234
69 +Twisted==17.9.0
70 +ufw==0.36
71 +unattended-upgrades==0.1
72 +uritemplate==3.0.1
73 +urllib3==1.25.9
74 +virtualenv==20.0.18
75 +zipp==3.1.0
76 +zope.interface==4.3.2
1 +#!/bin/bash
2 +python manage.py runserver 0.0.0.0:8000
...\ No newline at end of file ...\ No newline at end of file
File mode changed
1 +from django.contrib import admin
2 +
3 +# Register your models here.
1 +from django.apps import AppConfig
2 +
3 +
4 +class SnippetsConfig(AppConfig):
5 + name = 'snippets'
This diff is collapsed. Click to expand it.
1 +from django.db import models
2 +from pygments.lexers import get_all_lexers
3 +from pygments.styles import get_all_styles
4 +from pygments.lexers import get_lexer_by_name
5 +from pygments.formatters.html import HtmlFormatter
6 +from pygments import highlight
7 +
8 +LEXERS = [item for item in get_all_lexers() if item[1]]
9 +LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
10 +STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()])
11 +
12 +
13 +class Snippet(models.Model):
14 + created = models.DateTimeField(auto_now_add=True)
15 + title = models.CharField(max_length=100, blank=True, default='')
16 + code = models.TextField()
17 + linenos = models.BooleanField(default=False)
18 + language = models.CharField(
19 + choices=LANGUAGE_CHOICES, default='python', max_length=100)
20 + style = models.CharField(choices=STYLE_CHOICES,
21 + default='friendly', max_length=100)
22 + owner = models.ForeignKey(
23 + 'auth.User', related_name='snippets', on_delete=models.CASCADE)
24 + highlighted = models.TextField()
25 +
26 + def save(self, *args, **kwargs):
27 + """
28 + Use the `pygments` library to create a highlighted HTML
29 + representation of the code snippet.
30 + """
31 + lexer = get_lexer_by_name(self.language)
32 + linenos = 'table' if self.linenos else False
33 + options = {'title': self.title} if self.title else {}
34 + formatter = HtmlFormatter(style=self.style, linenos=linenos,
35 + full=True, **options)
36 + self.highlighted = highlight(self.code, lexer, formatter)
37 + super(Snippet, self).save(*args, **kwargs)
38 +
39 +
40 +class Meta:
41 + ordering = ['created']
1 +from rest_framework import permissions
2 +
3 +
4 +class IsOwnerOrReadOnly(permissions.BasePermission):
5 + """
6 + Custom permission to only allow owners of an object to edit it.
7 + """
8 +
9 + def has_object_permission(self, request, view, obj):
10 + # Read permissions are allowed to any request,
11 + # so we'll always allow GET, HEAD or OPTIONS requests.
12 + if request.method in permissions.SAFE_METHODS:
13 + return True
14 +
15 + # Write permissions are only allowed to the owner of the snippet.
16 + return obj.owner == request.user
1 +from rest_framework import serializers
2 +from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
3 +from django.contrib.auth.models import User
4 +
5 +
6 +class SnippetSerializer(serializers.HyperlinkedModelSerializer):
7 + owner = serializers.ReadOnlyField(source='owner.username')
8 + highlight = serializers.HyperlinkedIdentityField(
9 + view_name='snippet-highlight', format='html')
10 +
11 + class Meta:
12 + model = Snippet
13 + fields = ['url', 'id', 'highlight', 'owner',
14 + 'title', 'code', 'linenos', 'language', 'style']
15 +
16 +
17 +class UserSerializer(serializers.HyperlinkedModelSerializer):
18 + snippets = serializers.HyperlinkedRelatedField(
19 + many=True, view_name='snippet-detail', read_only=True)
20 +
21 + class Meta:
22 + model = User
23 + fields = ['url', 'id', 'username', 'snippets']
1 +from rest_framework import serializers
2 +from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
3 +
4 +
5 +class SnippetSerializer(serializers.Serializer):
6 + id = serializers.IntegerField(read_only=True)
7 + title = serializers.CharField(
8 + required=False, allow_blank=True, max_length=100)
9 + code = serializers.CharField(style={'base_template': 'textarea.html'})
10 + linenos = serializers.BooleanField(required=False)
11 + language = serializers.ChoiceField(
12 + choices=LANGUAGE_CHOICES, default='python')
13 + style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')
14 +
15 + def create(self, validated_data):
16 + """
17 + Create and return a new `Snippet` instance, given the validated data.
18 + """
19 + return Snippet.objects.create(**validated_data)
20 +
21 + def update(self, instance, validated_data):
22 + """
23 + Update and return an existing `Snippet` instance, given the validated data.
24 + """
25 + instance.title = validated_data.get('title', instance.title)
26 + instance.code = validated_data.get('code', instance.code)
27 + instance.linenos = validated_data.get('linenos', instance.linenos)
28 + instance.language = validated_data.get('language', instance.language)
29 + instance.style = validated_data.get('style', instance.style)
30 + instance.save()
31 + return instance
1 +from rest_framework import serializers
2 +from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
3 +from django.contrib.auth.models import User
4 +
5 +
6 +class SnippetSerializer(serializers.ModelSerializer):
7 + class Meta:
8 + model = Snippet
9 + fields = ['id', 'title', 'code', 'linenos', 'language', 'style']
10 +
11 +
12 +class UserSerializer(serializers.ModelSerializer):
13 + snippets = serializers.PrimaryKeyRelatedField(
14 + many=True, queryset=Snippet.objects.all())
15 + owner = serializers.ReadOnlyField(source='owner.username')
16 +
17 + class Meta:
18 + model = User
19 + fields = ['id', 'username', 'snippets', 'owner']
1 +from django.test import TestCase
2 +
3 +# Create your tests here.
1 +from django.urls import path, include
2 +from rest_framework.routers import DefaultRouter
3 +from snippets import views
4 +
5 +# Create a router and register our viewsets with it.
6 +router = DefaultRouter()
7 +router.register(r'snippets', views.SnippetViewSet)
8 +router.register(r'users', views.UserViewSet)
9 +
10 +# The API URLs are now determined automatically by the router.
11 +urlpatterns = [
12 + path('api/file', views.FileListView.as_view(), name="file"),
13 + path('', include(router.urls)),
14 +]
1 +from django.urls import path
2 +from rest_framework.urlpatterns import format_suffix_patterns
3 +from snippets import views
4 +
5 +# API endpoints
6 +urlpatterns = format_suffix_patterns([
7 + path('', views.api_root),
8 + path('snippets/',
9 + views.SnippetList.as_view(),
10 + name='snippet-list'),
11 + path('snippets/<int:pk>/',
12 + views.SnippetDetail.as_view(),
13 + name='snippet-detail'),
14 + path('snippets/<int:pk>/highlight/',
15 + views.SnippetHighlight.as_view(),
16 + name='snippet-highlight'),
17 + path('users/',
18 + views.UserList.as_view(),
19 + name='user-list'),
20 + path('users/<int:pk>/',
21 + views.UserDetail.as_view(),
22 + name='user-detail')
23 +])
24 +
25 +# tutorial 3&4 url
26 +# urlpatterns = [
27 +# path('snippets/', views.SnippetList.as_view()),
28 +# path('snippets/<int:pk>/', views.SnippetDetail.as_view()),
29 +# path('users/', views.UserList.as_view()),
30 +# path('users/<int:pk>/', views.UserDetail.as_view()),
31 +# path('', views.api_root),
32 +# path('snippets/<int:pk>/highlight/', views.SnippetHighlight.as_view()),
33 +
34 +# ]
35 +
36 +# tutorial. 1&2 url
37 +# urlpatterns = [
38 +# path('snippets/', views.snippet_list),
39 +# path('snippets/<int:pk>/', views.snippet_detail),
40 +# ]
41 +
42 +# urlpatterns = format_suffix_patterns(urlpatterns)
1 +from snippets.views import SnippetViewSet, UserViewSet, api_root
2 +from django.urls import path
3 +from rest_framework import renderers
4 +from rest_framework.urlpatterns import format_suffix_patterns
5 +
6 +snippet_list = SnippetViewSet.as_view({
7 + 'get': 'list',
8 + 'post': 'create'
9 +})
10 +snippet_detail = SnippetViewSet.as_view({
11 + 'get': 'retrieve',
12 + 'put': 'update',
13 + 'patch': 'partial_update',
14 + 'delete': 'destroy'
15 +})
16 +snippet_highlight = SnippetViewSet.as_view({
17 + 'get': 'highlight'
18 +}, renderer_classes=[renderers.StaticHTMLRenderer])
19 +user_list = UserViewSet.as_view({
20 + 'get': 'list'
21 +})
22 +user_detail = UserViewSet.as_view({
23 + 'get': 'retrieve'
24 +})
25 +
26 +urlpatterns = format_suffix_patterns([
27 + path('', api_root),
28 + path('snippets/', snippet_list, name='snippet-list'),
29 + path('snippets/<int:pk>/', snippet_detail, name='snippet-detail'),
30 + path('snippets/<int:pk>/highlight/',
31 + snippet_highlight, name='snippet-highlight'),
32 + path('users/', user_list, name='user-list'),
33 + path('users/<int:pk>/', user_detail, name='user-detail')
34 +])
1 +from rest_framework import renderers
2 +from rest_framework.reverse import reverse
3 +from rest_framework.response import Response
4 +from rest_framework.decorators import api_view
5 +from rest_framework.views import APIView
6 +from rest_framework.decorators import action
7 +from rest_framework import mixins
8 +from rest_framework import generics
9 +from rest_framework import permissions
10 +from rest_framework import viewsets
11 +from django.contrib.auth.models import User
12 +from snippets.models import Snippet
13 +from snippets.serializers import SnippetSerializer
14 +from snippets.serializers import UserSerializer
15 +from snippets.permissions import IsOwnerOrReadOnly
16 +
17 +
18 +class UserViewSet(viewsets.ReadOnlyModelViewSet):
19 + """
20 + This viewset automatically provides `list` and `detail` actions.
21 + """
22 + queryset = User.objects.all()
23 + serializer_class = UserSerializer
24 +
25 +
26 +class SnippetViewSet(viewsets.ModelViewSet):
27 + """
28 + This viewset automatically provides `list`, `create`, `retrieve`,
29 + `update` and `destroy` actions.
30 +
31 + Additionally we also provide an extra `highlight` action.
32 + """
33 + queryset = Snippet.objects.all()
34 + serializer_class = SnippetSerializer
35 + permission_classes = [permissions.IsAuthenticatedOrReadOnly,
36 + IsOwnerOrReadOnly]
37 +
38 + @action(detail=True, renderer_classes=[renderers.StaticHTMLRenderer])
39 + def highlight(self, request, *args, **kwargs):
40 + snippet = self.get_object()
41 + return Response(snippet.highlighted)
42 +
43 + def perform_create(self, serializer):
44 + serializer.save(owner=self.request.user)
45 +
46 +
47 +class SnippetList(generics.ListCreateAPIView):
48 + queryset = Snippet.objects.all()
49 + serializer_class = SnippetSerializer
50 + permission_classes = [permissions.IsAuthenticatedOrReadOnly]
51 +
52 + def perform_create(self, serializer):
53 + serializer.save(owner=self.request.user)
54 +
55 +
56 +class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
57 + queryset = Snippet.objects.all()
58 + serializer_class = SnippetSerializer
59 + permission_classes = [permissions.IsAuthenticatedOrReadOnly,
60 + IsOwnerOrReadOnly]
61 +
62 +
63 +class UserList(generics.ListAPIView):
64 + queryset = User.objects.all()
65 + serializer_class = UserSerializer
66 +
67 +
68 +class UserDetail(generics.RetrieveAPIView):
69 + queryset = User.objects.all()
70 + serializer_class = UserSerializer
71 +
72 +
73 +@api_view(['GET'])
74 +def api_root(request, format=None):
75 + return Response({
76 + 'users': reverse('user-list', request=request, format=format),
77 + 'snippets': reverse('snippet-list', request=request, format=format)
78 + })
79 +
80 +
81 +class SnippetHighlight(generics.GenericAPIView):
82 + queryset = Snippet.objects.all()
83 + renderer_classes = [renderers.StaticHTMLRenderer]
84 +
85 + def get(self, request, *args, **kwargs):
86 + snippet = self.get_object()
87 + return Response(snippet.highlighted)
88 +
89 +class FileListView(APIView):
90 + def get(self, request):
91 + data = {
92 + "search": '',
93 + "limit": 10,
94 + "skip": 0,
95 + "order": "time",
96 + "fileList": [
97 + {
98 + "name": "1.png",
99 + "created": "2020-04-30",
100 + "size": 10234,
101 + "isFolder": False,
102 + "deletedDate": "",
103 + },
104 + {
105 + "name": "2.png",
106 + "created": "2020-04-30",
107 + "size": 3145,
108 + "isFolder": False,
109 + "deletedDate": "",
110 + },
111 + {
112 + "name": "3.png",
113 + "created": "2020-05-01",
114 + "size": 5653,
115 + "isFolder": False,
116 + "deletedDate": "",
117 + },
118 + ]
119 + }
120 + return Response(data)
121 + def post(self, request, format=None):
122 + data = {
123 + "isSuccess": True,
124 + "File": {
125 + "name": "test.jpg",
126 + "created": "2020-05-02",
127 + "deletedDate": "",
128 + "size": 2312,
129 + "isFolder": False
130 + }
131 + }
132 + return Response(data)
133 +# class SnippetList(mixins.ListModelMixin,
134 +# mixins.CreateModelMixin,
135 +# generics.GenericAPIView):
136 +# queryset = Snippet.objects.all()
137 +# serializer_class = SnippetSerializer
138 +
139 +# def get(self, request, *args, **kwargs):
140 +# return self.list(request, *args, **kwargs)
141 +
142 +# def post(self, request, *args, **kwargs):
143 +# return self.create(request, *args, **kwargs)
144 +
145 +
146 +# class SnippetDetail(mixins.RetrieveModelMixin,
147 +# mixins.UpdateModelMixin,
148 +# mixins.DestroyModelMixin,
149 +# generics.GenericAPIView):
150 +# queryset = Snippet.objects.all()
151 +# serializer_class = SnippetSerializer
152 +
153 +# def get(self, request, *args, **kwargs):
154 +# return self.retrieve(request, *args, **kwargs)
155 +
156 +# def put(self, request, *args, **kwargs):
157 +# return self.update(request, *args, **kwargs)
158 +
159 +# def delete(self, request, *args, **kwargs):
160 +# return self.destroy(request, *args, **kwargs)
1 +from django.http import HttpResponse, JsonResponse
2 +from django.views.decorators.csrf import csrf_exempt
3 +from rest_framework.parsers import JSONParser
4 +from snippets.models import Snippet
5 +from snippets.serializers import SnippetSerializer
6 +
7 +
8 +@csrf_exempt
9 +def snippet_list(request):
10 + """
11 + List all code snippets, or create a new snippet.
12 + """
13 + if request.method == 'GET':
14 + snippets = Snippet.objects.all()
15 + serializer = SnippetSerializer(snippets, many=True)
16 + return JsonResponse(serializer.data, safe=False)
17 +
18 + elif request.method == 'POST':
19 + data = JSONParser().parse(request)
20 + serializer = SnippetSerializer(data=data)
21 + if serializer.is_valid():
22 + serializer.save()
23 + return JsonResponse(serializer.data, status=201)
24 + return JsonResponse(serializer.errors, status=400)
25 +
26 +
27 +@csrf_exempt
28 +def snippet_detail(request, pk):
29 + """
30 + Retrieve, update or delete a code snippet.
31 + """
32 + try:
33 + snippet = Snippet.objects.get(pk=pk)
34 + except Snippet.DoesNotExist:
35 + return HttpResponse(status=404)
36 +
37 + if request.method == 'GET':
38 + serializer = SnippetSerializer(snippet)
39 + return JsonResponse(serializer.data)
40 +
41 + elif request.method == 'PUT':
42 + data = JSONParser().parse(request)
43 + serializer = SnippetSerializer(snippet, data=data)
44 + if serializer.is_valid():
45 + serializer.save()
46 + return JsonResponse(serializer.data)
47 + return JsonResponse(serializer.errors, status=400)
48 +
49 + elif request.method == 'DELETE':
50 + snippet.delete()
51 + return HttpResponse(status=204)
1 +from rest_framework import status
2 +from rest_framework.decorators import api_view
3 +from rest_framework.response import Response
4 +from snippets.models import Snippet
5 +from snippets.serializers import SnippetSerializer
6 +
7 +
8 +@api_view(['GET', 'POST'])
9 +def snippet_list(request):
10 + """
11 + List all code snippets, or create a new snippet.
12 + """
13 + if request.method == 'GET':
14 + snippets = Snippet.objects.all()
15 + serializer = SnippetSerializer(snippets, many=True)
16 + return Response(serializer.data)
17 +
18 + elif request.method == 'POST':
19 + serializer = SnippetSerializer(data=request.data)
20 + if serializer.is_valid():
21 + serializer.save()
22 + return Response(serializer.data, status=status.HTTP_201_CREATED)
23 + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
24 +
25 +
26 +@api_view(['GET', 'PUT', 'DELETE'])
27 +def snippet_detail(request, pk):
28 + """
29 + Retrieve, update or delete a code snippet.
30 + """
31 + try:
32 + snippet = Snippet.objects.get(pk=pk)
33 + except Snippet.DoesNotExist:
34 + return Response(status=status.HTTP_404_NOT_FOUND)
35 +
36 + if request.method == 'GET':
37 + serializer = SnippetSerializer(snippet)
38 + return Response(serializer.data)
39 +
40 + elif request.method == 'PUT':
41 + serializer = SnippetSerializer(snippet, data=request.data)
42 + if serializer.is_valid():
43 + serializer.save()
44 + return Response(serializer.data)
45 + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
46 +
47 + elif request.method == 'DELETE':
48 + snippet.delete()
49 + return Response(status=status.HTTP_204_NO_CONTENT)
1 +from snippets.models import Snippet
2 +from snippets.serializers import SnippetSerializer
3 +from django.http import Http404
4 +from rest_framework.views import APIView
5 +from rest_framework.response import Response
6 +from rest_framework import status
7 +
8 +
9 +class SnippetList(APIView):
10 + """
11 + List all snippets, or create a new snippet.
12 + """
13 +
14 + def get(self, request, format=None):
15 + snippets = Snippet.objects.all()
16 + serializer = SnippetSerializer(snippets, many=True)
17 + return Response(serializer.data)
18 +
19 + def post(self, request, format=None):
20 + serializer = SnippetSerializer(data=request.data)
21 + if serializer.is_valid():
22 + serializer.save()
23 + return Response(serializer.data, status=status.HTTP_201_CREATED)
24 + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
25 +
26 +
27 +class SnippetDetail(APIView):
28 + """
29 + Retrieve, update or delete a snippet instance.
30 + """
31 +
32 + def get_object(self, pk):
33 + try:
34 + return Snippet.objects.get(pk=pk)
35 + except Snippet.DoesNotExist:
36 + raise Http404
37 +
38 + def get(self, request, pk, format=None):
39 + snippet = self.get_object(pk)
40 + serializer = SnippetSerializer(snippet)
41 + return Response(serializer.data)
42 +
43 + def put(self, request, pk, format=None):
44 + snippet = self.get_object(pk)
45 + serializer = SnippetSerializer(snippet, data=request.data)
46 + if serializer.is_valid():
47 + serializer.save()
48 + return Response(serializer.data)
49 + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
50 +
51 + def delete(self, request, pk, format=None):
52 + snippet = self.get_object(pk)
53 + snippet.delete()
54 + return Response(status=status.HTTP_204_NO_CONTENT)
File mode changed
1 +"""
2 +ASGI config for tutorial project.
3 +
4 +It exposes the ASGI callable as a module-level variable named ``application``.
5 +
6 +For more information on this file, see
7 +https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
8 +"""
9 +
10 +import os
11 +
12 +from django.core.asgi import get_asgi_application
13 +
14 +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tutorial.settings')
15 +
16 +application = get_asgi_application()
1 +"""
2 +Django settings for tutorial project.
3 +
4 +Generated by 'django-admin startproject' using Django 3.0.5.
5 +
6 +For more information on this file, see
7 +https://docs.djangoproject.com/en/3.0/topics/settings/
8 +
9 +For the full list of settings and their values, see
10 +https://docs.djangoproject.com/en/3.0/ref/settings/
11 +"""
12 +
13 +import os
14 +
15 +# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
16 +BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17 +
18 +
19 +# Quick-start development settings - unsuitable for production
20 +# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
21 +
22 +# SECURITY WARNING: keep the secret key used in production secret!
23 +SECRET_KEY = 'vqsbba_j(l_he_x6-++=(*g_@zq#tka6rb_43rt$re*n5iic)j'
24 +
25 +# SECURITY WARNING: don't run with debug turned on in production!
26 +DEBUG = True
27 +
28 +ALLOWED_HOSTS = []
29 +
30 +
31 +# Application definition
32 +
33 +REST_FRAMEWORK = {
34 + 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
35 + 'PAGE_SIZE': 10
36 +}
37 +
38 +INSTALLED_APPS = [
39 + 'django.contrib.admin',
40 + 'django.contrib.auth',
41 + 'django.contrib.contenttypes',
42 + 'django.contrib.sessions',
43 + 'django.contrib.messages',
44 + 'django.contrib.staticfiles',
45 + 'rest_framework',
46 + 'quickstart',
47 + 'snippets.apps.SnippetsConfig',
48 +]
49 +
50 +MIDDLEWARE = [
51 + 'django.middleware.security.SecurityMiddleware',
52 + 'django.contrib.sessions.middleware.SessionMiddleware',
53 + 'django.middleware.common.CommonMiddleware',
54 + 'django.middleware.csrf.CsrfViewMiddleware',
55 + 'django.contrib.auth.middleware.AuthenticationMiddleware',
56 + 'django.contrib.messages.middleware.MessageMiddleware',
57 + 'django.middleware.clickjacking.XFrameOptionsMiddleware',
58 +]
59 +
60 +ROOT_URLCONF = 'tutorial.urls'
61 +
62 +TEMPLATES = [
63 + {
64 + 'BACKEND': 'django.template.backends.django.DjangoTemplates',
65 + 'DIRS': [],
66 + 'APP_DIRS': True,
67 + 'OPTIONS': {
68 + 'context_processors': [
69 + 'django.template.context_processors.debug',
70 + 'django.template.context_processors.request',
71 + 'django.contrib.auth.context_processors.auth',
72 + 'django.contrib.messages.context_processors.messages',
73 + ],
74 + },
75 + },
76 +]
77 +
78 +WSGI_APPLICATION = 'tutorial.wsgi.application'
79 +
80 +
81 +# Database
82 +# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
83 +
84 +DATABASES = {
85 + 'default': {
86 + 'ENGINE': 'django.db.backends.sqlite3',
87 + 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
88 + }
89 +}
90 +
91 +
92 +# Password validation
93 +# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
94 +
95 +AUTH_PASSWORD_VALIDATORS = [
96 + {
97 + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
98 + },
99 + {
100 + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
101 + },
102 + {
103 + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
104 + },
105 + {
106 + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
107 + },
108 +]
109 +
110 +
111 +# Internationalization
112 +# https://docs.djangoproject.com/en/3.0/topics/i18n/
113 +
114 +LANGUAGE_CODE = 'en-us'
115 +
116 +TIME_ZONE = 'UTC'
117 +
118 +USE_I18N = True
119 +
120 +USE_L10N = True
121 +
122 +USE_TZ = True
123 +
124 +
125 +# Static files (CSS, JavaScript, Images)
126 +# https://docs.djangoproject.com/en/3.0/howto/static-files/
127 +
128 +STATIC_URL = '/static/'
1 +"""tutorial URL Configuration
2 +
3 +The `urlpatterns` list routes URLs to views. For more information please see:
4 + https://docs.djangoproject.com/en/3.0/topics/http/urls/
5 +Examples:
6 +Function views
7 + 1. Add an import: from my_app import views
8 + 2. Add a URL to urlpatterns: path('', views.home, name='home')
9 +Class-based views
10 + 1. Add an import: from other_app.views import Home
11 + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
12 +Including another URLconf
13 + 1. Import the include() function: from django.urls import include, path
14 + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
15 +"""
16 +from django.urls import include, path
17 +from django.conf.urls import include
18 +from rest_framework import routers
19 +from quickstart import views
20 +
21 +router = routers.DefaultRouter()
22 +router.register(r'users', views.UserViewSet)
23 +router.register(r'groups', views.GroupViewSet)
24 +
25 +# Wire up our API using automatic URL routing.
26 +# Additionally, we include login URLs for the browsable API.
27 +urlpatterns = [
28 + path('', include(router.urls)),
29 + path('api-auth/', include('rest_framework.urls')),
30 + path('', include('snippets.urls')),
31 +]
1 +"""
2 +WSGI config for tutorial project.
3 +
4 +It exposes the WSGI callable as a module-level variable named ``application``.
5 +
6 +For more information on this file, see
7 +https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
8 +"""
9 +
10 +import os
11 +
12 +from django.core.wsgi import get_wsgi_application
13 +
14 +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tutorial.settings')
15 +
16 +application = get_wsgi_application()