[Python] Django 투표 앱과 frontend 연결하기
·
Language/Python
frontend 연결하기투표 앱 프로젝트에 “django-cors-headers” 종속성 추가uv add django-cors-headers settings.py 수정INSTALLED_APPS에 'corsheaders' 추가MIDDLEWARE에 'corsheaders.middleware.CorsMiddleware’ 추가 요청을 허용할 origin을 선택, 허용할 메소드와 헤더도 추가CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", "http://127.0.0.1:3000",]CSRF_TRUSTED_ORIGINS = [ "http://localhost:3000", "http://127.0.0.1:3000",]# 허용할 메소드와 헤더CORS_ALL..
[Python] Django 투표 앱 RESTful api로 리팩토링하기
·
Language/Python
DetailView, IndexView, ResultsView기존의 DetailView는 html 형태로 데이터를 리턴함class DetailView(generic.DetailView): model = Question template_name = "polls/detail.html" get 요청시 model로 필요한 데이터를 받아오고, json 형태로 변환하여 리턴하도록 DetailView를 변경Question 테이블에 특정 id의 데이터가 없으면 404 error 발생하도록 처리class DetailView(View): def get(self, request, pk): question_with_choice = get_object_or_404(Question.objects.pr..
[Python] Django Model, View 사용하기
·
Language/Python
model 사용해서 데이터 조회하기model.py에서 모델 클래스에 __str__ 메서드 정의하기 → 모델 출력값 확인하기 위해 필요return 값으로 Question 테이블의 question_text 필드만 출력하도록 지정def __str__(self): return self.question_text question 테이블은 다음과 같음 model의 .objects.all() 메서드를 사용하면, Question 테이블의 모든 값이 출력됨 model의 .objects.get() 메서드를 사용하면, Question 테이블에서 특정 id의 데이터만 출력됨view 함수의 파라미터요청을 받을때 url에 있는 path를 view의 파라미터로 입력 받을 수 있음ex) http://localhost:8000/p..
[Python] Django 투표 앱 만들기 (2)
·
Language/Python
html 파일 생성/polls 밑에 templates/polls/ 디렉터리 생성하고, 파일 추가 detail.html{% include "./includes/header.html" %} {% csrf_token %} {{ question.question_text }} {% if error_message %}{{ error_message }}{% endif %} {% for choice in question.choice_set.all %} {{ choice.choice_text }} {% endfor %}{% include "./includes/footer.html" %}  index.html{% include "./includes/header.html" %..
[Python] Django 투표 앱 만들기 (1)
·
Language/Python
투표 앱 생성하고, View 작성하기투표 앱 생성하기, 다음과 같이 해당 디렉터리에 polls가 생성됨$ python manage.py startapp polls polls/view.py에 아래 내용 추가URL 경로에 매핑될 뷰 함수인 index를 정의index 함수는 "Hello, world. You're at the polls index."라는 HTTP 응답을 생성from django.http import HttpResponsedef index(request): return HttpResponse("Hello, world. You're at the polls index.") polls/urls.py에 아래 내용 추가/를 views.py의 index와 연결“”은 애플리케이션의 루트 경로에 해당fr..
[Python] Django 프로젝트 생성하기
·
Language/Python
mise로 python 설치하기mac 터미널에서 mise 설치하기$ curl https://mise.run | sh mise 활성화$ echo 'eval "$(~/.local/bin/mise activate zsh)"' >> ~/.zshrc Pyhon 3.11 버전 설치mise로 Python을 설치하면, 버전을 자유롭게 변경할 수 있음$ mise use -g python@3.11 설치된 python 버전 확인$ python --versionPython 3.11.10uv로 프로젝트 생성하기터미널에서 uv 설치하기$ curl -LsSf https://astral.sh/uv/install.sh | sh 프로젝트 초기화init 뒤에 생성할 프로젝트의 이름을 지정해주면 됨$ uv init my-first-djan..
[Python] 네이버 카페 게시글 크롤링 selenium, bs4
·
Language/Python
네이버 카페의 게시판에서 글번호, 제목, 작성자, 작성일을 크롤링하는 코드입니다. 링크 주소 복사 ▪ 크롤링할 카페의 게시판으로 가서 첫번째 페이지의 링크 주소 복사 크롤링할 페이지 개수, URL 설정 page_num = 5 # 크롤링할 페이지 개수 url = "https://cafe.naver.com/ArticleList.nhn?search.clubid=21771779&search.menuid=56&search.boardtype=L&search.totalCount=151&search.cafeId=21771779&search.page=" driver.get(url+'1') # 크롤링할 페이지 열기 ▪ page_num에서 크롤링할 페이지 개수를 지정 ex) 5로 지정했으면 1,2,3,4,5 페이지의 내용을..
[Python] 데이터프레임 합치기, 중복 행 제거
·
Language/Python
df1 = pd.DataFrame({'time':[1, 2, 3, 4, 5, 6], 'price':[1100, 1200, 1300, 1400, 1500, 1600]}) df2 = pd.DataFrame({'time':[4, 5, 6, 7, 8, 9], 'price':[1400, 1500, 1600, 1700, 1800, 1900]}) 데이터프레임 합치기 df = pd.concat([df1,df2], ignore_index=True) ignore_index=True는 인덱스 초기화 데이터프레임 중복값 제거 df = df.drop_duplicates(['time']).reset_index(drop=True) 지정한 열을 기준으로 중복값을 제거