172만명의 커뮤니티!! 함께 토론해봐요.
해결됨
이거 하나로 종결-스프링 기반 풀스택 웹 개발 무료 강의
저는 비전공자로 지금 html,css javascript에 대한 기본적인 지식을 갖고있으며 스프링을 응용하여 블로그정도의 웹 페이지를 만들 수 있는 수준이라고 생각합니다 하지만 최근 기업 트렌드를 보면 백엔드 개발자만을 원하는 것이 아닌 풀스택개발자를 원하는 것이 추세인것 같습니다. 이 추세에 대비하기위해 어떤 언어를 최우선적으로 학습해야할지 궁금합니다. ex)node.js,next.js, was , docker... 개발자로 성장하기 위한 방향성을 알려주시면 매우 감사드립니다.
HTML/CSS javascript jsp spring spring-boot spring-security
이동건
2025-02-14T08:18:03.621Z
댓글 1
좋아요 0
조회수 359
미해결
Next + React Query로 SNS 서비스 만들기
export default function PostArticle({ children, post }: Props) { const router = useRouter(); const onClick = () => { console.log(1); router.push(`/${post.User.id}/status/${post.postId}}`); }; return ( <article className={style.post} onClickCapture={onClick}> {children} </article> ); } 이 부분에서 onClickCapture에 대한 질문이 있습니다. 캡쳐링 단계에서 onClickCapture의 클릭함수가 실행된다면 자식인 <Link> 영역을 눌러도 <article>의 onClickCapture가 캡쳐링 단계에서 먼저 동작하여 <Link> 태그의 href 경로가 아닌 router.push()로 동작 해야한다고 생각하였습니다. 그러나 실제 <Link>태그를 클릭하면 콘솔에 1이 찍히지만 router.push() 경로가 아닌 <Link>태그의 href경로로 이동하더군요. 이 부분이 잘 이해가 안됩니다..
react next.js react-query next-auth msw
2025-02-14T08:15:52.917Z
댓글 1
좋아요 0
조회수 149
미해결
Next + React Query로 SNS 서비스 만들기
댓글, 재게시 기능 개발시 onSuccess 메서드 사용 부분에서 궁금한 점이 생겨 질문 드립니다. 로직은 비슷해서 재게시 로직 첨부했습니다!! 좋아요 기능과 마찬가지로 optimistic update 방식으로 보다 빠른 UI 변경을 보기 위해 사용하는건지 궁금합니다. 강의를 수강하다가 onMutate, onSuccess 메서드에서 optimistic update 방식이 혼재 되있어 댓글, 재게시 기능들은 onSuccess 함수에 invalidateQueries 메서드를 활용해 쿼리 상태를 최신으로 다시 가져오는 방식은 괜찮지 않을까, 또 제로초님 의견은 어떠신지 궁금점이 들어 질문 드립니다!! async onSuccess(response) { const newPost = await response.json(); setContent(""); setPreview([]); const queryCache = queryClient.getQueryCache(); const queryKeys = queryCache.getAll().map((cache) => cache.queryKey); queryKeys.forEach((queryKey) => { if (queryKey[0] === "posts") { const value: Post | InfiniteData<Post[]> | undefined = queryClient.getQueryData(queryKey); if (value && "pages" in value) { const obj = value.pages .flat() .find((v) => v.postId === parent?.postId); if (obj) { // 존재는 하는지 const pageIndex = value.pages.findIndex((page) => page.includes(obj) ); const index = value.pages[pageIndex].findIndex( (v) => v.postId === parent?.postId ); const shallow = { ...value }; value.pages = { ...value.pages }; value.pages[pageIndex] = [...value.pages[pageIndex]]; shallow.pages[pageIndex][index] = { ...shallow.pages[pageIndex][index], Comments: [{ userId: me?.user?.email as string }], _count: { ...shallow.pages[pageIndex][index]._count, Comments: shallow.pages[pageIndex][index]._count.Comments + 1, }, }; shallow.pages[0].unshift(newPost); // 새 답글 추가 queryClient.setQueryData(queryKey, shallow); } } else if (value) { // 싱글 포스트인 경우 if (value.postId === parent?.postId) { const shallow = { ...value, Comments: [{ userId: me?.user?.email as string }], _count: { ...value._count, Comments: value._count.Comments + 1, }, }; queryClient.setQueryData(queryKey, shallow); } } } }); await queryClient.invalidateQueries({ queryKey: ["trends"], }); // or async onSuccess() { console.log(queryClient.getQueryCache().getAll()); await Promise.all([ queryClient.invalidateQueries({ queryKey: ["posts", String(post?.postId)], }), queryClient.invalidateQueries({ queryKey: ["posts", String(post?.postId), "comments"], }), ]); }, },
react next.js react-query next-auth msw
천하무적박정권
2025-02-14T08:06:17.239Z
댓글 2
좋아요 0
조회수 123
미해결
공공데이터로 파이썬 데이터 분석 시작하기
강사님 안녕하세요 우선 너무 잘 듣고 있고 좋은 강의 정말 감사합니다 . 그런데 수업 내용이 자꾸 현재 버전과 달라서 너무 헷갈려요.. 설명하시는 단축키나, 어디에 들어가 어떻게 입력해야하는지 방법에 대한 설명 없이 내용뿐인 것들이 있어 따라가기 어려운듯해요 ㅜ profiling 한글폰트설정 부록 강의 올려주신 부분에서 터미널 들어가서 경로를 입력하라고 하시는데 어떤 형식으로 어디부터 어디까지 써서 입력해야하는지 모르겠어요.. ~/opt/anaconda3/lib/python3.12/site-packages/pandas_profiling 이렇게 따라 입력하면 저는 아무 반응도 안일어나는데 어떻게 해야할까요?
ynny
2025-02-14T07:39:15.168Z
댓글 2
좋아요 0
조회수 222
미해결
[신규 개정판] 이것이 진짜 크롤링이다 - 실전편 (인공지능 수익화)
- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. 강의에서는 너무 짧게 지나가서, 해결을 못하고 있습니다. 컴알못이라,, 자세히 설명 부탁드립니다 ㅠ,.ㅠ... 프로젝트 폴더를 06.GUI폴더로 설정 =>어디서 어떻게 클릭해서 설정하는지 모르겠습니다. 터미널에서 해당 명령어를 실행 "pyside6-uic ui -o py"=>1번부터가 막혀서 실행을 못하고 있습니다.
김형곤
2025-02-14T05:20:05.072Z
댓글 2
좋아요 0
조회수 199
해결됨
[코드캠프] 부트캠프에서 만든 '완벽한' 프론트엔드 코스
"use client"; import styles from "./styles.module.css"; import Image from "next/image"; const IMAGE_SRC = { profileImage: { src: ("/assets/profile_image.png"), alt: "프로필이미지", }, linkImage: { src: ("/assets/link.png"), alt: "링크아이콘", }, locationImage: { src: ("/assets/location.png"), alt: "위치아이콘", }, cheongsanImage: { src: ("/assets/cheongsan.png"), alt: "청산사진", }, neotubeImage: { src: ("/assets/neotube.png"), alt: "너튜브사진", }, badImage: { src: ("/assets/bad.png"), alt: "싫어요", }, goodImage: { src: ("/assets/good.png"), alt: "좋아요", }, hamberger: { src: ("/assets/hamberger.png"), alt: "목록아이콘", }, pencil: { src: ("/assets/pencil.png"), alt: "수정아이콘", }, } as const; export default function BoardsDetailPage() { return ( <div className={styles.detailLayout}> <div className={styles.detailBody}> <div className={styles.detailFrame}> <div className={styles.detailSubject}> 살어리 살어리랏다 쳥산(靑山)애 살어리랏다멀위랑 ᄃᆞ래랑 먹고 쳥산(靑山)애 살어리랏다얄리얄리 얄랑셩 얄라리 얄라 </div> <div className={styles.detailMetadataContainer}> <div className={styles.detailMetadataProfile}> <Image src={IMAGE_SRC.profileImage.src} alt={IMAGE_SRC.profileImage.alt} width={100} height={100} /> <div>홍길동</div> </div> <div className={styles.detailMetadataDate}>2024.11.11</div> </div> <div className={styles.enrollBorder}></div> <div className={styles.detailMetadataIconContainer}> <Image src={IMAGE_SRC.linkImage.src} alt={IMAGE_SRC.linkImage.alt} width={100} height={100} /> <Image src={IMAGE_SRC.locationImage.src} alt={IMAGE_SRC.locationImage.alt} width={100} height={100} /> </div> <div className={styles.detailContentContainer}> <Image src={IMAGE_SRC.cheongsanImage.src} alt={IMAGE_SRC.cheongsanImage.alt} className={styles.detailContentImage} width={100} height={100} /> <div className={styles.detailContentText}> <div>살겠노라 살겠노라. 청산에 살겠노라.</div> <div>머루랑 다래를 먹고 청산에 살겠노라.</div> <div>얄리얄리 얄랑셩 얄라리 얄라</div> <div className={styles.textGap}></div> <div>우는구나 우는구나 새야. 자고 일어나 우는구나 새야.</div> <div>너보다 시름 많은 나도 자고 일어나 우노라.</div> <div>얄리얄리 얄라셩 얄라리 얄라</div> <div className={styles.textGap}></div> <div> 갈던 밭(사래) 갈던 밭 보았느냐. 물 아래(근처) 갈던 밭 보았느냐 </div> <div>이끼 묻은 쟁기를 가지고 물 아래 갈던 밭 보았느냐.</div> <div>얄리얄리 얄라셩 얄라리 얄라</div> <div className={styles.textGap}></div> <div>이럭저럭 하여 낮일랑 지내 왔건만</div> <div>올 이도 갈 이도 없는 밤일랑 또 어찌 할 것인가.</div> <div>얄리얄리 얄라셩 얄라리 얄라</div> <div className={styles.textGap}></div> <div>어디다 던지는 돌인가 누구를 맞히려던 돌인가.</div> <div>미워할 이도 사랑할 이도 없이 맞아서 우노라.</div> <div>얄리얄리 얄라셩 얄라리 얄라</div> <div className={styles.textGap}></div> <div>살겠노라 살겠노라. 바다에 살겠노라.</div> <div>나문재, 굴, 조개를 먹고 바다에 살겠노라.</div> <div>얄리얄리 얄라셩 얄라리 얄라</div> <div className={styles.textGap}></div> <div>가다가 가다가 듣노라. 에정지(미상) 가다가 듣노라.</div> <div> 사슴(탈 쓴 광대)이 솟대에 올라서 해금을 켜는 것을 듣노라. </div> <div>얄리얄리 얄라셩 얄라리 얄라</div> <div className={styles.textGap}></div> <div>가다 보니 배불룩한 술독에 독한 술을 빚는구나.</div> <div> 조롱박꽃 모양 누룩이 매워 (나를) 붙잡으니 내 어찌 하리이까.[1] </div> <div>얄리얄리 얄라셩 얄라리 얄라</div> </div> <Image src={IMAGE_SRC.neotubeImage.src} alt={IMAGE_SRC.neotubeImage.alt} width={100} height={100} /> <div className={styles.detailContentGoodOrBad}> <div className={styles.detailGoodContainer}> <Image src={IMAGE_SRC.badImage.src} alt={IMAGE_SRC.badImage.alt} width={100} height={100} /> <div className={styles.detailBadText}>24</div> </div> <div className={styles.detailGoodContainer}> <Image src={IMAGE_SRC.goodImage.src} alt={IMAGE_SRC.goodImage.alt} width={100} height={100} /> <div className={styles.detailGoodText}>12</div> </div> </div> <div className={styles.detailButtonsContainer}> <button className={styles.detailButton}> <Image src={IMAGE_SRC.hamberger.src} alt={IMAGE_SRC.hamberger.alt} width={100} height={100} /> <div>목록으로</div> </button> <button className={styles.detailButton}> <Image src={IMAGE_SRC.pencil.src} alt={IMAGE_SRC.pencil.alt} width={100} height={100}/> <div>수정하기</div> </button> </div> </div> </div> </div> </div> ); } require 를 넣으면 왜 오류인지 require 어떤 기능인지 알 수 있을까요ㅕ?>
react react-native 하이브리드-앱 graphql next.js
이 규성
2025-02-14T04:56:14.521Z
댓글 2
좋아요 0
조회수 114
해결됨
한 입 크기로 잘라먹는 Next.js
선생님 서버액션을 이런식으로 사용하면 안되는걸까요? 굳이 버튼을 따로빼서 관리하는지 궁금합니다. "use client"; import { ReviewData } from "@/types"; import { deleteReview } from "@/actions/create-review-action"; export default function ReviewList({ id, content, author, createdAt, }: ReviewData) { const onClickHandler = async () => { await deleteReview({ id: id }); }; return ( <section> <span>{author}</span> <div>{content}</div> <p>{createdAt}</p> <button onClick={() => onClickHandler()}>삭제하기</button> </section> ); }
uphoon
2025-02-14T03:32:21.103Z
댓글 2
좋아요 0
조회수 153
해결됨
세계 대회 진출자가 알려주는 코딩테스트 A to Z (with Python)
안녕하세요 ! 수강전 문제를 풀어보았는데 풀었던 방법이 attributeError 런타임에러가 나왔습니다. 하기 방법에 매몰이 되어서 강의에 집중이 안되어서 이렇게 질문하게 되었습니다 ㅠㅠ 이렇게 풀면 메모리나 시간초과가 날까요? 그리고 어디가 틀려서 런타임에러가 나는지 알수있을까요? import sys # sys.stdin = open('./input.txt', 'r') input = sys.stdin.readlines().strip() from collections import defaultdict W, H = map(int, input().split()) lit = [int(input()) for _ in range(W)] # print(lit) # dict_ = defaultdict() ans = defaultdict() points = [] for y, v in enumerate(lit): if y % 2 == 0: for x in range(H-v, H): points.append((x, y)) else: for x in range(v): points.append((x, y)) for x, z in points: if x in ans.keys(): ans[x] += 1 else: ans[x] = 1 # print(ans) low_cnt = sorted(ans.values())[0] cnt = 0 for k, a in ans.items(): if a == low_cnt: cnt += 1 print(f'{low_cnt} {cnt}')
tocc22
2025-02-14T02:26:07.952Z
댓글 1
좋아요 0
조회수 139
미해결
비전공자를 위한 진짜 입문 올인원 개발 부트캠프
App.js, child.js 모두 강의 내용과 같이 작성 후 터미널에서 실행시켜 보았는데 리액트 초기화면만 표시되고 있습니다. 캐시 삭제, vscode 재시작 등을 시켜보았으나 변함이 없습니다. 왼쪽 화면이 App.js 코드 내용대로 바뀌지 않는 이유가 무엇일까요?
HTML/CSS javascript react node.js react-native 머신러닝 express tensorflow
2025-02-13T15:19:58.187Z
댓글 1
좋아요 0
조회수 270
미해결
파이썬/장고로 웹채팅 서비스 만들기 (Feat. Channels) - 기본편
def room_users(request, room_name): # room_name으로 해당 방을 찾기 room = get_object_or_404(Room, name=room_name) # 사용자가 방에 참여한 상태인지 확인 if not room.is_joined_user(request.user): return HttpResponse("Unauthorized user", status=401) # 방에 접속 중인 사용자 목록 가져오기 username_list = room.get_online_usernames() return JsonResponse({ "username_list": username_list, }) 저는 하나의 채팅방만 사용하기때문에 room_pk가 아니라 room_name을 전달했습니다. 근데 page not found가 뜹니다. 제가 생각기로는 name = room_name 전달이 제대로 안되어서 이렇게 뜨는거같습니다. room_pk에 관한 부분을 제대로 처리하지 못해 접속하거나 나갈때 뜨는 메세지도 제대로 작동하지 않고 있습니다. class Room(OnlineUserMixin, models.Model): owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="owned_room_set", ) name = models.CharField(max_length=100) class Meta: ordering = ["-pk"] @property def chat_group_name(self): return self.make_chat_group_name(room=self) chat/routing.py from django.urls import path, re_path from chat import consumers websocket_urlpatterns = [ path("ws/chat/<str:room_name>/chat/", consumers.ChatConsumer.as_asgi()), ] chat/urls.py from django.urls import path from app.urls import urlpatterns from chat import views # 향후 url reverse에 활용 app_name = "chat" urlpatterns=[ path("", views.index, name = "index"), path("<str:room_name>/chat/", views.room_chat, name = "room_chat" ), path("<str:room_name>/users/", views.room_users, name = "room_users" ), ] consumers.py from asgiref.sync import async_to_sync from channels.generic.websocket import JsonWebsocketConsumer from chat.models import Room # 모든 유저가 고정된 채널 레이어 그룹을 가질것. class ChatConsumer(JsonWebsocketConsumer): SQUARE_GROUP_NAME = "1" group_name = [SQUARE_GROUP_NAME] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def connect(self): user = self.scope['user'] self.group_name = self.SQUARE_GROUP_NAME if not user.is_authenticated: self.close() else: is_new_join = self.group_name if is_new_join: async_to_sync(self.channel_layer.group_send)( self.group_name, { "type": "chat.user.join", "username": user.username, } ) async_to_sync(self.channel_layer.group_add)( self.group_name, self.channel_name ) self.accept() def disconnect(self, code): if self.group_name: async_to_sync(self.channel_layer.group_discard)( self.group_name, self.channel_name ) user = self.scope['user'] # if self.room is not None: # is_last_leave = self.room.user_leave(self.channel_name, user) # if is_last_leave: # async_to_sync(self.channel_layer.group_send)( # self.group_name, # { # "type": "chat.user.leave", # "username": user.username, # } # ) def chat_user_join(self, message_dict): self.send_json({ "type": "chat.user.join", "username": message_dict["username"], }) def chat_user_leave(self, message_dict): self.send_json({ "type": "chat.user.leave", "username": message_dict["username"], }) def chat_message(self, message_dict): self.send_json({ "type": "chat.message", "message": message_dict["message"], "sender": message_dict["sender"], }) def receive_json(self, content, **kwargs): user = self.scope["user"] _type = content["type"] if _type == "chat.message": message = content["message"] sender = user.username async_to_sync(self.channel_layer.group_send)( self.SQUARE_GROUP_NAME, { "type": "chat.message", "message": message, "sender": sender, } ) else: print(f"Invalid message type : ${_type}") 질문 받아주셔서 감사합니다. 선생님의 파이썬 장고 가이드를 다 보고 이 강의 질문하는게 맞다고 생각합니다. , 제 팀프로젝트 데드라인이 임박하여 파이썬 장고 가이드를 다 보지 못하고, 제대로 공부하지 못하고 채널스를 공부하게 되어 이런 질문을 드리게되는거같아 죄송합니다. 프로젝트가 끝나도 장고 놓지 않고 제대로 이해할수있게 공부하겠습니다. 감사합니다ㅠ
python django django-channels
sunnnwo
2025-02-13T15:12:03.050Z
댓글 2
좋아요 0
조회수 202
미해결
3D리플릿 만들기 - 인터랙티브 웹 프로젝트
비공개 영상인데, 어떻게 영상을 볼 수 있나요?
HTML/CSS javascript 인터랙티브-웹
14212424
2025-02-13T11:05:26.958Z
댓글 1
좋아요 0
조회수 151
미해결
웹 애니메이션의 새로운 표준, Web Animations API
스크롤 이미지 영역 넘어갈시 가로가 움직여서 여러개의 이미지영역이 보이는게 안되여ㅠㅠ 선생님 완성본 02.html도 안되는거같아요 css @charset 'utf-8'; html, body, h1, h2, h3, h4, h5, h6, p, blockquote, code, img, dl, dt, dd, ol, ul, li, fieldset, legend, caption { margin: 0; padding: 0; border: 0; } div, span, article, section, header, footer, p, ul, li, fieldset, legend, label, a, nav, h1, h2, h3 { box-sizing: border-box; } html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { margin: 0; padding: 0; border: 0; } article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; } ol, ul, li { list-style: none; } table { border-collapse: collapse; border-spacing: 0; } img { max-width: 100%; height: auto; } html { font-size: 20px; font-family: Roboto; line-height: 1.6; } body { background: dodgerblue; } .wrap{ contain: paint; } .para { padding: 1em; font-size: 50px; } .gallery{ display: flex; align-items: center; position: sticky; top: 0; width:350vw; max-width: 4000px; height: 100vh; border: 10px dashed deeppink; } .gallery-item{ width:70vw; max-width: 800px; flex-shrink: 0; } .gallery-timeline{ height:2000px; border:10px dashed mediumaquamarine; } 02.js import './scroll-timeline.js' const gallery = document.querySelector('.gallery'); const galleryTimeline = document.querySelector('.gallery-timeline'); gallery.animate( [ {transform : 'translayeX(0)'}, {transform : 'translayeX(-100%)'} ], { fill : 'both', timeline : new ScrollTimeline ({ scrollOffsets : [ {target : galleryTimeline, edge : 'start' , threshold : 1}, {target : galleryTimeline, edge : 'end' , threshold : 1} ] }) } );
HTML/CSS javascript 인터랙티브-웹 frontend web-animations-api
vcxzz33
2025-02-13T08:36:40.328Z
댓글 1
좋아요 0
조회수 156
해결됨
한 입 크기로 잘라먹는 Next.js
src/app/(with-searchbar)/search/page.tsx Type error: Type 'Props' does not satisfy the constraint 'PageProps'. Types of property 'searchParams' are incompatible. Type '{ q?: string | undefined; }' is missing the following properties from type 'Promise<any>': then, catch, finally, [Symbol.toStringTag] vercel 명령어 사용시 build문제에서 에러가 생겼다고 하면서 위와 같은 타입 에러가 나오네요 ㅠ 선생님께서 제공해주신 github에서 내용을 가져와 적용해보았으나 같은 에러가 나오게되어 질문드립니다.
범띵떵
2025-02-13T08:32:55.261Z
댓글 2
좋아요 0
조회수 344
해결됨
Azure Native로 나만의 GPT 만들기
강의 잘 듣고있습니다. 이번 강의에서 front와 API를 연결하는 작업 도중, 계속 마지막에 토큰까지는 잘 받아오지만 웹소켓을 못 만드는 문제가 발생했습니다. 문제가 무엇일까 계속 고민해보다가 이 강의 가장 처음에 강사님이 진행했던 =을 붙이는 작업이 떠올라 그 =을 다시 지워줬습니다. 그런데 해결이 됐습니다. 제 키에는 =가 마지막에 없더라구요... =가 있는 경우와 없는 경우가 존재하나봅니다. =의 차이가 혹시 무엇인지 알 수 있을까요? 그냥 암호의 일부분일까요?
javascript python mongodb azure FastAPI
안현준
2025-02-13T06:02:22.969Z
댓글 2
좋아요 0
조회수 183
미해결
배달앱은 어떻게 내 주변의 맛집을 찾을까?
제가 이해한 구조는 아래와 같습니다. Request -> API -> Service -> Entity Redis에서 캐시 조회 실패하면 redis에서 몽고 db collection 관련 함수를 직접 조회 하는 게 아니라 서비스로 돌아가서 서비스단에서 몽고 db collection 관련 함수를 호출하는게 맞지 않나요? 아니면 주신 코드 처럼 Entity 단에서는 서로를 호출하면서 작동하는게 맞나요?
파사
2025-02-13T05:13:37.799Z
댓글 2
좋아요 0
조회수 173
미해결
파이썬/장고 웹서비스 개발 완벽 가이드 with 리액트 (장고 4.2 기준)
1) request.META["HTTP_USER_AGENT"] 실습 5번 내내 NameError로 표기 되지 않습니다. 구글링해도 정확히 어떤 이유인지 잘모르겠습니다. 2) 아래 pwsh 느낌표가 왜 나오는지 궁금합니다.
react python django web-api htmx
lkh5040
2025-02-13T02:24:59.487Z
댓글 1
좋아요 0
조회수 98
미해결
파이썬/장고로 웹채팅 서비스 만들기 (Feat. Channels) - 기본편
#consumers.py from asgiref.sync import async_to_sync from channels.generic.websocket import JsonWebsocketConsumer from chat.models import Room # 모든 유저가 고정된 채널 레이어 그룹을 가질것. class ChatConsumer(JsonWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) SQUARE_GROUP_NAME = "square" self.group_name = [SQUARE_GROUP_NAME] self.room = None def connect(self): user = self.scope['user'] if not user.is_authenticated: self.close() else: room_name = self.scope['url_route']['kwargs']['room_pk'] try: self.room = Room.objects.get(pk=room_name) except Room.DoesNotExist: #지정 룸 pk에 룸 인스턴스가 없을 경우 웹소켓 연결요청 수락. pass else: self.group_name = self.SQUARE_GROUP_NAME is_new_join = self.room.user_join(self.channel_name, user) if is_new_join: async_to_sync(self.channel_layer.group_send)( self.group_name, { "type": "chat.user.join", "username": user.username, } ) async_to_sync(self.channel_layer.group_add)( self.group_name, self.channel_name ) self.accept() def disconnect(self, code): if self.group_name: async_to_sync(self.channel_layer.group_discard)( self.group_name, self.channel_name ) user = self.scope['user'] if self.room is not None: is_last_leave = self.room.user_leave(self.channel_name, user) if is_last_leave: async_to_sync(self.channel_layer.group_send)( self.group_name, { "type": "chat.user.leave", "username": user.username, } ) def chat_user_join(self, message_dict): self.send_json({ "type": "chat.user.join", "username": message_dict["username"], }) def chat_user_leave(self, message_dict): self.send_json({ "type": "chat.user.leave", "username": message_dict["username"], }) def chat_message(self, message_dict): self.send_json({ "type": "chat.message", "message": message_dict["message"], "sender": message_dict["sender"], }) def receive_json(self, content, **kwargs): user = self.scope["user"] _type = content["type"] if _type == "chat.message": message = content["message"] sender = user.username async_to_sync(self.channel_layer.group_send)( self.SQUARE_GROUP_NAME, { "type": "chat.message", "message": message, "sender": sender, } ) else: print(f"Invalid message type : ${_type}") room_name = self.scope['url_route']['kwargs']['room_pk'] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^ KeyError: 'room_pk' 이런 에러가 나서, urls.py, views.py, index.html도 맞춰줘 봤지만, 잘 해결이 되질 않습니다. 어떤식으로 이 에러를 처리해야할까요. 오늘도 좋은 하루 되시길 바랍니다. 감사합니다.
python django django-channels
sunnnwo
2025-02-12T23:39:36.083Z
댓글 1
좋아요 0
조회수 117
미해결
[신규 개정판] 이것이 진짜 크롤링이다 - 실전편 (인공지능 수익화)
상세페이지 href속성을 찾아 기존페이지 url?상세페이지 url을 적용하여 실습을 성공해 오다가 난관에 부딪혔습니다. html속성값을 보니 아래와 같이 되어 있고 url에 붙이거나 해도 페이지가 로드 되지 않아 어려움을 겪고 있습니다. <a href="Javascript:view_content('869');">처리 일정 문의 드립니다.</a> 위와같은 href가 나타날때는 어떻게 상세페이지로 이동해야 하는지 궁금하고 이럴때 혹시 우회할 수 있는 대안이 있다면 알고 싶어요
민소리
2025-02-12T22:49:33.121Z
댓글 1
좋아요 0
조회수 123
해결됨
이거 하나로 종결-스프링 기반 풀스택 웹 개발 무료 강의
안녕하세요. 수강해보려고 하는데, 최대한 빠르게 끝내보고 싶습니다. c++ 문법 정도만 알고 있는 수준인데, 공부 기간은 얼마 정도로 예상하시나요?
HTML/CSS javascript jsp spring spring-boot spring-security
yeonm217
2025-02-12T19:33:34.771Z
댓글 1
좋아요 0
조회수 416
미해결
구글 애드센스 수익형 워드프레스 블로그 만들기
서브도메인 이름은 아무거나 해도되나요?
HTML/CSS wordpress php 웹-디자인 반응형-웹
최재원
2025-02-12T14:14:19.728Z
댓글 1
좋아요 0
조회수 139