172만명의 커뮤니티!! 함께 토론해봐요.
해결됨
실리콘밸리 엔지니어가 가르치는 파이썬 기초부터 고급까지
안녕하세요 더치 페이 함수 만들기에서 going_dutch 함수 리턴값 계산하실 때 return float(total) / num_of_ppl 로 int 값인 total을 float으로 바꾸셨는데 굳이 float으로 바꾸신 이유가 궁금합니다 어차피 int끼리 나눗셈(/)을 하면 결과가 무조건 float으로 나오는데, 굳이 total을 float으로 바꾸신 이유가 있을까요? 바꾸지 않아도 결괏값은 float으로 나오지 싶어서요. 답변 기다리겠습니다. 감사합니다
천천히꾸준하게
2025-03-10T12:15:16.034Z
댓글 2
좋아요 0
조회수 223
해결됨
React, Node.js, MongoDB로 만드는 나만의 회사 웹사이트: 완벽 가이드
비슷한 질문이 있어서 5-2강까지 강의를 들어서 adminLogin까지 구현을 하였습니다. 앞의 4-6강에서 로그아웃을 시도하였을 때, 400 Bad Request : 이미 로그아웃된 상태로 나옵니다. 그래서 console.log(req.cookies.token)을 해보았을 때, undefined가 나옵니다. adminLogin을 진행하여 브라우저에 쿠키가 제대로 저장되었는지 확인해보았는데, localhost:5173에서도 localhost:3000에서도 cookie에 token값이 저장되어있었습니다. index.js에 cookie-parser 또한 존재하는 상태입니다. 질문을 올리기 전에 여러가지를 시도해보았는데, router.post () 에서는 req.cookies.token의 값을 undefined로 가져오고, router.get()에서는 정상적인 토큰값을 반환했습니다. 어떻게 해야 router.post () 에서도 req.cookies.token값을 가져올 수 있을까요? thunder client로 GET http://localhost:3000/api/auth/getCookie를 했을 때도 token은 undefined 값이 출력되었다가 브라우저에서 주소로 접근하니 token값이 정상적으로 출력되었습니다. 아래의 사진은 thunder client로 get 방식과 post 방식으로 보냈을 때의 차이를 담은 사진입니다. 브라우저에 cookie가 정상적으로 저장된 사진입니다. // index.js require("dotenv").config(); const express = require("express"); const mongoose = require("mongoose"); const cookieParser = require("cookie-parser"); const cors = require("cors"); const userRoutes = require("./routes/user"); const app = express(); const PORT = 3000; app.use(cors({ origin: "http://localhost:5173", credentials: true, })); app.use(express.json()) app.use(express.urlencoded({extended : true})) app.use(cookieParser()); app.use("/api/auth", userRoutes); app.get("/", (req, res) => { res.send("Hello world"); console.log("token: " + req.cookies.token); }); app.post("/cookie", (req, res) => { console.log(req.cookies.token) res.send("api/auth"); }) mongoose .connect(process.env.MONGO_URL) .then(() => console.log("MongoDB와 연결이 되었습니다.")) .catch((error) => console.log("MongoDB와 연결에 실패했습니다: ", error)); app.listen(PORT, () => { console.log("Server is running"); }); // user.js const express = require("express"); const router = express.Router(); const bcrypt = require("bcrypt"); const User = require("../models/User"); const axios = require("axios"); const jwt = require("jsonwebtoken"); // const cookieParser = require("cookie-parser"); // router.use(express.json()) // router.use(express.urlencoded({extended : true})) // router.use(cookieParser()); router.post("/signup", async (req, res) => { try { const { username, password } = req.body; const existingUser = await User.findOne({ username }); if (existingUser) { return res.status(400).json({ message: "이미 존재하는 사용자입니다." }); } const hashedPassword = await bcrypt.hash(password, 10); const user = new User({ username, password: hashedPassword, }); await user.save(); res.status(201).json({ message: "회원가입이 완료되었습니다." }); } catch (error) { res.status(500).json({ message: "서버 오류가 발생했습니다." }); console.log(error); } }); router.post("/login", async (req, res) => { try { const { username, password } = req.body; const user = await User.findOne({ username }).select("+password"); if (!user) { return res.status("401").json({ message: "사용자를 찾을 수 없습니다." }); } if (!user.isActive) { return res .status(401) .json({ message: "비활성화된 계정입니다. 관리자에게 문의하세요." }); } if (user.isLoggedIn) { return res .status(401) .json({ message: "이미 다른 기기에서 로그인되어 있습니다." }); } const isValidPassword = await bcrypt.compare(password, user.password); if (!isValidPassword) { user.failedLoginAttempts += 1; user.lastLoginAttempt = new Date(); if (user.failedLoginAttempts >= 5) { user.isActive = false; await user.save(); return res.status(401).json({ message: "비밀번호를 5회 이상 틀려 계정이 비활성화되었습니다.", }); } await user.save(); return res.status(401).json({ message: "비밀번호가 일치하지 않습니다.", remainingAttempts: 5 - user.failedLoginAttempts, }); } user.failedLoginAttempts = 0; user.lastLoginAttempt = new Date(); user.isLoggedIn = true; // try { // const response = await axios.get("https://api.ipify.org?format=json"); // const ipAddress = response.data.ip; // user.ipAddress = ipAddress; // } catch (error) { // console.log("IP 주소를 가져오던 중 오류 발생: ", error.message); // } await user.save(); console.log("로그인 성공"); const token = jwt.sign( { userId: user._id, username: user.username }, process.env.JWT_SECRET, { expiresIn: "24h" } ); console.log(token); res.cookie("token", token, { httpOnly: true, secure: "production", sameSite: "strict", maxAge: 24 * 60 * 60 * 1000, }); console.log("쿠키 설정", ); const userWithoutPassword = user.toObject(); delete userWithoutPassword.password; res.json({ user: userWithoutPassword }); console.log("json 전달 후 종료"); } catch (error) { console.log("서버 오류: ", error.message); res.status(500).json({ message: "서버 오류가 발생했습니다." }); } }); router.post("/logout", async (req, res) => { try { const token = req.cookies.token; console.log(token); if (!token) { return res.status(400).json({ message: "이미 로그아웃된 상태입니다." }); } try { const decoded = jwt.verify(token, process.env.JWT_SECRET); const user = await User.findById(decoded.userId); if (user) { user.isLoggedIn = false; await user.save(); } } catch (error) { console.log("토큰 검증 오류: ", error.message); } res.clearCookie("token", { httpOnly: true, secure: "production", sameSite: "strict", }); res.json({ message: "로그아웃되었습니다." }); } catch (error) { console.log("로그아웃 오류: ", error.message); res.status(500).json({ message: "서버 오류가 발생했습니다." }); } }); router.delete("/delete/:userId", async (req, res) => { try { const user = await User.findByIdAndDelete(req.params.userId); if (!user) { return res.status(404).json({ message: "사용자를 찾을 수 없습니다." }); } res.json({ message: "사용자가 성공적으로 삭제되었습니다." }); } catch (error) { res.status(500).json({ message: "서버 오류가 발생했습니다." }); } }); router.post("/verify-token", (req, res) => { const token = req.cookies.token; if (!token) { return res .status(400) .json({ isValid: false, message: "토큰이 없습니다." }); } try { const decoded = jwt.verify(token, process.env.JWT_SECRET); return res.status(200).json({ isValid: true, user: decoded }); } catch (error) { return res .status(401) .json({ isValid: false, message: "유효하지 않은 토큰입니다." }); } }); // router.get("/getCookie", async (req, res) => { // res.send(req.cookies.token) // console.log("getCookie's token : " , req.cookies.token) // }) // router.post("/postCookie", async (req, res) => { // res.send(req.cookies.token) // console.log("postCookie's token : ", req.cookies.token) // }) module.exports = router;
HTML/CSS javascript react node.js mongodb
김주형
2025-03-10T11:44:41.488Z
댓글 1
좋아요 0
조회수 166
해결됨
UIUX 포트폴리오 Part.3 - 반응형 웹 포트폴리오
안녕하세요. "UIUX 포트폴리오 Part.3 - 반응형 웹 포트폴리오" 강의를 재밌게 보고 있습니다. "완성" 폴더에 "원본"폴더에 있는 "yeskey"에 들어간 움직이는 이미지들을, 이미지 사이트에서 다운로드 받으신걸까요? 만약 그렇다면 다운 받으신 사이트의 주소를 알려주실 수 있을까요? 제 이메일 주소를 남깁니다. happinessboom@daum.net 입니다. 좋은 강의를 만들어 주셔서 감사합니다.
HTML/CSS javascript jquery 반응형-웹 media-query
happinessboom
2025-03-10T09:59:28.602Z
댓글 4
좋아요 1
조회수 299
미해결
프로그래밍 시작하기 : 웹 입문 (Inflearn Original)
하라는 데로 다 해도 그냥 안 깔리네요. 응용 프로그램 크롬으로 넘어가는 과정도 전혀 실행이 안되고요. 추측되는 요인 있으신 분 없으실까요?
문정언
2025-03-10T08:57:18.872Z
댓글 1
좋아요 0
조회수 214
해결됨
React, Node.js, MongoDB로 만드는 나만의 회사 웹사이트: 완벽 가이드
강의에서는 command prompt를 사용하셨는데, 맥북에서는 zsh와 bash 중 어떤 것을 사용해야 할까요?
HTML/CSS javascript react node.js mongodb
어린 송어
2025-03-10T07:35:59.567Z
댓글 2
좋아요 0
조회수 167
미해결
프로그래밍 시작하기 : 파이썬 입문 (Inflearn Original)
dsom8383@naver.com
dsom8383
2025-03-10T06:38:04.438Z
댓글 2
좋아요 0
조회수 103
해결됨
(2026 최신!) 일주일만에 합격하는 정보처리기사 실기
36:06 main함수 6번째줄 if(isEven(testVal, 1))을 실행하러 왼쪽의 isEven함수에 가면 if문 2개 다 실행하는게 아닌가요? if(mode==1) 실행하고 if(number%2==0)도 실행해서 '1는 홀수입니다 / 1는 홀수입니다.(0)' 두 줄이 프린트된다고 생각했는데 왜 아닌지 궁금합니다.
깔뀰
2025-03-10T05:17:58.243Z
댓글 2
좋아요 1
조회수 86
미해결
파이썬으로 장고(Django) 공략하기: 입문
첨부파일 화면처럼 빨간 줄이 나타납니다. 실행은 전혀 문제가 없이 실행이 잘 됩니다.
임정훈
2025-03-10T05:07:22.896Z
댓글 1
좋아요 0
조회수 168
미해결
처음 만난 리액트(React)
학습을 잘 따라가는 중 아무 오류나 에러는 없는데 콘솔에는 에러가 나네요 ㅜㅜ 분명 코드도 똑같은데 이유를 잘 모르겠어 코드와 오류 사진 캡처 드립니다!
2025-03-10T05:04:44.808Z
댓글 2
좋아요 1
조회수 235
미해결
떠먹는 Three.js
Material 수업강의 중 2:44초에 roughness이 안먹힙니다.. 빛반사가 안되는데 확인 부탁드려요 ㅜ <script async src="https://ga.jspm.io/npm:es-module-shims@2.0.10/dist/es-module-shims.js"></script> <script type="importmap"> { "imports":{ "three" : "https://cdn.jsdelivr.net/npm/three@0.174.0/build/three.module.js", "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.174.0/examples/jsm/" } } import * as THREE from "three"; const $result = document.querySelector("#result"); // 1. Scene : 화면에서 보여주려는 객체를 담는 공간 const scene = new THREE.Scene(); // scene.add(요소) scene.background = new THREE.Color(0xffe287); // 2. Camera : 신을 바라볼 시점을 결정 const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.set(2, 2, 2); camera.lookAt(0, 0, 0); // 3. Renderer : Scene+Camera, 화면을 그려주는 역할 const renderer = new THREE.WebGLRenderer({ canvas: $result, antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); // console.log(renderer); // document.body.appendChild(renderer.domElement) const light = new THREE.DirectionalLight(0xffffff); light.position.set(2, 4, 3); scene.add(light); const geometry = new THREE.BoxGeometry(1, 1, 1) const basic = new THREE.MeshBasicMaterial({ color: 0x2e6ff2, // wireframe: true, transparent: true, opacity: 0.5 }); // 가장 일반적으로 사용 됨. const standard = new THREE.MeshStandardMaterial({ color: 0xffaaaa, roughness: 0.2, }); const mesh = new THREE.Mesh(geometry, standard); scene.add(mesh); function animate() { // box.rotation.y += 0.01; // box.rotation.x += 0.01; // console.log(box.rotation.y); renderer.render(scene, camera); requestAnimationFrame(animate); } animate(); // 반응형을 위한 함수 window.addEventListener("resize", () => { // 1. 카메라의 종횡비 camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); //카메라 업데이트 // 2. renderer의 크기 renderer.setSize(window.innerWidth, window.innerHeight); });
HTML/CSS javascript three.js
2025-03-10T01:50:22.598Z
댓글 1
좋아요 0
조회수 142
미해결
파이썬/장고 웹서비스 개발 완벽 가이드 with 리액트 (장고 4.2 기준)
파이썬 기초 문법 학습 후 현재 강의를 듣는 중인데 2번 세션 맛보기 반복 숙달 어느정도까지 해야 다음 챕터로 넘어가는 것이 맞나요? 강의 이름은 맛보기인데 중요한 것 들 같아서 반복 숙달을 어느정도 까지 하는게 좋을 지 궁금합니다.
react python django web-api htmx
lkh5040
2025-03-10T01:46:43.013Z
댓글 2
좋아요 0
조회수 186
해결됨
한 입 크기로 잘라먹는 Next.js
next는 자동적으로 캐시 저장기능이 있고 next에서도 DB 데이터가 필요한 페이지에서 직접 불러와서 사용하는 것을 권장한다 라고 말씀해주셨는데요 그러면 next는 보통 zustand, recoli, redux와 같은 상태관리 라이브러리를 사용하지 않는 것을 추천하시나요? 아니면 사용하는 것을 추천하시나요??
Full Stack 개발자
2025-03-10T00:49:32.044Z
댓글 2
좋아요 0
조회수 91
미해결
실리콘밸리 데이터 리더가 알려주는 Airflow 기초
이 과정은 google colab을 사용하여 ETL 프로세스를 만들어 스노우플레이크에 적재하는 방식을 보여줍니다. 두 개의 컬럼을 갖고 있는 country_capital.csv 파일을 텍스트로 풀어 쓰고 콤마로 나눠 country와 capital 로 나누는 과정을 설명해주는데, 이 과정을 진행하는 이유가 단순 궁금합니다. 스노우플레이크 GUI 환경에서 add data 하여 스테이지-테이블 순으로 적재를 하면 되는데 코드화 하여 적재하는 구분하여 적재하는 이유가 단순히 궁금합니다. 혹시, 나중에 처리하여 올리기 힘든 데이터의 경우 이렇게 전처리 과정을 미리 거쳐 올리는 방법을 알려주시는건가요?
python sql airflow snowflake
고해양
2025-03-09T10:32:44.153Z
댓글 3
좋아요 1
조회수 225
미해결
Prompt Engineering: 완벽 가이드
수업 자료에는 code, review_criteria 이 두개만 있어요. 이 강의에서 사용하는 레딧 자료가 어디있는지 모르겠네요.
박세준
2025-03-09T08:37:43.272Z
댓글 2
좋아요 0
조회수 144
미해결
프로그래밍 시작하기 : 파이썬 입문 (Inflearn Original)
흠... 많은 분들이 module 파일을 가져오실 때, 에러가 발생하는 듯 한데 그 누구도 뭔가 속시원하게 말씀해주지 않으시는 듯하여 아래와 같이 제가 해결한 내용 공유드립니다. 1.우선, 다음과 같은 사전지식이 필요합니다. - vscode에서 python 코드를 실행 하면, vscode 내 python 전용서버인 Pylance가 실행 되며, 해당 서버는 모듈을 찾을 때 기본적으로 특정한 경로만 확인 합니다. 그 특정 경로라는 것이 바로 sys.path 안에 포함되어 있는 경로 라고 보시면 됩니다. 그래서 vscode에서 다음과 같이 코드 입력 후 터미널에서 실행보면 이 때에는 math 폴더가 포함되어 있지 않다는 것을 알 수 있습니다. import sys print(sys.path) print(type(sys.path)) 따라서 sys.path.append()와 import test_module을 입력하셔도 해당 모듈을 찾아올 수 없었던 것 입니다!! 2.python 전용서버인 Pylance에 sys.path 경로 탐색 외 vscode를 통해 별도 경로도 탐색할 수 있도록 해주세요. - 현재 작업중인 루트폴더 (*수업으로 생각해보면, 파이썬 입문과정)에 .vscode라는 폴더 생성 - 만약 현재 작업중인 폴더만 띄어놓고 하고 싶다면, Chapter06 이라는 폴더에다가 생성해줘도 됩니다! - 해당 폴더에 Pylance가 참조할 수 있는 경로 추가 설정 - 경로 추가 설정하는 방법 : settings.json 파일 생성 후 아래 코드 입력 { "python.analysis.extraPaths": ["/Users/admin/Documents/파이썬 입문과정/math"] } 위 처럼 설정하시면, 이제 Pylance는 import 예약어를 통해 특정 모듈을 가져오고자 할 때, 기본 경로인 sys.path 뿐만 아니라, 개발자가 추가 설정해준 위 경로에서도 값을 참조해 올 수 있게 됩니다.
Json
2025-03-09T04:07:15.058Z
댓글 2
좋아요 3
조회수 158
해결됨
(2026 최신!) 일주일만에 합격하는 정보처리기사 실기
안녕하세요 선생님, 수업 잘 듣고 있습니다. 내장 타입과 메서드 강의 자료와 문자열 슬라이싱 마스터하기 강의 자료에 대한 질문입니다. (1) 내장 메서드를 이용한 출력의 경우 s = "Hello, World!" 에 대한 print(s.lower()) 이 'hello, world!' 그리고 print(s.upper()) 이 'HELLO, WORLD!' 이런 식으로 작은 따옴표가 붙어서 출력되는데 (2) 사전 형태의 메서드의 경우에서는 왜 my_dict = {"name" : "WeekendCode" (이하 생략)} 의 print(my_dict.get("job", "Not Found")) 가 그냥 Not Found 이렇게 따옴표가 없이 출력되는지 궁금합니다. (3) 반면 문자열 슬라이싱에서는 기본 예제에서는 주석으로 출력형이 'Hello' 이런식으로 달려있습니다만, 음수 인덱스의 출력값에는 World 이런식으로 쓰여있는데 따옴표가 있는 형태와 없는 형태 둘 중 어느 것이 정답인지 궁금합니다. 시험에 나온다고 생각했을때 내장 메서드를 이용한 출력은 출력값에 따옴표를 붙이고 사전 형태의 메서드에서 내장 메서드를 사용해 키 또는 값등을 불러올때는 출력값에 따옴표를 붙이지 않으며 문자열 슬라이싱을 하는 경우에는 출력값에 따옴표를 붙이지 않는다 이렇게 생각하면 될까요? 늘 좋은 강의에 감사드립니다.
김도영
2025-03-09T02:24:51.466Z
댓글 2
좋아요 0
조회수 126
해결됨
(2026 최신!) 일주일만에 합격하는 정보처리기사 실기
안녕하세요! 제가 풀어봤는데 도저히 정답이 이해가지 않아서 틀린부분을 알려주시면 감사하겠습니다. 제가 푼 방식은 아래와 같습니다. b는 a의 처음부터 3번째 까지의 문자이므로, "eng" c는 a의 4번째부터 6번째 까지의 문자인데 첫 문자를 0부터 세므로 4번째 문자는 n이된다. 즉, "nee" d는 a의 28번째부터 끝까지의 문자이므로, "ing" b+c+d 는 "engneeing" 정답은 "engneeing" 일 것 같은데, 왜 "engneing" 일까요?
wooni0909wn
2025-03-09T01:56:12.786Z
댓글 2
좋아요 0
조회수 95
미해결
비전공자를 위한 진짜 입문 올인원 개발 부트캠프
공익을 위해 첨부합니다... Windows의 경우 Mac과 다른 방식으로 경로가 설정되는 탓인지 상품 업로드 후 홈화면에서 상품이미지가 엑박으로 보이는 오류가 발생합니다. 그동안 질문&답변 게시판에 올라온 모든 질문 및 답변을 참고해 해결을 해보고자 하였는데요, 그 어느 답변을 참고해도 해결이 되지 않아 눈물을 머금고 10분짜리 강의에 몇시간동안 매달려있었습니다. 그렇게 알게된 방법은... 저의 경우 (1) 상품 업로드 화면에서 사진을 첨부한 후 개발자 도구의 Network에서 첨부한 사진의 링크를 보면 http://localhost:8080/upload/(상품이름).jpg 이런 식으로 뜹니다. (2) 업로드 버튼을 누른 후 홈 화면으로 이동 (3) 개발자 도구의 Network에서 새롭게 업로드된 사진의 링크를 보면 http://localhost:3000/upload/(상품이름).jpg 이런 식으로 뜹니다. 이를 해결하기 위해, grab-market-web 폴더 (사용자에 따라 폴더 이름은 다를 수 있음) → src → main → index.js에서 product-card 의 product-img 부분을 확인합니다. <div> <img className="product-img" src={`${API_URL}/${product.imageUrl}`} ></img> </div> src 링크를 다음과 같이 변경합니다. 그럼 상품 업로드 화면에서의 이미지와 홈화면에서의 이미지가 localhost:8080로 동일해지기 때문에 상품 사진이 정상적으로 보입니다. 물론 이렇게 코드를 수정하고 나면 기존에 저장해놨던 상품들의 이미지에 엑박이 뜹니다. (images/products/__ 이런 식으로 폴더 내 이미지와 연결해둔 링크들이 http://localhost:8080/images/products/__ 처럼 변경되니 엑박이 뜨는 것으로 추정됩니다.) 어차피 이제 사진을 서버에 직접 업로드하는 방법으로 진행될 예정이니 그냥 기존의 상품들은 삭제하시면 될 것 같습니다. (DB Browser → 데이터 탐색 → 기존 상품 레코드 선택 → 현재 레코드 삭제하기 → 변경사항 저장하기 이용하면 삭제 가능합니다.) 저와 동일한 이유로 엑박 뜨는게 아니라면... 저도 모르겠습니다. 방법을 찾으시면 공유해주세요. 파이팅! +) 상품 상세페이지를 들어가면 다시 엑박이 뜹니다. <div id="image-box"> <img src={`${API_URL}/${product.imageUrl}`} /> {console.log(product.imageUrl)} </div> 이때는 product 폴더의 index.js에 들어가여 image-box 부분을 다음과 같이 변경해주세요. 원리는 위와 동일합니다. 그러면 상세페이지에서도 정상적으로 작동합니다.
HTML/CSS javascript react node.js react-native 머신러닝 express tensorflow
sugi0jubak
2025-03-08T19:54:55.858Z
댓글 1
좋아요 0
조회수 220
해결됨
실전! FastAPI 활용(비동기)
안녕하세요. 좋은 강의 감사합니다. 강의를 기반으로 제 방식대로 서버를 구성하다가 알 수 없는 에러에 빠졌습니다. 서버는 정상 구동은 되고, postman으로 root url인 localhost:8000/ 에 request를 날리면 정상적으로 결과값을 반환 받는데 localhost:8000/api/recommend?userId=1 만 호출하면 바로 에러메세지 없이 500만 응답으로 받고 있습니다. print(1) 도 서버 로그에 찍히지 않고 서버 로그는 아예 나오질 않네요. localhost:8000/ 에서도 동일하게 서버 로그는 찍히지 않습니다 우선 의도는 BaseRepository 클래스를 만들어서 find_by_id 같은 중복 코드를 하나로 관리해보려고 했습니다. 의존성 주입 부분은 지피티의 도움을 받아서 위치를 조정했습니다. 도저히 어디서 문제가 난건지 알 수 없어서 도움 요청 드립니다 ㅜㅜ # main.py from typing import Dict from dotenv import load_dotenv from fastapi import FastAPI from src.app.app import create_app load_dotenv() app: FastAPI = create_app() @app.get("/") async def health_check_handler() -> Dict[str, str]: return {"statusMsg": "good"} # app.py from contextlib import asynccontextmanager from typing import AsyncGenerator import anyio from fastapi import FastAPI from src.app.endpoints.recommend import router @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncGenerator: limiter = anyio.to_thread.current_default_thread_limiter() limiter.total_tokens = 200 yield def create_app() -> FastAPI: app = FastAPI(lifespan=lifespan) app.include_router(router, prefix="/api") # 다른 설정들(예: 미들웨어, 이벤트 핸들러 등)을 추가할 수 있습니다. return app # connection.py import os import urllib from typing import AsyncGenerator from dotenv import load_dotenv from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker, create_async_engine load_dotenv() DB_USERNAME: str = os.getenv("DB_USERNAME", "root") DB_PASSWORD: str = os.getenv("DB_PASSWORD", "root") DB_HOST: str = os.getenv("DB_HOST", "127.0.0.1") DB_NAME: str = os.getenv("DB_NAME", "") DB_PORT: str = os.getenv("DB_PORT", "3306") DB_ECHO: bool = os.getenv("DB_ECHO", "true").lower() == "true" if not DB_NAME: raise ValueError("DB_NAME 환경변수가 설정되지 않았습니다.") # 비밀번호 특수문자 허용 encoded_password = urllib.parse.quote_plus(DB_PASSWORD) DATABASE_URL: str = f"mysql+asyncmy://{DB_USERNAME}:{encoded_password}@{DB_HOST}:{DB_PORT}/{DB_NAME}" engine: AsyncEngine = create_async_engine( DATABASE_URL, echo=DB_ECHO, pool_size=10, max_overflow=0, pool_timeout=30, # second pool_recycle=60, # second pool_pre_ping=True, ) SessionFactory = async_sessionmaker(autocommit=False, autoflush=False, bind=engine) async def get_db() -> AsyncGenerator[AsyncSession, None]: session = SessionFactory() try: yield session finally: await session.close() # user_route.py from typing import Dict from fastapi import APIRouter, Depends, status from src.app.dependency.query_param_denpendency import snake_case_query from src.core.common_type import V from src.core.exception.not_found_exceptions import UserNotFoundExceiption from src.db.connection import get_db from src.entity.user import UserEntity from src.repository.user import UserRepository, get_user_repository from src.dto.response.user_response import UserResponse router = APIRouter(prefix="/recommend") @router.get(path="", status_code=status.HTTP_200_OK, response_model=UserResponse) async def get_recommend_schedule( params: Dict[str, V]=Depends(snake_case_query), user_repo: UserRepository=Depends(get_user_repository) ): print(1) user_id: int = int(params.get("user_id", None)) user: UserEntity | None = await user_repo.get_user_by_id(user_id) if not user: raise UserNotFoundExceiption() user = UserResponse.model_validate(user) return user # base_repository.py from typing import Type from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from src.core.common_type import E class BaseRepository: def __init__(self, db: AsyncSession): self.db = db async def get_entity_by_id(self, model: Type[E], entity_id: int) -> E | None: print(2) entity: E | None = await self.db.execute(select(model).where(model.id==entity_id)) return entity.scalars().first() # user_repo.py from fastapi import Depends from sqlalchemy.ext.asyncio import AsyncSession from src.db.connection import get_db from src.entity.user import UserEntity from src.repository.base_repository import BaseRepository def get_user_repository(db: AsyncSession = Depends(get_db)) -> "UserRepository": return UserRepository(db) class UserRepository(BaseRepository): async def get_user_by_id(self, user_id: int) -> UserEntity | None: print(3) return await self.get_entity_by_id(UserEntity, user_id) # user_response.py from datetime import datetime from typing import Optional from pydantic import BaseModel class UserResponse(BaseModel): id: int name: str nickname: str email: str phone: str join_date: datetime updated_at: Optional[datetime] = None deleted_at: Optional[datetime] = None class Config: from_attributes = True 도대체 어디서 문제가 생긴걸까요...
python FastAPI websocket asyncio pubsub
윤서준
2025-03-08T14:36:44.555Z
댓글 5
좋아요 0
조회수 589
미해결
FastAPI 완벽 가이드
머신러닝 강좌는 언제 오픈하나요? 빨리듣고 싶습니다. ㅎㅎ 일 때문에 빨리 듣고싶은데 프리뷰 필요하시면 연락부탁드립니다.
python sql sqlalchemy FastAPI
SpeedGogo
2025-03-08T13:00:53.388Z
댓글 2
좋아요 0
조회수 160