본문 바로가기

728x90
반응형

Python

(100)
Django: ckeditor # django-ckeditor # 텍스트 에디터 html 태그를 입혀주는 ckeditor를 django library로 구현 이용 라이브러리: https://github.com/django-ckeditor/django-ckeditor 설치 및 실행 pip install django-ckeditor INSTALLED_APPS 추가 # settings.py INSTALLED_APPS = [ ..., 'ckeditor', 'ckeditor_uploader'# 이미지 업로드를 위해 필요(browse server를 통해 embeding할 이미지 찾는데 쓰임 ] 이미지가 upload될 ckeditor path 설정 # settings.py CKEDITOR_UPLOAD_PATH = 'uploads/' 이미지 upload시 필요한 url 등록 및 이미지 등록 UI를..
Python Django: symmetrical option in ManyToMany # ManyToMany에서 한쪽만 관계 설정 # 테이블 자신을 참조하는 경우 Django에서 ManyToMany를 통해 Table을 연결하면, 예를 들어 A, B 테이블을 ManyToMany를 통해 연결시 A에서 B를 연결할 경우, B에서 A 방향으로도 자동 연결 그러나 A -> B를 연결 하더라도, B -> A로 자동연결이 되는 것을 원치 않는 상황도 존재 예를 들어 A 의 row에 대한 추천 상품으로 B의 row 들을 지정한다고 해보자. 그러나 B의 row에 대한 추천 상품은 A가 아닌 C를 지정하길 원한다고 하면, 기존 ManyToMany 방식으로 B의 추천상품을 불러올 시 A가 함께 가져와진다. 이는 ManyToMany의 기본 옵션이 상호 대칭적인 symmetrical = True 이기 때문 따라서 ManyToMany설정시 symmetrical = False 옵션으로 주면..
Django: HTTP DELETE Method # HTTP # DELETE, PUT # GET, POST Django에서 HTTP request는 내장기능으로 GET, POST만 지원하고 DELETE, PUT은 지원하지 않는다. print(dir(request)) 위와 같이 찍어보면 ['COOKIES', 'FILES', 'GET', 'LANGUAGE_CODE', 'META', 'POST', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__',..
Python: Celery with Django Django 프로젝트 내에 Celery를 두고 연계해서 사용하기 * Install redis 설치(ubuntu 기준) $ sudo apt update $ sudo apt install redis-server 부팅시 redis 시작 $ sudo systemctl enable redis-server celery[redis] 설치 $ pip install celery[redis] * Celery - Django 설정 1. celery.py Django의 settings.py와 같은 경로에 celery.py 를 생성 (settings/local.py 또는 settings/base.py등, 환경에 따라 나눈 경우 settings 폴더와 같은 경로에 두면 됨) import os from celery import C..
Python: Error handling # 에러를 어떻게 다룰지를 쉽게 파악해보자 Error handling을 어떻게 할지 도구들을 살펴보자 def is_callable(obj): try: call_result = obj() return {"callable":True, "result": call_result} except: return {"callable":False, "result": obj} try: """Some Error Logic""" except Exception as e: for i in dir(e): print(i, is_callable(eval(f"e.{i}"))) 위와 같이 하면 Exception을 어떤 method를 통해 다룰지 살펴보기 좋다.
Python: 중첩 list comprehension # 이중 컴프리헨션 # itertools # chain 리스트 안에 리스트가 담긴 형태, 다른 표현으로는, 2차원 행렬을 하나의 리스트로 담고자 할때 다음과 같이 사용 가능 test_list = [[a,b], [c,d], [e,f]] new_list = [j for i in test_list for j in i] itertools 라이브러리의 chain.from_iterbale()을 통해서도 가능 from itertools import chain test_list = [[a,b], [c,d], [e,f]] new_list = list(chain.from_iterable(test_list)) 결과: [a,b,c,d,e,f]
Python: 색 추출 # pick color # PIL Python pillow, PIL.image 를 활용해서 가장 많이 사용된 색깔과 가운데 사용된 색깔을 추출해보자 우선 Pillow library 설치 $ pip install Pillow 1. 가장 많이 사용된 색 추출 from PIL import Image from collections import Counter def get_most_used_color(image_path): # Open the image using Pillow image = Image.open(image_path) # Convert the image to RGB mode (in case it's grayscale or has an alpha channel) image = image.convert('RGB') # Get the wi..
Python Django: select_related 언제 쓰고, 왜 쓰냐? 1) select_related 예시 1. my_fr = MyFruit.objects.get(fruit_id=fr_id, customer=customer) 2. my_fr = MyFruit.objects.select_related('fruit').get(fruit_id=fr_id, customer=customer) 1과 2는 어떤게 더 효율적이거나 좋은 방법일까? ------------- 1과 2 중 더 효율적인 방법은 상황에 따라 다르다. my_fr = MyFruit.objects.get(fruit_id=fr_id, customer=customer) 이 방법은 MyFruit 객체를 가져올 때, 연결된 fruit 객체는 가져오지 않습니다. 따라서 이후에 my_fr.fruit에 접근..

728x90
반응형