django 12. View

dev-somi·2022년 1월 22일
0

django

목록 보기
11/13
  1. View
  • 1개의 HTTP 요청에 대해 1개의 뷰가 호출
  • urlpatterns 리스트에 view를 매핑한다.
    즉 함수의 형태로 구현할 수 있다. class 형태 등
    (callable objects)
  • 함수 기반 뷰(기반)와 클래스 기반 뷰의 형태
  • (HttpRequest 객체, 현재 요청의 URL로부터 Capture된 문자열들)
  1. 리턴값
  • HttpResponse 객체를 리턴해야 한다.

그렇지 않으면 이런 Value error가 뜬다.

def post_detail(request, pk):

# return render(request, 'instagram/post_list.html')
response = HttpResponse()
response.write("hello world")
return response
  1. pandas를 통한 CSV 응답 생성

프로그램을 통해서 2차원 데이터를 로직으로 처리할 일이 많은데
pandas 라이브러리를 이용하여서 데이터프레임을 사용하거나
데이터 분석, DB insert 등을 사용할 수 있다.

def response_csv(request):
df = pd.DataFrame([
[100, 110, 120],
[200, 210, 220],
[300, 310, 320],
])
io = StringIO()
df.to_csv(io)
io.seek(0) # 메모리 기반의 파일 인터페이스
response = HttpResponse(io, content_type='text/csv')
response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(encoded_filename)
return response

0개의 댓글