아래의 엔드포인트 두개의 함수 부분에서 async def download_basic(file_name: str): async def download_custom(file_name: str): if not file_path.startswith(os.path.abspath(DOWNLOAD_DIR)): 이 부부의 file_path를 full_file_path를 아래처럼 할당한 후에 if not full_file_path.startswith(os.path.abspath(DOWNLOAD_DIR)): 으로 수정해야 할 듯 합니다. @app.get("/download/basic/{file_name}") async def download_basic(file_name: str): safe_base_filename = os.path.basename(file_name) file_path = os.path.join(DOWNLOAD_DIR, safe_base_filename) full_file_path = os.path.abspath(file_path) . ' ' if not full_file_path.startswith(os.path.abspath(DOWNLOAD_DIR)): # if not file_path.startswith(os.path.abspath(DOWNLOAD_DIR)): @app.get("/download/custom/{file_name}") async def download_custom(file_name: str): safe_base_filename = os.path.basename(file_name) file_path = os.path.join(DOWNLOAD_DIR, safe_base_filename) full_file_path = os.path.abspath(file_path) . ' ' if not full_file_path.startswith(os.path.abspath(DOWNLOAD_DIR)): # if not file_path.startswith(os.path.abspath(DOWNLOAD_DIR)): 그렇지 않으면 검증이 되지 않습니다. 아래 참고 file_path: ./downloadables/스크린샷_3.png full_file_path: D:\Python_FastAPI\Inflearn_Master\File_API\downloadables\스크린샷_3.png os.path.abspath(DOWNLOAD_DIR): D:\Python_FastAPI\Inflearn_Master\File_API\downloadables
............10%............20%.............30%............40%.............50%............60%.............70%............80%.............90%............100% Welcome to Gradle 8.4! Here are the highlights of this release: - Compiling and testing with Java 21 - Faster Java compilation on Windows - Role focused dependency configurations creation For more details see https://docs.gradle.org/8.4/release-notes.html Starting a Gradle Daemon (subsequent builds will be faster) <==========---> 78% EXECUTING [2m 6s] > :test > Executing test com...Ec2SpringBootSampleApplicationTests > :test > 0 tests completed 78%에서 더이상 올라가지 않고 멈춰있네요.. instance를 지우고 다시 해봐도 동일 합니다 ㅜㅜ 어떤 이유때문인지 감이 아예 안잡혀 문의 드립니다!
에러 로그는 아래와 같아요 File "<frozen importlib._bootstrap_external>", line 999, in exec_module File "<frozen importlib._bootstrap>", line 488, in call with_frames_removed File "/app/ main.py ", line 6, in <module> from app.db.database import Base, async_engine File "/app/app/db/ database.py ", line 1, in <module> from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine ModuleNotFoundError: No module named 'sqlalchemy' WARNING: WatchFiles detected changes in 'app/db/crud/ user.py '. Reloading... Process SpawnProcess-2: Traceback (most recent call last): File "/usr/local/lib/python3.12/multiprocessing/ process.py ", line 314, in _bootstrap self.run () File "/usr/local/lib/python3.12/multiprocessing/ process.py ", line 108, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.12/site-packages/uvicorn/_ subprocess.py ", line 80, in subprocess_started target(sockets=sockets) File "/usr/local/lib/python3.12/site-packages/uvicorn/ server.py ", line 67, in run return asyncio.run (self.serve(sockets=sockets)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/asyncio/ runners.py ", line 195, in run return runner.run (main) ^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/asyncio/ runners.py ", line 118, in run return self._ loop.run _until_complete(task) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "uvloop/loop.pyx", line 1518, in uvloop.loop.Loop.run _until_complete File "/usr/local/lib/python3.12/site-packages/uvicorn/ server.py ", line 71, in serve await self._serve(sockets) File "/usr/local/lib/python3.12/site-packages/uvicorn/ server.py ", line 78, in _serve config.load() File "/usr/local/lib/python3.12/site-packages/uvicorn/ config.py ", line 436, in load self.loaded_app = import_from_string( self.app ) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/uvicorn/ importer.py ", line 22, in import_from_string raise exc from None File "/usr/local/lib/python3.12/site-packages/uvicorn/ importer.py ", line 19, in import_from_string module = importlib.import_module(module_str) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/importlib/__init__.py", line 90, in import_module return bootstrap. gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in gcd import File "<frozen importlib._bootstrap>", line 1360, in find and_load File "<frozen importlib._bootstrap>", line 1331, in find and_load_unlocked File "<frozen importlib._bootstrap>", line 935, in load unlocked File "<frozen importlib._bootstrap_external>", line 999, in exec_module File "<frozen importlib._bootstrap>", line 488, in call with_frames_removed File "/app/ main.py ", line 6, in <module> from app.db.database import Base, async_engine File "/app/app/db/ database.py ", line 1, in <module> from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine ModuleNotFoundError: No module named 'sqlalchemy' 위 에러 때문인지 코드에서 아래 에러? 도 뜨네요 uvicorn main:app --reload도 당연 에러 뜨구요.. 어떤 부분을 확인하면 될까요? ㅠ
31강에서 구현된 users.py의 read_all_users는 화면에 구현이 안되는 것이 맞는 것인가요? Users의 POST /users 밑에 GET /users/all로 있어야 할 것 같은데... ===> PC를 재시작 후 다시 서버를 실행해 보니 나타납니다. DB Browser에서 특정 User의 is_admin을 true로 수정하고 저장까지 완료하고 난 후, 각각의 User들로 로그인해보았습니다. 그런데, is_admin이 false인 모든 User들도 read_all_users의 endpoint인 /users/all에서 모든 회원들의 리스트가 조회가 됩니다. /docs 페이지라서 그런 것인지 아니면 잘못 구현된 것인지 궁금합니다. 강의에서는 docs에서의 이런 상황에 대한 언급이 없어 질문을 드립니다.
30강을 완강후에 Postman을 통해 post로 http://127.0.0.1:8000/token 으로 요청을 보냈는데 아래 처럼 응답으로 토큰이 날아오지 않습니다. 422 Unprocessable Content 에러가 나오구요~~ oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") # http://<your_domain>/token 뭐가 문제일런지요? postman사용법에 맞게 된것 같지가 않은데요..... @@@ 추가 질문 그리고, 더불어서 발급받은 토큰을 /docs에서 Authentication의 어디에 입력을 해서 테스트를 해야 하는지도 같이 안내바랍니다. 여기 client secret에 입력해서 테스트 하는것 같은데.... username, password를 입력해서 로그인하면 token은 잘 생성됩니다. 그리고 이렇게 username과 password로 로그인할 때 생성된 토큰으로 client secret에 입력해서 로그인하면 auth error Error: Unprocessable Content 라는 메시지가 뜹니다. postman사용법이 미숙해서인지 postman에서 post /token으로 날려도 토큰이 반환되어 오질 않습니다. 당연히 docs에서 username, password로 로그인한 후에... 수정, 삭제 권한적용은 잘 적용됩니다.
안녕하세요, 질문 있습니다! 마지막 부분에서 초기 비밀번호 외에 새로 생성한 비밀번호로는 새로 생성할 수 없다고 하셨는데, 호스트 컴퓨터의 폴더를 삭제하고 다시 생성하는 경우 이전에 생성했던 데이터베이스도 모두 삭제되는 게 맞을까요? : 호스트 컴퓨터의 폴더를 삭제하면 데이터도 삭제로 이해면 될지 답변부탁드립니다. (유익한 강의 즐겁게 수강중입니당.. 감사합니다.)
26강에서 User model를 만들고, Task model의 관계 설정까지 하고 env.py에서 User를 임포트하고 난후 alembic revision --autogenerate를 실행하고, alembic upgrade head 를 실행하면 User 테이블과 Task 모델의 관계설정은 잘 만들어 졌지만, 아래에 보이는 것처럼, 제약조건에 name을 지정하라고 나옴니다. 그래서 name을 지정하고 db를 삭제하고, alembic을 초기화된 상태로 만든 후에 다시 똑같은 과정을 거쳐 실행햇는데, 두번째 alembic revision --autogenerate 을 실행하면, sqlalchemy.exc.NoReferencedColumnError: Could not initialize target column for ForeignKey ' users.id ' on table 'tasks': table 'users' has no column named 'id' 이런 오류가 나타납니다. 자꾸 자꾸 계속해서 다시 해봐도 제약조건에 이름을 넣으라고 나오고, 그것을 수정하면 users에 id가 없다는 둥 계속 똑같이 오류가 나옵니다. 해결 방법은 무엇일까요? 완전히 새로 해봐도 똑같은 오류만 계속 반복됩니다.
💡 질문하기 전에 먼저 확인해보세요! UnicodeDecodeError: 'cp949' codec can't decode byte 0xed in position 3465: illegal multibyte sequence 유니코드 관련에러가 발생합니다. utf-8 관련 설정에 문제가 있어보이는데, 해결방법을 구합니다. 별것을 다해본것 같은데 해결이 되질 않습니다. 코드는 알려주신데로 아래와 같이 수정했습니다. # /alembic.ini 파일 sqlalchemy.url = sqlite+aiosqlite:///./sql_app.db # /alembic/env.py 파일 import asyncio # 추가 from logging.config import fileConfig import os # 경로 작업 위해 추가 import sys # 경로 작업 위해 추가 from sqlalchemy import engine_from_config from sqlalchemy import pool # ✨ 추가: 비동기 엔진 설정을 위해 async_engine_from_config 사용 ✨ from sqlalchemy.ext.asyncio import async_engine_from_config from alembic import context # --- ✨ 추가: 프로젝트 루트 경로 추가 (env.py가 app 모듈을 찾도록) ✨ --- # env.py 파일의 부모 디렉토리의 부모 디렉토리 (즉, 프로젝트 루트)를 sys.path에 추가 sys.path.insert(0, os.path.realpath(os.path.join(os.path.dirname(__file__), ".."))) # -------------------------------------------------------------- # --- ✨ 추가: Base 및 모델 임포트 ✨ --- from app.database import Base # database.py의 Base 임포트 import app.sql_models.task # task 모델 모듈 임포트 (Base.metadata가 인식하도록) # 만약 다른 모델 파일들이 있다면 모두 임포트해주는 것이 안전합니다. # ----------------------------------------------------------------------------- # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret the config file for Python logging. # This line sets up loggers basically. if config.config_file_name is not None: fileConfig(config.config_file_name) # add your model's MetaData object here # for 'autogenerate' support # from myapp import mymodel # target_metadata = mymodel.Base.metadata # target_metadata = None # --- ✨변경: target_metadata 설정 ✨ --- target_metadata = Base.metadata # 우리의 모델 메타데이터 지정! # -------------------------------- # other values from the config, defined by the needs of env.py, # can be acquired: # my_important_option = config.get_main_option("my_important_option") # ... etc. # ✨ 추가 ✨----------------------------------------------------------------- def do_run_migrations(connection): # context 설정 및 마이그레이션 실행 (run_sync 내부에서 호출될 함수) context.configure(connection=connection, target_metadata=target_metadata) with context.begin_transaction(): context.run_migrations() # --------------------------------------------------------------------------- # ... (run_migrations_offline 함수는 보통 그대로 둠) ... def run_migrations_offline() -> None: """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output. """ url = config.get_main_option("sqlalchemy.url") context.configure( url=url, target_metadata=target_metadata, literal_binds=True, dialect_opts={"paramstyle": "named"}, ) with context.begin_transaction(): context.run_migrations() # --- ✨ 변경: run_migrations_online 함수 비동기 방식으로 수정 ✨ --- async def run_migrations_online() -> None: """Run migrations in 'online' mode for an async application.""" # config 섹션에서 비동기 엔진 생성 connectable = async_engine_from_config( config.get_section(config.config_ini_section), prefix="sqlalchemy.", poolclass=pool.NullPool, future=True, # SQLAlchemy 2.0 스타일 사용 ) # 비동기적으로 DB 연결 async with connectable.connect() as connection: # 동기적인 마이그레이션 함수(do_run_migrations)를 # 비동기 연결의 run_sync 메서드 내에서 실행 await connection.run_sync(do_run_migrations) # 엔진 연결 종료 await connectable.dispose() # ----------------------------------------------------------------- ''' # ✨ 위의 것으로 수정 def run_migrations_online() -> None: """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ connectable = engine_from_config( config.get_section(config.config_ini_section, {}), prefix="sqlalchemy.", poolclass=pool.NullPool, ) with connectable.connect() as connection: context.configure( connection=connection, target_metadata=target_metadata ) with context.begin_transaction(): context.run_migrations() ''' if context.is_offline_mode(): run_migrations_offline() else: # ✨ run_migrations_online() # 아래로 변경 # 온라인 모드일 경우 비동기 함수 실행 asyncio.run(run_migrations_online())
안녕하세요, 강의 수강 중 질문이 생겨 여쭤봅니다. mysql, mongoDb를 사용하실때는 docker exec -it로 직접 컨테이너에 들어와 실행하시는 과정을 보여주셨는데, postgreSQL 예시에서는 따로 docker exec -it 과정이 강의 내용 중 보이지 않는 것 같아 여쭤봅니다. 실행 방법이 docker exec -it 로 컨테이너에 들어오지 않고 데이터그립을 바로 실행하신 것 같은데, 이렇게 되면 로컬에서 데이터그립의 postgreSQL을 실행시키고 컨테이너 안에서는 postgreSQL을 실행시키지 않은게 아닌가요 .. ? 혹시 제가 놓친 부분이 있다면 죄송합니다 !
13강 15분 즈음에 나오는 DeleteUserCookie함수는 도대체 어디에 있는건가요? 강의 듣는도중 노션에 없는 예시가 음성으로만 나오는데 관련된 코드가 따로 있는건가요? 한 두 강의에서만 그런게 아니라 이전 강의에서도 노션에 없는 코드를 음성으로만 설명하는 경우가 있던데 원래 그런건가요...?
SingleTopic/index.jsx -> voteOptions 으로 전달하는데요 <Chart topicId={topic.topic_id} voteOptions={topic.vote_options} /> Chart/index.jsx ->voteOpitons 으로 받더라구요 제가 웹은 거의 몰라서 변수 선언, 호출 등 이런게 와닿지가 않고 시간적 여유가 없는 상황에 노션 코드를 많이 가져다 써서 공부하고 있는데요..ㅠ 앞으로 강의에서도 노션 코드에 오타 좀 더 신경 써주시면 좋을 것 같아요 c++ 같은 언어에 익숙한 저로서는 이런 에러 발생 시, 찾아가는 것도 도움이 많이 되긴합니다 ㅎㅎ
안녕하세요! 강의 재밌게 잘듣고 있습니다 :] 컨테이너의 Stateless 제약 -> 상태가 업식 때문에 저장 및 공유가 필요한 데이터는 무조건 외부에 저장해야합니다. 라는 내용을 보다가 실무에서는 어떤지 궁금증이 생겼습니다. 실무에서는 DB를 도커로 띄어서 운영을 하는 경우에, DB의 정보들을 별도로 외부에 저장을 하는 것인지 궁금합니다! 제가 생각한 바로는 1. 배치 또는 스냅샷을 사용해서 일정주기마다 백업을 한다. (이 방법을 사용하면 컨테이너가 사라졌을 때와 가장 최근 백업 사이에 간격이 어쩔 수 없이 발생할 것 같다는 생각이 들었습니다.) 2. DB는 RDS 같은 서비스가 있기 때문에 도커를 굳이 사용하지 않는다. 강사님의 의견을 여쭤보고 싶습니다!