Skip to content

Commit

Permalink
#51 fix : modify lands create&img etc... (#63)
Browse files Browse the repository at this point in the history
  • Loading branch information
0321minji authored Aug 11, 2024
1 parent 12b6501 commit a76bbb6
Show file tree
Hide file tree
Showing 10 changed files with 290 additions and 62 deletions.
46 changes: 46 additions & 0 deletions core/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import io
import boto3
import uuid
from django.conf import settings
from Cognisle.settings import development
from datetime import datetime


def get_random_text(length):
return str(uuid.uuid4()).replace('-', '')[:length]

def s3_file_upload_by_file_data(upload_file, region_name, bucket_name, bucket_path, content_type=None):
bucket_name = bucket_name.replace('/', '')
# 파일 확장자 추출
if content_type:
content_type = content_type
else:
content_type = upload_file.content_type

now = datetime.now()
random_str = get_random_text(20)
extension = upload_file.name.split('.')[-1]

#random_file_name = '{}.{}'.format(str(now.strftime('%Y%m%d%H%M%S'))+random_str,extension)
# 파일의 ContentType을 설정
random_file_name = f"{now.strftime('%Y%m%d%H%M%S')}_{random_str}.{extension}"
upload_file_path_name = f"{bucket_path}/{random_file_name}"
print(upload_file_path_name)
s3 = boto3.resource('s3', region_name=region_name, aws_access_key_id=development.AWS_ACCESS_KEY_ID, aws_secret_access_key=development.AWS_SECERT_ACCESS_KEY)

try:
# 버킷이 존재하는지 확인
s3.meta.client.head_bucket(Bucket=bucket_name)
except s3.meta.client.exceptions.NoSuchBucket:
raise Exception(f"The specified bucket does not exist: {bucket_name}")

file_data = io.BytesIO(upload_file.read())

try:
# 파일을 S3에 업로드
s3.Bucket(bucket_name).put_object(Key=upload_file_path_name, Body=file_data, ContentType=content_type)
#return f"https://{bucket_name}.s3.{region_name}.amazonaws.com/{upload_file_path_name}"
return f"https://s3.{region_name}.amazonaws.com/{bucket_name}/{upload_file_path_name}"
except Exception as e:
print(f"Failed to upload file to S3: {e}")
return False
19 changes: 19 additions & 0 deletions lands/migrations/0011_alter_item_item_image.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Generated by Django 4.0 on 2024-08-03 12:20

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
('lands', '0010_alter_land_user'),
]

operations = [
migrations.AlterField(
model_name='item',
name='item_image',
field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='items', to='lands.itemimage'),
),
]
18 changes: 18 additions & 0 deletions lands/migrations/0012_alter_itemimage_image.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 4.0 on 2024-08-03 12:36

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('lands', '0011_alter_item_item_image'),
]

operations = [
migrations.AlterField(
model_name='itemimage',
name='image',
field=models.URLField(),
),
]
5 changes: 3 additions & 2 deletions lands/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@ class Location(models.Model):

#일단 lands 앱 안에 item 모델도 생성하긴 했는데 따로 앱 만드는게 좋을지 아니면 그냥 list api정도만 만들어도 괜찮을지
class ItemImage(models.Model):
image = models.ImageField(upload_to=get_item_pic_upload_path, default='item_image.png')
#image = models.ImageField(upload_to=get_item_pic_upload_path, default='item_image.png')
image=models.URLField()

#하나의 이미지로 여러 아이템 생성 가능 > 한 아이템당 show 값 지니는 거 맞음 & 한 item 마다 location 가지니까 manytomany onetoone으로 수정
class Item(models.Model):
item_image = models.ForeignKey(ItemImage, on_delete=models.CASCADE, related_name='items')
item_image = models.OneToOneField(ItemImage, on_delete=models.CASCADE, related_name='items')
#show=models.BooleanField(default=False)
#lands=models.Field('Land',related_name='items')
users=models.ManyToManyField('users.User', related_name='items')
Expand Down
2 changes: 1 addition & 1 deletion lands/selectors.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def show(self, item: Item):
class LandSelector:
@staticmethod
def get_user_items(user_id):
items = Item.objects.filter(users__id=user_id).prefetch_related('item_image', 'locations')
items = Item.objects.filter(users__id=user_id).prefetch_related('item_image', 'locations')
return items

@staticmethod
Expand Down
98 changes: 57 additions & 41 deletions lands/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,34 @@
from django.shortcuts import get_list_or_404, get_object_or_404
import io, time, uuid
from django.conf import settings
from Cognisle.settings import development
from .selectors import ItemSelector
from .models import Land,Location,Item, ItemImage
from users.models import User
from core.utils import s3_file_upload_by_file_data
from rest_framework.exceptions import NotFound, PermissionDenied, ValidationError
from django.db import IntegrityError

class LandCoordinatorService:
def __init__(self,user:User):
self.user=user

@transaction.atomic
def create(self, background:str)->Land:
def create(self, background:str,user_id:str)->Land:
land_service=LandService()
if user_id:
try:
user = User.objects.get(pk=user_id)
except User.DoesNotExist:
raise NotFound("해당 ID를 가진 사용자를 찾을 수 없습니다.")
else:
# user_id가 제공되지 않으면 요청한 사용자로 설정
if not self.user.is_authenticated:
raise PermissionDenied("사용자가 인증되지 않았습니다.")
user = self.user
land=land_service.create(
background=background,
user=self.user
user=user
)

if land is not None:
Expand Down Expand Up @@ -45,52 +59,54 @@ def __init__(self):
pass

@staticmethod
def create(image:InMemoryUploadedFile):
ext=image.name.split(".")[-1]
file_path='{}.{}'.format(str(time.time())+str(uuid.uuid4().hex),ext)
img=ImageFile(io.BytesIO(image.read()),name=file_path)
image=ItemImage(image=img)

image.full_clean()
image.save()

print(image.image.url)
return (f'{settings.MEDIA_URL}{image.image.name}', image.pk)
def create(image:ImageFile):
img_url=s3_file_upload_by_file_data(
upload_file=image,
region_name=development.AWS_S3_REGION_NAME,
bucket_name=development.AWS_STORAGE_BUCKET_NAME,
bucket_path=f'media/lands/item/pic'
)
item_image=ItemImage(image=img_url)
item_image.save()
print(item_image.image)
return (item_image.image, item_image.pk)

class ItemService:
def __init__(self):
pass
@staticmethod
def show_or_no(item:Item)->bool:
selector=ItemSelector()
if selector.show(item=item):
item.show=False
# def show_or_no(item:Item)->bool:
# selector=ItemSelector()
# if selector.show(item=item):
# item.show=False

item.full_clean()
item.save()
return False
else:
item.show=True
item.full_clean()
item.save()
# location 값이 없으면 기본값 설정
if not item.locations.exists():
default_location = {'x': '30', 'y': '30', 'z': '3'}
Location.objects.create(item=item, **default_location)
return True
# item.full_clean()
# item.save()
# return False
# else:
# item.show=True
# item.full_clean()
# item.save()
# # location 값이 없으면 기본값 설정
# if not item.locations.exists():
# default_location = {'x': '30', 'y': '30', 'z': '3'}
# Location.objects.create(item=item, **default_location)
# return True

@staticmethod
def create(image_id:str,show=bool):
def create(image_id:str):
item_image=get_object_or_404(ItemImage, pk=image_id)
print(item_image.image.url)
# land=get_object_or_404(Land,user=user)
item=Item(
item_image=item_image,
show=show,
# land=land,
# user=user,
)
item.full_clean()
item.save()

print(item_image.image)
try:
item=Item(
item_image=item_image,
)
item.full_clean()
item.save()
except ValidationError as e:
# ValidationError가 발생하면 예외를 발생시킴
raise Exception(f"Validation error: {e.message_dict}")
except IntegrityError as e:
# 데이터베이스 무결성 오류 발생 시 예외 발생
raise Exception(f"Integrity error: {str(e)}")
return item
14 changes: 8 additions & 6 deletions lands/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@
app_name = "lands"

urlpatterns=[
path('create/',LandCreateApi.as_view(),name='create'),
path('item/img/create/',ItemImageCreateApi.as_view(),name='item_img_create'),
path('show/',ItemShowUpdateApi.as_view(),name='item_show'),
path('',LandCreateApi.as_view(),name='create'),
path('items/img/',ItemImageCreateApi.as_view(),name='item_img_create'),
#path('show/',ItemShowUpdateApi.as_view(),name='item_show'),
path('<int:user_id>/',UserLandItemListApi.as_view(),name='lands_items'),
path('item/',ItemLocationUpdateApi.as_view(),name='item_update'),
path('item/create/',ItemCreateApi.as_view(),name='item_create'),
path('item/game/',ItemGetApi.as_view(),name='item_get'),
#path('items/',ItemLocationUpdateApi.as_view(),name='item_update'),
path('items/',ItemCreateApi.as_view(),name='item_create'),
path('items/game/',ItemGetApi.as_view(),name='item_get'),
path('items/<int:user_id>/',ItemListApi.as_view(),name='item_list'),
#path('items/',AllItemListApi.as_view(),name='all_item_list'),
]
Loading

0 comments on commit a76bbb6

Please sign in to comment.