본문으로 바로가기

Django Rest Api 참고

category Python 2020. 3. 25. 18:08

- 테스트 코드

 

파일 업로드 (post)

 

rest_frameworkdjango-rest-framework 설치

pip3 install djangorestframework

 

urls.py

from django.urls import path
from . import views

app_name = 'test'
urlpatterns = [
    path('chp/<int:cnt>', views.chp, name='chp/'),
    path('chp_up', views.chp_up, name='chp_up'),
]

 

models.py

from django.db import models
from django.utils import timezone

class Project(models.Model):
    idx = models.AutoField(primary_key=True, verbose_name='idx')
    p_id = models.CharField(max_length=30, verbose_name='프로젝트 아이디', help_text='프로젝트 아이디')
    ...
    p_reg_date = models.DateTimeField(auto_now_add=True, verbose_name='등록일', help_text='등록일')
    p_edit_date = models.DateTimeField(auto_now=True, verbose_name='수정일', help_text='수정일')

    class Meta:
        db_table = '테이블 이름'
        verbose_name='프로젝트'
        verbose_name_plural = '프로젝트'

 

view.py

import os, json, datetime
from inc.models import Project
from rest_framework.decorators import api_view
from .serializers import ProjectSerializer
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, JsonResponse
from django.conf import settings


@api_view(['GET'])
def chp(request, cnt=1):

  if request.method == 'GET':
      # print(request.data.get('v1'))
      print(cnt)

      projects = Project.objects.all()
      serializer = ProjectSerializer(projects, many=True)
      data = json.dumps({'projects': serializer.data})
      # tmp = request.META.get('CONTENT_TYPE')
      # tmp = request.META['CONTENT_TYPE']
      return HttpResponse(data)



@api_view(['POST'])
@csrf_exempt
def chp_up(request):

  print(request.method)
  pw = request.POST.get('title')
  if request.method == 'POST':
      print(pw)
      print(request.META['CONTENT_TYPE'])

      for idx, x in enumerate(request.FILES.getlist("file")):
          file = request.FILES.getlist("file")[idx]
          filename = file._name

          now = datetime.datetime.now()
          fname = now.strftime('%Y%m%d%H%M%S')

          ext = filename.split('.')[-1]  # 파일이름으로부터 확장자명가져오기
          print(ext)

          filename_new = f"{fname}_{idx}.{ext}"
          # filename_new = "%s_%s.%s" % (fname, idx, ext)
          # filename_new = "{0}_{1}.{2}".format(fname, idx, ext)

          fileDir = os.path.join(settings.MEDIA_ROOT, 'temp')
          fp = open('%s/%s' % (fileDir, filename_new), 'wb')
          for chunk in file.chunks():
              fp.write(chunk)
          fp.close()

  # return HttpResponse("OK")
  return JsonResponse({
      'state': True,
  }, json_dumps_params={'ensure_ascii': True})
  

 

 

html

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<form name="frm" id="frm" enctype="multipart/form-data" method="post">
    <input type="text" name="title" value="테스트"><br>
    <input type="file" name="file"><br>
    <input type="file" name="file"><br>
    <input type="button" value="전송" onclick="send();"><br>
    <input type="button" value="리스트" onclick="getlist();">
</form>

<script>

    function getlist(){
        $.ajax({
            url:'http://localhost:8201/test/chp/2', //request 보낼 서버의 경로
            type:'get', // 메소드(get, post, put 등)
            async: false, //동기: false, 비동기(기본값): ture
            timeout: 2*60*60*1000, //2 hours,
            success: function(data) {
                //서버로부터 정상적으로 응답이 왔을 때 실행
                console.log(data);
            },
            error: function(err) {
                //서버로부터 응답이 정상적으로 처리되지 못햇을 때 실행
                console.log(err);
            }
        });
    }

    function send(){
        // var formData = $("#frm").serialize();
        var form = $('#frm')[0];
        var formData = new FormData(form);

        $.ajax({
            url:'http://localhost:8201/test/chp_up', //request 보낼 서버의 경로
            type:'post', // 메소드(get, post, put 등)
            processData : false, //false로 선언 시 formData를 string으로 변환하지 않음
            contentType : false, //false 로 선언 시 content-type 헤더가 multipart/form-data로 전송되게 함
            async: false, //동기: false, 비동기(기본값): ture
            // data:{'id':'admin'}, //보낼 데이터,
            data:formData,
            timeout: 2*60*60*1000, //2 hours,
            success: function(data) {
                //서버로부터 정상적으로 응답이 왔을 때 실행
                console.log(data);
            },
            error: function(err) {
                //서버로부터 응답이 정상적으로 처리되지 못햇을 때 실행
                console.log(err);
            }
        });
    }

</script>

 

 

CROS 이슈 

pip3 install django-cors-headers

settings.py

# 파일 저장 경로
MEDIA_ROOT = os.path.join(BASE_DIR, 'files')
MEDIA_URL = '/files/'


# Application definition
INSTALLED_APPS = [
...
    'test',
    'rest_framework',  #Rest Api Framework
    'corsheaders',  #Cors 
]

MIDDLEWARE = [
...
    'corsheaders.middleware.CorsMiddleware',
]


##CORS
CORS_ORIGIN_ALLOW_ALL=True
CORS_ALLOW_CREDENTIALS = True #전체 주소 허용 
# 특정 주소 허용 
# CORS_ORIGIN_WHITELIST = (
#     'www.mysite.com',
#     'www.anothersite.com'
# )

CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
)

CORS_ALLOW_HEADERS = (
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
)

 

 

 

참고

http://raccoonyy.github.io/drf3-tutorial-2/  

https://jay-ji.tistory.com/30  

http://egloos.zum.com/killins/v/3013984   

http://jamanbbo.tistory.com/43 

http://throughkim.kr/2018/05/29/django-rest/

https://zladnrms.tistory.com/97  

http://www.semusa.org/blog/8f82b881-3aed-44b2-a8d6-de8721880f36/  

https://wp.mytrails.io/stub/?mod=document&uid=7