Add PostView for handling CRUD operations on posts

This commit is contained in:
Jean Lionel Ndabaga 2024-03-11 00:34:18 +02:00
parent d9cdada41f
commit 2d432ca37d
6 changed files with 153 additions and 515 deletions

20
api/serializers.py Normal file
View file

@ -0,0 +1,20 @@
from rest_framework import serializers
from .models import *
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
class TypeSerializer(serializers.ModelSerializer):
class Meta:
model = Type
fields = ['name']
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ['image', 'title', 'content', 'post_type', 'date_posted', 'author']

View file

@ -1,5 +1,8 @@
from django.urls import path from django.urls import path
from .views import PostView
urlpatterns = [ urlpatterns = [
path('post/', PostView.as_view()),
path('post/<int:pk>/', PostView.as_view()),
] ]

View file

@ -1,3 +1,96 @@
from django.shortcuts import render from django.http import JsonResponse
from rest_framework.views import APIView
from .models import *
from .serializers import *
# Create your views here. class PostView(APIView):
"""
A view for handling CRUD operations on Post objects.
Methods:
- get: Retrieve all posts.
- post: Create a new post.
- put: Update an existing post.
- delete: Delete a post.
"""
def get(self, request):
"""
Retrieve all posts.
Parameters:
request (HttpRequest): The HTTP request object.
Returns:
JsonResponse: A JSON response containing the serialized data of all posts.
"""
try:
posts = Post.objects.all()
serializer = PostSerializer(posts, many=True)
return JsonResponse(serializer.data, safe=False)
except Exception as e:
return JsonResponse({'error': str(e)}, status=500)
def post(self, request):
"""
Create a new post.
Parameters:
request (HttpRequest): The HTTP request object.
Returns:
JsonResponse: A JSON response containing the serialized data of the created post.
If the request data is invalid, returns a JSON response with the serializer errors and status 400.
"""
try:
serializer = PostSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
except Exception as e:
return JsonResponse({'error': str(e)}, status=500)
def put(self, request, pk):
"""
Update an existing post.
Parameters:
request (HttpRequest): The HTTP request object.
pk (int): The primary key of the post to be updated.
Returns:
JsonResponse: A JSON response containing the serialized data of the updated post.
If the request data is invalid, returns a JSON response with the serializer errors and status 400.
"""
try:
post = Post.objects.get(pk=pk)
serializer = PostSerializer(post, data=request.data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=400)
except Post.DoesNotExist:
return JsonResponse({'error': 'Post not found'}, status=404)
except Exception as e:
return JsonResponse({'error': str(e)}, status=500)
def delete(self, request, pk):
"""
Delete a post.
Parameters:
request (HttpRequest): The HTTP request object.
pk (int): The primary key of the post to be deleted.
Returns:
JsonResponse: A JSON response with status 204 indicating successful deletion.
"""
try:
post = Post.objects.get(pk=pk)
post.delete()
return JsonResponse(status=204)
except Post.DoesNotExist:
return JsonResponse({'error': 'Post not found'}, status=404)
except Exception as e:
return JsonResponse({'error': str(e)}, status=500)

View file

@ -43,6 +43,7 @@ INSTALLED_APPS = [
'django.contrib.staticfiles', 'django.contrib.staticfiles',
'rest_framework', 'rest_framework',
'corsheaders', 'corsheaders',
'drf_yasg',
'api', 'api',
] ]
@ -57,6 +58,15 @@ MIDDLEWARE = [
'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',
] ]
# SWAGGER SETTINGS
SWAGGER_SETTINGS = {
'SECURITY_DEFINITIONS': {
'Basic': {
'type': 'basic'
}
}
}
ROOT_URLCONF = 'buffer_clone_backend.urls' ROOT_URLCONF = 'buffer_clone_backend.urls'
TEMPLATES = [ TEMPLATES = [

View file

@ -18,8 +18,24 @@ from django.contrib import admin
from django.urls import path, include from django.urls import path, include
from django.conf import settings from django.conf import settings
from django.conf.urls.static import static from django.conf.urls.static import static
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
schema_view = get_schema_view(
openapi.Info(
title="Buffer Clone API",
default_version='v1',
description="An API for handling CRUD operations on posts.",
),
public=True,
permission_classes=(permissions.AllowAny,),
)
urlpatterns = [ urlpatterns = [
path('ui/', schema_view.with_ui('swagger',
cache_timeout=0), name='schema-swagger-ui'),
path('admin/', admin.site.urls), path('admin/', admin.site.urls),
path('api-auth/', include('rest_framework.urls')), path('api-auth/', include('rest_framework.urls')),
path('api/', include('api.urls')), path('api/', include('api.urls')),

View file

@ -1,526 +1,22 @@
aardwolf==0.2.2
adblockparser==0.7
aesedb==0.1.3
aiocmd==0.1.2
aioconsole==0.7.0
aiodns==3.1.1
aiofiles==23.2.1
aiohttp==3.9.1
aiomultiprocess==0.9.0
aioquic==0.9.25
aiosignal==1.3.1
aiosmb==0.4.4
aiosqlite==0.17.0
aiowinreg==0.0.7
ajpy==0.0.5
altgraph==0.17.4
aniso8601==9.0.1
anyio==4.2.0
appdirs==1.4.4
arc4==0.3.0
argcomplete==3.1.4
asciitree==0.3.3
asgiref==3.7.2 asgiref==3.7.2
asn1crypto==1.5.1 astroid==3.1.0
asn1tools==0.164.0
astroid==3.0.3
asttokens==2.4.1
asyauth==0.0.9
async-timeout==4.0.3
asysocks==0.2.2
attrs==23.2.0
autocommand==2.2.2
Automat==22.10.0
Babel==2.10.3
backoff==2.2.1
bcrypt==3.2.2
beautifulsoup4==4.12.3
beniget==0.4.1
bidict==0.22.1
binwalk==2.3.3
bitstruct==8.15.1
blinker==1.7.0
bluepy==1.3.0
Brlapi==0.8.5
Brotli==1.1.0
catfish==4.16.4
censys==2.2.11
certifi==2023.11.17
certipy-ad==4.7.0
chardet==5.2.0
charset-normalizer==3.3.2
cheroot==10.0.0+ds1
CherryPy==18.9.0
cherrypy-cors==1.6
click==8.1.6
click-plugins==1.1.1
colorama==0.4.6
constantly==23.10.4
contourpy==1.0.7
crackmapexec==5.4.0
crispy-tailwind==1.0.0
cryptography==41.0.7
cssselect==1.2.0
cupshelpers==1.0
cycler==0.11.0
dbus-python==1.3.2
decorator==5.1.1
Deprecated==1.2.14
dicttoxml==1.7.15
dill==0.3.8 dill==0.3.8
diskcache==5.4.0 Django==5.0.3
distlib==0.3.8 django-cors-headers==4.3.1
distro==1.9.0 djangorestframework==3.14.0
distro-info==1.7 drf-yasg==1.21.7
Django==5.0.1 inflection==0.5.1
django-crispy-forms==2.1
django-filter==23.5
dnslib==0.9.24
dnspython==2.6.1
docopt==0.6.2
donut-shellcode==0.9.3
dropbox==11.36.2
dsinternals==1.2.4
ecdsa==0.18.0
et-xmlfile==1.0.1
executing==2.0.1
ExifRead==3.0.0
fastapi==0.101.0
fierce==1.5.0
filelock==3.13.1
flasgger==0.9.7.2.dev2
Flask==2.2.5
Flask-RESTful==0.3.9
Flask-SocketIO==5.3.2
fonttools==4.46.0
frozenlist==1.4.0
fs==2.4.16
galternatives==1.0.9
gast==0.5.2
GDAL==3.8.4
gpg==1.18.0
graphviz==0.20.2.dev0
greenlet==3.0.1
h11==0.14.0
h2==4.1.0
hashID==3.1.4
hiredis==2.3.2
hpack==4.0.0
html5lib==1.1
httpagentparser==1.9.1
httpcore==1.0.2
httplib2==0.20.4
httpx==0.26.0
humanize==4.9.0
hyperframe==6.0.0
hyperlink==21.0.0
idna==3.6
impacket==0.11.0
importlib-metadata==4.12.0
importlib-resources==6.0.1
incremental==22.10.0
inflect==7.0.0
iniconfig==1.1.1
invoke==2.0.0
ipwhois==1.2.0
IPy==1.1
ipython==8.20.0
isort==5.13.2 isort==5.13.2
itsdangerous==2.1.2
jaraco.collections==4.2.0
jaraco.context==4.3.0
jaraco.functools==4.0.0
jaraco.text==3.11.1
jedi==0.19.1
Jinja2==3.1.2
jq==1.6.0
jsonpointer==2.3
jsonschema==4.10.3
kaitaistruct==0.10
kali-tweaks==2023.3.2
KismetCaptureBtGeiger==2021.7.1
KismetCaptureFreaklabsZigbee==2018.7.0
KismetCaptureRtl433==2020.10.1
KismetCaptureRtladsb==2020.10.1
KismetCaptureRtlamr==2020.10.1
kiwisolver==0.0.0
lazr.restfulclient==0.14.6
lazr.uri==1.0.6
ldap3==2.9.1
ldapdomaindump==0.9.4
libevdev==0.5
lightdm-gtk-greeter-settings==1.2.2
limits==3.6.0
louis==3.28.0
lsassy==3.1.6
lxml==5.1.0
lz4==4.0.2+dfsg
macholib==1.16.3
Mako==1.3.2.dev0
Markdown==3.5.2
markdown-it-py==3.0.0
MarkupSafe==2.1.5
masky==0.1.1
matplotlib==3.6.3
matplotlib-inline==0.1.6
mccabe==0.7.0 mccabe==0.7.0
mdurl==0.1.2 packaging==24.0
mechanize==0.4.9
meson==1.2.3
minidump==0.0.21
minikerberos==0.4.0
mistune0==0.8.4
mitmproxy==10.2.2
more-itertools==10.2.0
mpmath==0.0.0
msgpack==1.0.3
msldap==0.4.7
multidict==6.0.4
mysqlclient==1.4.6
nassl==5.0.1
neo4j==5.2.dev0
neobolt==1.7.17
neotime==1.7.4
netaddr==0.10.1
netifaces==0.11.0
networkx==2.8.8
ntlm-auth==1.5.0
numpy==1.24.2
oauthlib==3.2.2
objgraph==3.6.1
olefile==0.46
onboard==1.4.1
openpyxl==3.1.2
oscrypto==1.3.0
packaging==23.2
paramiko==2.12.0
parso==0.8.3
passlib==1.7.4
Paste==3.7.1
PasteDeploy==3.1.0
PasteScript==3.2.1
patator==1.0
pcapy==0.11.5.dev0
pexpect==4.9.0
phonenumbers==8.12.57
pillow==10.2.0 pillow==10.2.0
platformdirs==4.2.0 platformdirs==4.2.0
pluggy==1.4.0 pylint==3.1.0
pluginbase==1.0.1
ply==3.11
portend==3.1.0
prettytable==3.6.0
prompt-toolkit==3.0.43
protobuf==4.21.12
psycopg2==2.9.9
ptyprocess==0.7.0
publicsuffix2==2.20191221
publicsuffixlist==0.9.3
pure-eval==0.0.0
pyasn1==0.4.8
pyasn1-modules==0.2.8
pyasyncore==1.0.2
pycairo==1.25.1
pycares==4.4.0
pycryptodomex==3.11.0
pycups==2.0.1
pycurl==7.45.2
pydantic==1.10.14
PyDispatcher==2.0.5
pydot==1.4.2
pyee==11.1.0
pygame==2.5.2
pygexf==0.2.2
Pygments==2.17.2
PyGObject==3.46.0
pygraphviz==1.7
PyHamcrest==2.1.0
pyinotify==0.9.6
PyInstaller==3.5+498e6ee058
PyJWT==2.7.0
pylint==3.0.3
pylint-django==2.5.5 pylint-django==2.5.5
pylint-plugin-utils==0.8.2 pylint-plugin-utils==0.8.2
pylnk3==0.4.2
pylsqpack==0.3.18
pymssql==2.2.11
PyMySQL==1.0.2
PyNaCl==1.5.0
pyOpenSSL==23.2.0
pyparsing==3.1.1
PyPDF2==2.12.1
pyperclip==1.8.2
pyppeteer==1.0.1
pypsrp==0.8.1
pypykatz==0.6.6
PyQt5==5.15.10
PyQt5-sip==12.13.0
PyQt6==6.6.1
PyQt6-sip==13.6.0
pyqtgraph==0.13.3
pyrsistent==0.20.0
PySecretSOCKS==0.9.1
pyserial==3.5
pysmi==0.3.4
pysnmp==4.4.12
PySocks==1.7.1
pyspnego==0.8.0
pytest==7.4.4
python-apt==2.7.5
python-dateutil==2.8.2
python-decouple==3.8
python-docx==1.1.0
python-dotenv==1.0.1 python-dotenv==1.0.1
python-engineio==4.3.4
python-jose==3.3.0
python-magic==0.4.27
python-multipart==0.0.6
python-pam==2.0.2
python-pptx==0.6.18
python-socketio==5.7.2
pythran==0.15.0
pytz==2024.1 pytz==2024.1
pyudev==0.24.0
pyVNC==0.1
pywerview==0.3.3
pyxdg==0.28
PyYAML==6.0.1 PyYAML==6.0.1
redis==4.3.4
repoze.lru==0.7
requests==2.31.0
requests-file==1.5.1
requests-ntlm==1.1.0
requests-toolbelt==1.0.0
retrying==1.3.3
rfc3987==1.3.8
rich==13.3.1
Routes==2.5.1
rq==1.15.1
rsa==4.9
ruamel.yaml==0.17.21
ruamel.yaml.clib==0.2.8
scapy==2.5.0
SciPy==1.11.4
secure==0.3.0
service-identity==24.1.0
shodan==1.30.1
simplejson==3.19.2
six==1.16.0
slowapi==0.1.4
smbmap==1.9.2
sniffio==1.3.0
sortedcontainers==2.4.0
soupsieve==2.5
SQLAlchemy==1.4.50
SQLAlchemy-Utc==0.14.0
sqlparse==0.4.4 sqlparse==0.4.4
sslyze==5.2.0 tomlkit==0.12.4
stack-data==0.6.3
starlette==0.31.1
stone==3.3.1
sympy==1.12
Tempita==0.5.2
tempora==5.5.0
termcolor==1.1.0
terminaltables==3.1.10
theHarvester==4.5.1
tldextract==3.1.2
tls-parser==1.2.2
tomli==2.0.1
tomlkit==0.12.3
tornado==6.4
tqdm==4.64.1
traitlets==5.5.0
Twisted==23.10.0
types-aiofiles==23.2
types-aws-xray-sdk==2.12
types-beautifulsoup4==4.12
types-bleach==6.1
types-boltons==23.0
types-boto==2.49
types-braintree==4.24
types-cachetools==5.3
types-caldav==1.3
types-cffi==1.16
types-chevron==0.14
types-click-default-group==1.2
types-click-spinner==0.1
types-colorama==0.4
types-commonmark==0.9
types-console-menu==0.8
types-croniter==2.0
types-dateparser==1.1
types-decorator==5.1
types-Deprecated==1.2
types-dockerfile-parse==2.0
types-docopt==0.6
types-docutils==0.20
types-editdistance==0.6
types-entrypoints==0.4
types-ExifRead==3.0
types-first==2.0
types-flake8-2020==1.8
types-flake8-bugbear==23.9.16
types-flake8-builtins==2.2
types-flake8-docstrings==1.7
types-flake8-plugin-utils==1.3
types-flake8-rst-docstrings==0.3
types-flake8-simplify==0.21
types-flake8-typing-imports==1.15
types-Flask-Cors==4.0
types-Flask-Migrate==4.0
types-Flask-SocketIO==5.3
types-fpdf2==2.7.4
types-gdb==12.1
types-google-cloud-ndb==2.2
types-greenlet==3.0
types-hdbcli==2.18
types-html5lib==1.1
types-httplib2==0.22
types-humanfriendly==10.0
types-ibm-db==3.2
types-influxdb-client==1.38
types-inifile==0.4
types-JACK-Client==0.5
types-jmespath==1.0
types-jsonschema==4.19
types-keyboard==0.13
types-ldap3==2.9
types-libsass==0.22
types-Markdown==3.5
types-mock==5.1
types-mypy-extensions==1.0
types-mysqlclient==2.2
types-netaddr==0.9
types-oauthlib==3.2
types-openpyxl==3.1
types-opentracing==2.4
types-paho-mqtt==1.6
types-paramiko==3.3
types-parsimonious==0.10
types-passlib==1.7
types-passpy==1.0
types-peewee==3.17
types-pep8-naming==0.13
types-pexpect==4.8
types-pika-ts==1.3
types-Pillow==10.1
types-playsound==1.3
types-pluggy==1.2.0
types-polib==1.2
types-portpicker==1.6
types-protobuf==4.24
types-psutil==5.9
types-psycopg2==2.9
types-pyasn1==0.5
types-pyaudio==0.2
types-PyAutoGUI==0.9
types-pycocotools==2.0
types-pycurl==7.45.2
types-pyfarmhash==0.3
types-pyflakes==3.1
types-Pygments==2.16
types-pyinstaller==6.1
types-pyjks==20.0
types-PyMySQL==1.1
types-pynput==1.7
types-pyOpenSSL==23.3
types-pyRFC3339==1.1
types-PyScreeze==0.1.29
types-pyserial==3.5
types-pysftp==0.2
types-pytest-lazy-fixture==0.6
types-python-crontab==3.0
types-python-datemath==1.5
types-python-dateutil==2.8
types-python-gflags==3.1
types-python-jose==3.3
types-python-nmap==0.7
types-python-slugify==8.0
types-python-xlib==0.33
types-pytz==2023.3.post1
types-pywin32==306
types-pyxdg==0.28
types-PyYAML==6.0
types-qrcode==7.4
types-redis==4.6.0
types-regex==2023.10.3
types-requests==2.31
types-requests-oauthlib==1.3
types-retry==0.9
types-s2clientprotocol==5
types-seaborn==0.13
types-Send2Trash==1.8
types-setuptools==68.2
types-simplejson==3.19
types-singledispatch==4.1
types-six==1.16
types-slumber==0.7
types-stdlib-list==0.8
types-stripe==3.5
types-tabulate==0.9
types-tensorflow==2.12
types-toml==0.10
types-toposort==1.10
types-tqdm==4.66
types-translationstring==1.4
types-tree-sitter==0.20.1
types-tree-sitter-languages==1.8
types-ttkthemes==3.2
types-tzlocal==5.1
types-ujson==5.8
types-untangle==1.2
types-usersettings==1.1
types-uWSGI==2.0
types-vobject==0.9
types-waitress==2.1
types-WebOb==1.8
types-whatthepatch==1.0
types-workalendar==17.0
types-WTForms==3.1
types-xmltodict==0.13
types-zstd==1.5
types-zxcvbn==4.4
typing_extensions==4.9.0
ufoLib2==0.16.0
ujson==5.9.0
unicodedata2==15.1.0
unicrypto==0.0.10
uritemplate==4.1.1 uritemplate==4.1.1
urllib3==1.26.18
urwid==2.6.4
uvicorn==0.27.0
uvloop==0.19.0
vboxapi==1.0
virtualenv==20.25.0+ds
wadllib==1.3.6
wafw00f==2.2.0
wcwidth==0.2.5
webcolors==1.11.1
webencodings==0.5.1
WebOb==1.8.6
websocket-client==1.7.0
websockets==10.4
websockify==0.10.0
Werkzeug==3.0.1
wfuzz==3.1.0
whois==0.8
wifite==2.7.0
winacl==0.1.7
wrapt==1.15.0
wsproto==1.2.0
xdg==5
xdot==1.3
xlrd==2.0.1
XlsxWriter==3.1.9
xlutils==2.0.0
xlwt==1.3.0
xmltodict==0.13.0
yara-python==4.5.0
yarl==1.8.2
zc.lockfile==2.0
zipp==1.0.0
zlib-wrapper==0.1.3
zombie-imp==0.0.2
zope.interface==6.1
zstandard==0.22.0