运行时错误(f“目录“{Directory}”不存在”)运行时错误:目录“app/static”不存在

2024-10-03 09:13:35 发布

您现在位置:Python中文网/ 问答频道 /正文

运行server.py文件时出错

File "C:\Users\nawin\AppData\Local\Programs\Python\Python38\lib\site-packages\starlette\staticfiles.py", line 57, in __init__
    raise RuntimeError(f"Directory '{directory}' does not exist")
RuntimeError: Directory 'app/static' does not exist

server.py文件

app = Starlette()
app.add_middleware(CORSMiddleware, allow_origins=['*'], allow_headers=['X-Requested-With', 'Content-Type'])
app.mount('/static', StaticFiles(directory='app/static'))

python版本3.8 操作系统windows 10


Tags: 文件pyappservernotstaticusersdirectory
1条回答
网友
1楼 · 发布于 2024-10-03 09:13:35

了解程序的执行路径非常重要(对于GNU/Linux环境):

如果您有这样一个工作目录:~/working/myprogram

第一例

  1. 第一次访问您的工作目录:cd ~/working/myprogram
  2. 执行:python3 mysuper.py

然后您可以毫无问题地执行

第二种情况

但如果您在另一个目录中:

  1. 转到桌面文件夹:cd ~/Desktop
  2. 执行:python3 ~/working/myprogram/mysuper.py

在第二种情况下,您将遇到问题。为了避免这种情况,有一个建议(很难看),但可以是:

import os
script_dir = os.path.dirname(__file__)
st_abs_file_path = os.path.join(script_dir, "static/")
app.mount("/static", StaticFiles(directory=st_abs_file_path), name="static")

相关问题 更多 >