Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor for django #186

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion frameworks/django/requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
django == 4.0.3
django==4.1.2
79 changes: 39 additions & 40 deletions frameworks/django/views.py
Original file line number Diff line number Diff line change
@@ -1,63 +1,62 @@
import json
import time

from uuid import uuid4

from django.http import HttpResponse, JsonResponse
from django.views.generic import View
from django.urls import path
from django.http import HttpResponse, JsonResponse, HttpResponseNotAllowed, HttpResponseBadRequest
import json


async def html(request):
"""Return HTML content and a custom header."""
content = "<b>HTML OK</b>"
headers = {'x-time': f"{time.time()}"}
return HttpResponse(content, headers=headers)


async def upload(request):
"""Load multipart data and store it as a file."""
# 2021-04-18 Django 3.2 django.views.decorators.http.require_http_methods hasn't async support
if request.method != 'POST':
return HttpResponseNotAllowed(['POST'])

formdata = request.FILES
if 'file' not in formdata:
return HttpResponseBadRequest('ERROR')
class HtmlView(View):
""" Return HTML content and a custom header. """
async def get(self, request):
resp = HttpResponse('<b>HTML OK</b>')
resp.headers['x-time'] = time.time()
return resp

with open(f"/tmp/{uuid4().hex}", 'wb') as target:
target.write(formdata['file'].read())

return HttpResponse(target.name, content_type="text/plain")
class UploadView(View):
""" Load multipart data and store it as a file. """
async def post(self, request):
file = request.FILES.get('file')
if not file:
return HttpResponse('ERROR', status=400)

with open(f"/tmp/{uuid4().hex}", 'wb') as target:
target.write(file.read())

return HttpResponse(target.name, content_type="text/plain")

async def api(request, user, record):
"""Check headers for authorization, load JSON/query data and return as JSON."""
if request.method != 'PUT':
return HttpResponseNotAllowed(['PUT'])

if not request.headers.get('authorization'):
return HttpResponse('ERROR', status=401)
class ApiView(View):
""" Check headers for authorization, load JSON/query data and return as JSON. """
async def put(self, request, **kwargs):
if not request.headers.get('authorization'):
return HttpResponse('ERROR', status=401)

data = json.loads(request.body.decode())
return JsonResponse({
'params': {'user': user, 'record': record},
'query': dict(request.GET),
'data': data,
})
data = json.loads(request.body)
return JsonResponse({
'params': kwargs,
'query': request.GET.dict(),
'data': data,
})


urlpatterns = [
path('html', html),
path('upload', upload),
path('api/users/<int:user>/records/<int:record>', api),
path('html', HtmlView.as_view()),
path('upload', UploadView.as_view()),
path('api/users/<int:user>/records/<int:record>', ApiView.as_view()),
]


# More load for routing system
# ----------------------------
async def req_ok(*args, **kwargs):
return HttpResponse('ok')
class ReqOk(View):
async def get(self, request):
return HttpResponse('ok')


for n in range(5):
urlpatterns.insert(0, path(f"route-{n}", req_ok))
urlpatterns.insert(0, path(f"route-dyn-{n}/<part>", req_ok))
urlpatterns.insert(0, path(f"route-{n}", ReqOk.as_view()))
urlpatterns.insert(0, path(f"route-dyn-{n}/<part>", ReqOk.as_view()))