inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

묻고 답해요

172만명의 커뮤니티!! 함께 토론해봐요.

파이썬 face-recognition 모듈 설치 오류

미해결

pip를 통해서 face-recognition 모듈을 설치하려는데 아래 사진과 같은 오류가 계속 발생합니다. pip 버전은 제일 최신 버전 파이썬 버전은 3.11.4 인터넷 보니 CMake를 설치하래서 일단 CMake 버전은 3.28.1입니다 아 dlib도 pip말고 직접 설치하래서 했더니 밑에 빨간 글자를 제외하고 위에 'subprocess.CalledProcessError' 부분과 똑같은 오류가 발생하더군요 이걸로 계속 고통받다 마지막으로 질문해봅니다 ㅠ

  • python
  • 파이썬
댓글 1 좋아요 0 조회수 417

Bind for 0.0.0.0:8080 failed: port is already allocated

미해결

Airflow 마스터 클래스

아무것도 변경한게 없는데 아래 에러가 나옵니다 Error response from daemon: driver failed programming external connectivity on endpoint Bind for 0.0.0.0:8080 failed: port is already allocated 컴퓨터를 재시작해도 나옵니다. 도커 데스크탑이 깔려있긴 하지만 종료한 상태입니다. 설마 도커 데스크탑 설치했다고 이러는 건 아니겠죠..?

  • python
  • 데이터-엔지니어링
  • airflow
인프독학 댓글 1 좋아요 0 조회수 1169

(실습) ORM 적용 - HTTP Response 처리

미해결

실전! FastAPI 입문

from typing import List from fastapi import FastAPI, Body, HTTPException, Depends from pydantic import BaseModel from sqlalchemy.orm import Session from database.orm import ToDo from database.connection import get_db from database.repository import get_todos from schema.response import ListToDoResponse, ToDoSchema app = FastAPI() @app.get("/") def heath_check_handler(): return {"ping": "pong"} todo_data = { 1: { "id": 1, "contents": "실전! FastAPI 섹션 0 수강", "is_done": True, }, 2: { "id": 2, "contents": "실전! FastAPI 섹션 1 수강", "is_done": False, }, 3: { "id": 3, "contents": "실전! FastAPI 섹션 2 수강", "is_done": False, }, } @app.get("/todos", status_code=200) def get_todos_handler( order: str | None = None, session: Session = Depends(get_db), ) -> ListToDoResponse: todos: List[ToDo] = get_todos(session=session) if order and order == "DESC": return ListToDoResponse( todos=[ToDoSchema.from_orm(todo) for todo in todos[::-1]] ) return ListToDoResponse( todos=[ToDoSchema.from_orm(todo) for todo in todos] ) @app.get("/todos/{todo_id}", status_code=200) def get_todo_handler(todo_id: int): todo = todo_data.get(todo_id) if todo: return todo raise HTTPException(status_code=404, detail="ToDo Not Found") class CreateToDoRequest(BaseModel): id: int contents: str is_done: bool @app.post("/todos", status_code=201) def create_todo_handler(request: CreateToDoRequest): todo_data[request.id] = request.dict() return todo_data[request.id] @app.patch("/todos/{todo_id}", status_code=200) def update_todo_handler( todo_id: int, is_done: bool = Body(..., embed=True) ): todo = todo_data.get(todo_id) if todo: todo["is_done"] = is_done return todo raise HTTPException(status_code=404, detail="ToDo Not Found") @app.delete("/todos/{todo_id}") def delete_todo_handler(todo_id: int): todo = todo_data.pop(todo_id, None) if todo: return raise HTTPException(status_code=404, detail="ToDo Not Found") from typing import List from pydantic import BaseModel class ToDoSchema(BaseModel): id: int contents: str is_done: bool class Config: orm_mode = True class ListToDoResponse(BaseModel): todos: List[ToDoSchema] from typing import List from sqlalchemy import select from sqlalchemy.orm import Session from database.orm import ToDo def get_todos(session: Session) -> List[ToDo]: return list(session.scalars(select(ToDo))) from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker DATABASE_URL = "mysql+pymysql://root:todos@127.0.0.1:3306/todos" engine = create_engine(DATABASE_URL, echo=True) SessionFactory = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_db(): session = SessionFactory() try: yield session finally: session.close() from sqlalchemy import Boolean, Column, Integer, String from sqlalchemy.orm import declarative_base Base = declarative_base() class ToDo(Base): __tablename__ = 'todo' id = Column(Integer, primary_key=True, index=True) contents = Column(String(256), nullable=False) is_done = Column(Boolean, nullable=False) def __repr__(self): return f"ToDo(id={self.id}, contents={self.contents}, is_done={self.is_done})" 에러가 납니다. 파이썬 콘솔 <input>:1: PydanticDeprecatedSince20: The from_orm method is deprecated; from schema.response import ToDoSchema from datagbase.orm import ToDo Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2023.3.2\plugins\python\helpers\pydev\pydevconsole.py", line 364, in runcode coro = func() ^^^^^^ File "<input>", line 1, in <module> File "C:\Program Files\JetBrains\PyCharm 2023.3.2\plugins\python\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import module = self._system_import(name, args, *kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ModuleNotFoundError: No module named 'datagbase' from database.orm import ToDo todo = ToDo(id=100, contents="test", is_done=True) ToDoSchema.from_orm(todo) <input>:1: PydanticDeprecatedSince20: The from_orm method is deprecated; set model_config['from_attributes']=True and use model_validate instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.5/migration/ Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2023.3.2\plugins\python\helpers\pydev\pydevconsole.py", line 364, in runcode coro = func() ^^^^^^ File "<input>", line 1, in <module> File "C:\Users\manag\pyProject\todos\Lib\site-packages\typing_extensions.py", line 2499, in wrapper return arg(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^ File "C:\Users\manag\pyProject\todos\Lib\site-packages\pydantic\main.py", line 1126, in from_orm raise PydanticUserError( pydantic.errors.PydanticUserError: You must set the config attribute from_attributes=True to use from_orm http://localhost:8000/docs#/default/get_todos_handler_todos_get 접속시 터미널 INFO: 127.0.0.1:56312 - "GET /docs HTTP/1.1" 200 OK INFO: 127.0.0.1:56312 - "GET /openapi.json HTTP/1.1" 200 OK 2024-01-23 16:06:15,108 INFO sqlalchemy.engine.Engine BEGIN (implicit) 2024-01-23 16:06:15,109 INFO sqlalchemy.engine.Engine SELECT todo.id, todo.contents, todo.is_done FROM todo 2024-01-23 16:06:15,109 INFO sqlalchemy.engine.Engine [cached since 826.5s ago] {} 2024-01-23 16:06:15,113 INFO sqlalchemy.engine.Engine ROLLBACK INFO: 127.0.0.1:56312 - "GET /todos HTTP/1.1" 500 Internal Server Error ERROR: Exception in ASGI application Traceback (most recent call last): File "C:\Users\manag\pyProject\todos\Lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 404, in run_asgi result = await app( # type: ignore[func-returns-value] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\manag\pyProject\todos\Lib\site-packages\uvicorn\middleware\proxy_headers.py", line 84, in call return await self.app(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\manag\pyProject\todos\Lib\site-packages\fastapi\applications.py", line 1054, in call await super().__call__(scope, receive, send) File "C:\Users\manag\pyProject\todos\Lib\site-packages\starlette\applications.py", line 123, in call await self.middleware_stack(scope, receive, send) File "C:\Users\manag\pyProject\todos\Lib\site-packages\starlette\middleware\errors.py", line 186, in call raise exc File "C:\Users\manag\pyProject\todos\Lib\site-packages\starlette\middleware\errors.py", line 164, in call await self.app(scope, receive, _send) File "C:\Users\manag\pyProject\todos\Lib\site-packages\starlette\middleware\exceptions.py", line 62, in call await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) File "C:\Users\manag\pyProject\todos\Lib\site-packages\starlette\_exception_handler.py", line 64, in wrapped_app raise exc File "C:\Users\manag\pyProject\todos\Lib\site-packages\starlette\_exception_handler.py", line 53, in wrapped_app await app(scope, receive, sender) File "C:\Users\manag\pyProject\todos\Lib\site-packages\starlette\routing.py", line 762, in call await self.middleware_stack(scope, receive, send) File "C:\Users\manag\pyProject\todos\Lib\site-packages\starlette\routing.py", line 782, in app await route.handle(scope, receive, send) File "C:\Users\manag\pyProject\todos\Lib\site-packages\starlette\routing.py", line 297, in handle await self.app(scope, receive, send) File "C:\Users\manag\pyProject\todos\Lib\site-packages\starlette\routing.py", line 77, in app await wrap_app_handling_exceptions(app, request)(scope, receive, send) File "C:\Users\manag\pyProject\todos\Lib\site-packages\starlette\_exception_handler.py", line 64, in wrapped_app raise exc File "C:\Users\manag\pyProject\todos\Lib\site-packages\starlette\_exception_handler.py", line 53, in wrapped_app await app(scope, receive, sender) File "C:\Users\manag\pyProject\todos\Lib\site-packages\starlette\routing.py", line 72, in app response = await func(request) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\manag\pyProject\todos\Lib\site-packages\fastapi\routing.py", line 299, in app raise e File "C:\Users\manag\pyProject\todos\Lib\site-packages\fastapi\routing.py", line 294, in app raw_response = await run_endpoint_function( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\manag\pyProject\todos\Lib\site-packages\fastapi\routing.py", line 193, in run_endpoint_function return await run_in_threadpool(dependant.call, **values) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\manag\pyProject\todos\Lib\site-packages\starlette\concurrency.py", line 40, in run_in_threadpool return await anyio.to_thread.run_sync(func, *args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\manag\pyProject\todos\Lib\site-packages\anyio\to_thread.py", line 56, in run_sync return await get_async_backend().run_sync_in_worker_thread( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\manag\pyProject\todos\Lib\site-packages\anyio\_backends\_asyncio.py", line 2134, in run_sync_in_worker_thread return await future ^^^^^^^^^^^^ File "C:\Users\manag\pyProject\todos\Lib\site-packages\anyio\_backends\_asyncio.py", line 851, in run result = context.run(func, *args) ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\manag\pyProject\todos\src\main.py", line 48, in get_todos_handler todos=[ToDoSchema.from_orm(todo) for todo in todos] ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\manag\pyProject\todos\Lib\site-packages\typing_extensions.py", line 2499, in wrapper return arg(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^ File "C:\Users\manag\pyProject\todos\Lib\site-packages\pydantic\main.py", line 1126, in from_orm raise PydanticUserError( pydantic.errors.PydanticUserError: You must set the config attribute from_attributes=True to use from_orm

  • python
  • 리팩토링
  • orm
  • FastAPI
  • pytest
네오스카이 댓글 2 좋아요 0 조회수 1267

DB volume 설정 - 컨테이너 재기동시 DBeaver 테이블 사라지는 경우

해결됨

Airflow 마스터 클래스

안녕하세요, docker volume 설정에 관해서 궁금한 점이 있어 질문드립니다. (상황설명) postgres 컨테이너 올리는 내용을 참고하여 mariadb 컨테이너를 올리고자 하는 상황입니다. (docker-compose.yaml에서 mariadb 컨테이너 내용 추가 --> docker compose up --> dbeaver 연결) (질문) 도커의 경우 컨테이너를 내리면 데이터가 모두 사라지기 때문에, 데이터를 영속적으로 저장하고 있기 위해서 볼륨을 설정한다고 이해했습니다. 제가 이해한 바에 따르면 DB 컨테이너에서 볼륨을 지정했을 때엔, 도커를 재기동해도 데이터가 남아있게 되는 것인데 --> 도커 재기동시 dbeaver mariadb의 테이블과 데이터가 사라지게 되는 상황 이 맞는 걸까요..? 도커 재기동시에도 dbeaver 데이터를 남겨두고 싶은데 제가 볼륨 설정을 잘못한 것인지? 혹은 제가 볼륨에 대한 이해한 것이 잘못 되었다면 어떻게 설정해야 재기동시에도 dbeaver mariadb 데이터가 남아있을 수 있을지? 여쭤봅니다. *도커 재기동 => docker compose down / docker compose up -d (참고내용) #docker-compose.yaml services: mariadb: image: mariadb:10 container_name: mariadb-container environment: MYSQL_USER: user MYSQL_PASSWORD: passwd MYSQL_ROOT_PASSWORD: root_pw MYSQL_DATABASE: mariadb TZ: Asia/Seoul volumes: - mariadb-db-volume:/var/lib/mysql/data restart: always ports: - 3307:3306 networks: network_custom: ipv4_address: 172.28.0.2 ... volumes: postgres-db-volume: mariadb-db-volume: networks: network_custom: driver: bridge ipam: driver: default config: - subnet: 172.28.0.0/16 gateway: 172.28.0.1 # sudo docker volume ls # sudo docker inspect dhkim_mariadb-db-volume #volume mount directory cd /var/lib/docker/volumes/dhkim_mariadb-db-volume/_data ls -al #도커재기동시 dbeaver 화면(table 사라짐)

  • python
  • 데이터-엔지니어링
  • airflow
김도현 댓글 1 좋아요 1 조회수 495

피미 인디언 당뇨병 예측 관련 질문

해결됨

[개정판] 파이썬 머신러닝 완벽 가이드

교수님 안녕하십니까 교수님의 수업을 정말 즐기면서 듣고있는 AI빅데이터 전공 대학생입니다. 교수님의 강의 피마 인디언 당뇨병 예측 편을 보고 여태 배운 것을 백분 활용하여 제 방식대로 따로 모델을 구현을 해보았는데요. 먼저 임신횟수와 Outcome을 제외한 나머지 column들에 있는 0 값들은 모두 결측치로 판단하고 평균 값으로 대체하였습니다. RandomForestClassifier 알고리즘을 사용하고 GridSearchCV 함수를 통해 best estimator를 추출였습니다. 정밀도와 재현율이 동시에 높으면 좋지만 재현율이 증가하면 정밀도가 하락하는 현상(trade-off) 때문에 둘 중 하나를 선택해야 했고 이 피마 인디언 당뇨병 데이터 셋 같은 경우 병의 발견 목적으로 모델을 제작한다고 했을 때 실제로 당뇨병인데 모델이 당뇨병이 아니라고 예측하는 것이 치명적이라고 생각하여 정밀도 보다는 재현율을 중점적으로 보았습니다. 그리하여 precision_recall_curve 함수를 통해 최적의 재현율과 F1_score얻은 threshold 값을 추출하였습니다. 제가 얻은 값은 오차 행렬 [[72 28] [ 4 50]] 정확도: 79.22% , 정밀도: 64.10% , 재현율 92.59%, F1_Score: 75.76% 임계값: 0.32212471005503873 입니다. 오차 행렬을 보았을때도 한쪽에 치우쳐있는 불균형도 없다고 판단하였고 정밀도와 재현율 f1_score도 괜찮게 나왔다고 판단했습니다. 임계값을 0.32212471005503873로 주었을 때 roc_auc_score는 0.82296이라는 1에 꽤나 근접한 수치를 얻었습니다. 질문1: 이런식으로 모델을 찾아가는 방식이 옳은 방식인지 궁금합니다. 질문2: 제가 선택한 모델을 사용한다고 한다면 매번 RandomClassifier로 fit한 model을 Binarizer을 통해서 threshold 값을 매번 지정해주어야 하는건가요? 애초에 처음 모델을 fit할 때 임계값을 제가 부여는 못하는 것일가요?

  • python
  • 머신러닝
  • 통계
신봉균 댓글 1 좋아요 1 조회수 365

trigger rule 설정 질문

미해결

Airflow 마스터 클래스

안녕하세요. 트리거룰 기능 관련해서 질문드립니다. 강의에는 1개 이상 스킵, 컴플리트, 모두 컴플리트 이런 식의 조건만 소개되어 있는데, 특정 테스크를 지정해서 설정하는 방법은 없나요? 예를 들어, 5개 상위 테스크 중에 2,4번 테스크가 완료되는 경우에만 실행한다, 이런 식의 조건이 가능한지 궁금합니다. 별개로 airflow2 강의도 계획 중이신지 궁금합니다!

  • python
  • 데이터-엔지니어링
  • airflow
jihoon 댓글 1 좋아요 0 조회수 308

test 버튼 비활성화

미해결

Airflow 마스터 클래스

SimpleHttp 오퍼레이터로 서울시 공공데이터 API 받아오기위해 커넥션 작성 중 test버튼이 비활성화 되어있습니다. 구글링을 통해 해당 도커 airflow-webserver 의 ariflow.cfg 상태변수 test_connection = Enabled로 변경 후 도커를 내렸다 다시 올렸는데도 그대로 test 버튼이 비활성화 되어있습니다. 해결 방법이 궁금합니다. 참고로 저는 unbuntu 22 버전에 실습 중 입니다.

  • python
  • 데이터-엔지니어링
  • airflow
양유정 댓글 2 좋아요 0 조회수 370

502 Bad Gateway

해결됨

작정하고 장고! Django로 Pinterest 따라만들기 : 바닥부터 배포까지

2024/01/15 15:08:24 [error] 22#22: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.64.1, server: , request: "GET / HTTP/1.1", upstream: "http://172.18.0.2:8000/", host: "192.168.64.7" 위와 같은 오류가 발생하는데 문제가 무엇인지 모르겠습니다.

  • python
  • django
  • docker
댓글 0 좋아요 0 조회수 489

mariadb 접근권한 오류

해결됨

작정하고 장고! Django로 Pinterest 따라만들기 : 바닥부터 배포까지

File "/usr/local/lib/python3.9/site-packages/MySQLdb/connections.py", line 193, in init super().__init__(*args, **kwargs2) django.db.utils.OperationalError: (1044, "Access denied for user 'django'@'%' to database 'django'") mariadb 컨테이너를 실행 후, django 컨테이너를 실행 시 위와 같은 오류가 발생합니다. 찾아보니 django 에 대한 권한이 없어서 그렇다고 하는데, 해결방법이 있을까요?

  • python
  • django
  • docker
댓글 1 좋아요 0 조회수 563

5장 회귀 실습 2:캐글경연 주택가격 예측-Advanced Regression Techniques - 01 질문 있습니다😊

미해결

[개정판] 파이썬 머신러닝 완벽 가이드

선생님 안녕하세요! 5장 회귀 실습 2:캐글경연 주택가격 예측-Advanced Regression Techniques - 01 을 듣다가 타겟 값인 Price를 로그 변환하여 정규 분포 형태로 변환하고, 피처들 중 숫자형 컬럼의 Null 값 데이터 처리 부분 코드를 다음과 같이 썼습니다. 그런데 결과가 사진과 같이 float64가 포함된 형태로 나왔습니다. 제가 어떤 부분에서 잘못한 건지, 그리고 어떻게 해야 선생님과 같은 결과가 나올 수 있나요?ㅎㅎ # SalePrice 로그 변환 original_SalePrice = house_df['SalePrice'] house_df['SalePrice'] = np.log1p(house_df['SalePrice']) # Null이 너무 많은 컬럼들과 불필요한 컬럼 삭제 house_df.drop(['Id', 'PoolQC', 'MiscFeature', 'Alley', 'Fence', 'FireplaceQu'], axis=1, inplace=True) # Drop하지 않는 숫자형 Null 컬럼들은 평균 값으로 대체 num_columns = house_df.dtypes[house_df.dtypes !='object'].index.to_list() house_df[num_columns].fillna(house_df[num_columns].mean(), inplace=True) # Null 값이 있는 피처명과 타입을 추출 null_column_count = house_df.isnull().sum()[house_df.isnull().sum() > 0] print('## Null 피처의 Type :\n', house_df.dtypes[null_column_count.index])

  • python
  • 머신러닝
  • 통계
곽민선 댓글 1 좋아요 0 조회수 240

python-telegram-bot 2021년 20 버전 이후

미해결

파이썬으로 영화 예매 오픈 알리미 만들기

python-telegram-bot 20 버전부터는 비동기 프로그래밍이 적용되어 강의와는 다른 코드가 필요합니다. https://github.com/python-telegram-bot/python-telegram-bot/wiki/Introduction-to-the-API 위 깃허브 python-telegram-bot 공식 위키 페이지로 가시면 필수적이고 간단한 용례들을 보실 수 있습니다.

  • python
FastCampus 댓글 1 좋아요 0 조회수 1130

HDFS, Hive new Connection : apt-get update

해결됨

Airflow 마스터 클래스

HDFS, Hive를 위한 Connection 추가 과정에서 이미지를 빌드하는 부분에서 에러가 발생합니다. 아래 명령 실행 후 에러가 발생하며, 에러 부분은 이미지(참고2)로 첨부하였습니다. sudo docker build -t airflow_custom . (참고 - Dockerfile 내용 / airflow 2.8.0 version 설치) (참고2 - 에러로그)

  • python
  • 데이터-엔지니어링
  • airflow
김도현 댓글 2 좋아요 1 조회수 347

python 오퍼레이터 실행되지 않음

미해결

Airflow 마스터 클래스

아래 코드 작동을 안합니다 어디가 잘못된 걸까요 operator 생성된게 보이지 않습니다 git pull까지 다한 상태입니다 from airflow import DAG import pendulum import datetime from airflow.operators.python import PythonOperator import random with DAG( dag_id="dags_python_operator", schedule="30 6 * *", start_date=pendulum.datetime(2024, 1, 9, tz="Asia/Seoul"), catchup=False, ) as dag: def select_fruit(): fruit = ['APPLE', 'BANANA', 'ORANGE', 'AVOCADO'] rand_int = random.randint(0,3) print(fruit[rand_int]) py_t1 = PythonOperator( task_id = 'py_t1', python_callable=select_fruit ) py_t1

  • python
  • 데이터-엔지니어링
  • airflow
인프독학 댓글 1 좋아요 0 조회수 357

현재 23.01.07 기준으로 하시는 분 계시면 보세요.

미해결

파이썬으로 영화 예매 오픈 알리미 만들기

해당 강의에서 작성하는 코드를 그대로 실행하면 되지 않습니다. 현재 iframe 태그가 자바스크립트를 통해 실행되기 때문에 페이지가 로드된 후에도 자바스크립트가 실행될 시간이 필요합니다. 강의처럼 iframe의 주소만 따와서 실행시키는 것이 아닌 전체 주소를 가져와 iframe 태그로 전환시켜주고 자바스크립트 실행까지 기다려 주는 방식으로 진행하셔야 합니다. https://velog.io/@os_js/%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EC%9B%B9-%ED%81%AC%EB%A1%A4%EB%A7%81%EC%9D%B4%EC%9A%A9-%ED%85%94%EB%A0%88%EA%B7%B8%EB%9E%A8-%EC%B1%97%EB%B4%87 저도 강의중 안됐던 내용이 있었기에 그에 대한 내용을 블로그에 올려두었습니다. 강의 진행대로 따라하다가 안되는 부분만 정리하여 올렸기 때문에 강의내용과 비교하시면서 보셔야 될 듯 합니다.

  • python
나도했음 댓글 1 좋아요 0 조회수 611

dags_external_task_sensor 오류 질문

미해결

Airflow 마스터 클래스

선생님 안녕하세요 좋은 강의 감사합니다. section 9 dags_external_task_sensor 에서, task b 가 fail로 뜨지 않고 계속 running 인 오류가 나는 데 이유를 모르겠습니다. dags_branch_python_operator는 아래와 같습니다. from airflow import DAG import pendulum from airflow.operators.python import PythonOperator from airflow.operators.python import BranchPythonOperator with DAG( dag_id='dags_branch_python_operator', start_date=pendulum.datetime(2023,4,1, tz='Asia/Seoul'), schedule='0 1 * * *', catchup=False ) as dag: def select_random(): import random item_lst = ['A','B','C'] selected_item = random.choice(item_lst) # 만약 실행해야 하는 task가 하나라면 task_id를 str 으로 하나만 넣는다. # 만약 실행해야 하는 task가 두개 이상이라면 list of str을 넣는다. if selected_item == 'A': return 'task_a' elif selected_item in ['B','C']: return ['task_b','task_c'] python_branch_task = BranchPythonOperator( task_id='python_branch_task', python_callable=select_random ) def common_func(**kwargs): print(kwargs['selected']) task_a = PythonOperator( task_id='task_a', python_callable=common_func, op_kwargs={'selected':'A'} ) task_b = PythonOperator( task_id='task_b', python_callable=common_func, op_kwargs={'selected':'B'} ) task_c = PythonOperator( task_id='task_c', python_callable=common_func, op_kwargs={'selected':'C'} ) python_branch_task >> [task_a, task_b, task_c] 마지막으로 돌린 기록은 a를 선택하고, b,c 는 skipped 된 상태입니다. dags_external_task_sensor 는 아래와 같고요 from airflow import DAG from airflow.sensors.external_task import ExternalTaskSensor import pendulum from datetime import timedelta from airflow.utils.state import State with DAG( dag_id='dags_external_task_sensor', start_date=pendulum.datetime(2023,4,1, tz='Asia/Seoul'), schedule='0 7 * * *', catchup=False ) as dag: external_task_sensor_a = ExternalTaskSensor( task_id='external_task_sensor_a', external_dag_id = 'dags_branch_python_operator', external_task_id='task_a', allowed_states=[State.SKIPPED], # task_a 가 skipped로 되면 sensor_a task는 success로 표시된다는 뜻 # allowed states 조건을 만족하지 못하면 계속 실행된다. 10초마다 execution_delta=timedelta(hours=6), poke_interval=10 # 10초 ) external_task_sensor_b = ExternalTaskSensor( task_id='external_task_sensor_b', external_dag_id = 'dags_branch_python_operator', external_task_id='task_b', failed_states=[State.SKIPPED], # task_b 가 skipped로 되면 sensor_b task는 failed로 표시된다는 뜻 execution_delta=timedelta(hours=6), poke_interval=10 ) external_task_sensor_c = ExternalTaskSensor( task_id='external_task_sensor_c', external_dag_id = 'dags_branch_python_operator', external_task_id='task_c', allowed_states=[State.SUCCESS], # task_c 가 success로 되면 sensor_c task는 success로 표시된다는 뜻 # success가 뜰때까지 꼐속 시도를 한다. execution_delta=timedelta(hours=6), poke_interval=10 ) 이대로라면 강의에서 나온것 처럼 , b만 fail로 뜨고 a,c는 계속 running 이어야 하는데요, 셋다 running 이 나옵니다. log를 보면 계속 b를 poke만 하고 있더라고요 혹시 무엇이 문제일까요..?ㅠ

  • python
  • 데이터-엔지니어링
  • airflow
nathan 댓글 1 좋아요 0 조회수 374

시각화 관련 질문

미해결

Airflow 마스터 클래스

선생님 안녕하세요 좋은 강의 감사합니다. 강의 내용에 대한 질문은 아니고요. 혹시 실습1에서 Rshiny를 사용하신 이유가 따로 있으실까요? Airflow는 파이썬이고, Rshiny를 처음 보는 것이어서 파이썬으로 된 시각화 라이브러리를 왜 사용하지 않는지 궁금합니다. plotly의 dash 같은 것은 airflow와 연동이 안되는건가요?

  • python
  • 데이터-엔지니어링
  • airflow
nathan 댓글 1 좋아요 0 조회수 212

맥으로 에어플로우 라이브러리 설치가 안됩니다.

미해결

Airflow 마스터 클래스

1 error generated. error: command '/usr/bin/gcc' failed with exit code 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for google-re2 Failed to build google-re2 ERROR: Could not build wheels for google-re2, which is required to install pyproject.toml-based projects 이렇게 뜨는데 뭐가 문젤까요 검색해도 해결방법이 안뜨네요.

  • python
  • 데이터-엔지니어링
  • airflow
이상윤 댓글 1 좋아요 0 조회수 1347

강의 소스코드는 어디서 찾을 수 있을까요?

미해결

프로젝트를 통해 배우는 파이썬 프로그램

안녕하세요. 강의 소스코드는 어디서 찾을 수 있을까요? 말씀하신 사이트에 로그인했는데, 그다음이 없네요. 확인 부탁드립니다.

  • python
  • Raspberry-Pi
  • iot
훈쭌엄마 댓글 2 좋아요 0 조회수 335

병렬처리 질문드립니다.

해결됨

실리콘밸리 엔지니어와 함께하는 Apache Airflow

안녕하세요 선생님 🙂 airflow 실습중에 airflow의 병렬처리에서 메시지 큐가 어떻게 처리되는지 궁금하여 질문드립니다! celery와 k8s를 병렬처리에 사용함에 있어서 메시지 큐를 별도로 설정하지 않는것 같은데요. 이 둘은 메시지 큐를 알아서 처리해주는건거요? celery와 k8s를 사용한 병렬 처리방식은 이해못해서 일단은 concurrent 패키지의 ThreadPoolExecutor 사용하여 병렬 처리를 하였습니다. airflow에서 병렬처리시 일반적으로 threadPool을 사용하는지도 궁금합니다. threadPool이 일반적이지 않다면 어떤 방식으로 병렬 처리를 하는지 궁금합니다! 항상 감사합니다! 🙂

  • python
  • 빅데이터
  • 데이터-엔지니어링
  • airflow
JP 댓글 2 좋아요 1 조회수 531

색션8 postgres

해결됨

Airflow 마스터 클래스

안녕하세요 선생님 색션8 2장에서 docker-compose.yaml파일을 수정 하고 sudo docker compose up 하니 docker-compose.yaml: services.airflow-scheduler.depends_on.networks condition is required 라는 오류가 납니다. 코드는 # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # # Basic Airflow cluster configuration for CeleryExecutor with Redis and PostgreSQL. # # WARNING: This configuration is for local development. Do not use it in a production deployment. # # This configuration supports basic configuration using environment variables or an .env file # The following variables are supported: # # AIRFLOW_IMAGE_NAME - Docker image name used to run Airflow. # Default: apache/airflow:2.7.3 # AIRFLOW_UID - User ID in Airflow containers # Default: 50000 # AIRFLOW_PROJ_DIR - Base path to which all the files will be volumed. # Default: . # Those configurations are useful mostly in case of standalone testing/running Airflow in test/try-out mode # # _AIRFLOW_WWW_USER_USERNAME - Username for the administrator account (if requested). # Default: airflow # _AIRFLOW_WWW_USER_PASSWORD - Password for the administrator account (if requested). # Default: airflow # _PIP_ADDITIONAL_REQUIREMENTS - Additional PIP requirements to add when starting all containers. # Use this option ONLY for quick checks. Installing requirements at container # startup is done EVERY TIME the service is started. # A better way is to build a custom image or extend the official image # as described in https://airflow.apache.org/docs/docker-stack/build.html. # Default: '' # # Feel free to modify this file to suit your needs. --- version: '3.8' x-airflow-common: &airflow-common # In order to add custom dependencies or upgrade provider packages you can use your extended image. # Comment the image line, place your Dockerfile in the directory where you placed the docker-compose.yaml # and uncomment the "build" line below, Then run `docker-compose build` to build the images. image: ${AIRFLOW_IMAGE_NAME:-apache/airflow:2.7.3} # build: . environment: &airflow-common-env AIRFLOW__CORE__EXECUTOR: CeleryExecutor AIRFLOW__DATABASE__SQL_ALCHEMY_CONN: postgresql+psycopg2://airflow:airflow@postgres/airflow # For backward compatibility, with Airflow <2.3 AIRFLOW__CORE__SQL_ALCHEMY_CONN: postgresql+psycopg2://airflow:airflow@postgres/airflow AIRFLOW__CELERY__RESULT_BACKEND: db+postgresql://airflow:airflow@postgres/airflow AIRFLOW__CELERY__BROKER_URL: redis://:@redis:6379/0 AIRFLOW__CORE__FERNET_KEY: '' AIRFLOW__CORE__DAGS_ARE_PAUSED_AT_CREATION: 'true' AIRFLOW__CORE__LOAD_EXAMPLES: 'true' AIRFLOW__API__AUTH_BACKENDS: 'airflow.api.auth.backend.basic_auth,airflow.api.auth.backend.session' # yamllint disable rule:line-length # Use simple http server on scheduler for health checks # See https://airflow.apache.org/docs/apache-airflow/stable/administration-and-deployment/logging-monitoring/check-health.html#scheduler-health-check-server # yamllint enable rule:line-length AIRFLOW__SCHEDULER__ENABLE_HEALTH_CHECK: 'true' # WARNING: Use _PIP_ADDITIONAL_REQUIREMENTS option ONLY for a quick checks # for other purpose (development, test and especially production usage) build/extend Airflow image. _PIP_ADDITIONAL_REQUIREMENTS: ${_PIP_ADDITIONAL_REQUIREMENTS:-} AIRFLOW__SMTP__SMTP_HOST: 'smtp.gmail.com' AIRFLOW__SMTP__SMTP_USER: '' AIRFLOW__SMTP__SMTP_PASSWORD: '' AIRFLOW__SMTP__SMTP_PORT: 587 AIRFLOW__SMTP__SMTP_MAIL_FROM: '' volumes: - ${AIRFLOW_PROJ_DIR:-.}/airflow/dags:/opt/airflow/dags - ${AIRFLOW_PROJ_DIR:-.}/logs:/opt/airflow/logs - ${AIRFLOW_PROJ_DIR:-.}/config:/opt/airflow/config - ${AIRFLOW_PROJ_DIR:-.}/airflow/plugins:/opt/airflow/plugins - ${AIRFLOW_PROJ_DIR:-.}/airflow/files:/opt/airflow/files user: "${AIRFLOW_UID:-50000}:0" depends_on: &airflow-common-depends-on redis: condition: service_healthy postgres: condition: service_healthy services: postgres_custom: image: postgres:13 environment: POSTGRES_USER: userbbs POSTGRES_PASSWORD: userbbs POSGRES_DB: userbbs TZ: Asia/Seoul volumes: - postgres-custom-db-volume:/var/lib/postgresql/data ports: - 5432:5432 networks: network_custom: ipv4_address: 172.28.0.3 postgres: image: postgres:13 environment: POSTGRES_USER: airflow POSTGRES_PASSWORD: airflow POSTGRES_DB: airflow volumes: - postgres-db-volume:/var/lib/postgresql/data healthcheck: test: ["CMD", "pg_isready", "-U", "airflow"] interval: 10s retries: 5 start_period: 5s restart: always ports: - 5431:5432 networks: network_custom: ipv4_address: 172.28.0.4 redis: image: redis:latest expose: - 6379 healthcheck: test: ["CMD", "redis-cli", "ping"] interval: 10s timeout: 30s retries: 50 start_period: 30s restart: always networks: network_custom: ipv4_address: 172.28.0.5 airflow-webserver: <<: *airflow-common command: webserver ports: - "8080:8080" healthcheck: test: ["CMD", "curl", "--fail", "http://localhost:8080/health"] interval: 30s timeout: 10s retries: 5 start_period: 30s restart: always depends_on: <<: *airflow-common-depends-on airflow-init: condition: service_completed_successfully networks: network_custom: ipv4_address: 172.28.0.6 airflow-scheduler: <<: *airflow-common command: scheduler healthcheck: test: ["CMD", "curl", "--fail", "http://localhost:8974/health"] interval: 30s timeout: 10s retries: 5 start_period: 30s restart: always depends_on: <<: *airflow-common-depends-on airflow-init: condition: service_completed_successfully networks: network_custom: ipv4_address: 172.28.0.7 airflow-worker: <<: *airflow-common command: celery worker healthcheck: # yamllint disable rule:line-length test: - "CMD-SHELL" - 'celery --app airflow.providers.celery.executors.celery_executor.app inspect ping -d "celery@$${HOSTNAME}" || celery --app airflow.executors.celery_executor.app inspect ping -d "celery@$${HOSTNAME}"' interval: 30s timeout: 10s retries: 5 start_period: 30s environment: <<: *airflow-common-env # Required to handle warm shutdown of the celery workers properly # See https://airflow.apache.org/docs/docker-stack/entrypoint.html#signal-propagation DUMB_INIT_SETSID: "0" restart: always depends_on: <<: *airflow-common-depends-on airflow-init: condition: service_completed_successfully networks: network_custom: ipv4_address: 172.28.0.8 airflow-triggerer: <<: *airflow-common command: triggerer healthcheck: test: ["CMD-SHELL", 'airflow jobs check --job-type TriggererJob --hostname "$${HOSTNAME}"'] interval: 30s timeout: 10s retries: 5 start_period: 30s restart: always depends_on: <<: *airflow-common-depends-on airflow-init: condition: service_completed_successfully networks: network_custom: ipv4_address: 172.28.0.9 airflow-init: <<: *airflow-common entrypoint: /bin/bash # yamllint disable rule:line-length command: - -c - | function ver() { printf "%04d%04d%04d%04d" $${1//./ } } airflow_version=$$(AIRFLOW__LOGGING__LOGGING_LEVEL=INFO && gosu airflow airflow version) airflow_version_comparable=$$(ver $${airflow_version}) min_airflow_version=2.2.0 min_airflow_version_comparable=$$(ver $${min_airflow_version}) if (( airflow_version_comparable < min_airflow_version_comparable )); then echo echo -e "\033[1;31mERROR!!!: Too old Airflow version $${airflow_version}!\e[0m" echo "The minimum Airflow version supported: $${min_airflow_version}. Only use this or higher!" echo exit 1 fi if [[ -z " 입니다. 어디서 잘못 된걸까요?

  • python
  • 데이터-엔지니어링
  • airflow
가나다 댓글 1 좋아요 0 조회수 327

인기 태그

인프런 TOP Writers

주간 인기글