【问题标题】:what does forward slash do in this django settings.py python list?在这个 django settings.py python 列表中正斜杠做什么?
【发布时间】:2021-04-13 16:01:53
【问题描述】:

我是 python 新手,我不明白这个正斜杠在 django settings.py 中是如何工作的

STATICFILES_DIRS = [
    BASE_DIR / "static",
]

它似乎是连接 BASE_DIR + "static" 的值,但实际上 str(BASE_DIR) + "static" 对吗?

它是某种特殊的 Django 分隔符吗?

根据 Django 文档,这是正确的用法: https://docs.djangoproject.com/en/3.1/howto/static-files/#configuring-static-files

STATICFILES_DIRS 不是参数列表 - 所以这似乎不适用 https://docs.python.org/3/faq/programming.html#what-does-the-slash-in-the-parameter-list-of-a-function-mean

它不是二元除法运算符: https://docs.python.org/3/reference/expressions.html#binary

【问题讨论】:

    标签: python django


    【解决方案1】:

    默认 BASE_DIR 将从 Django 3.1 设置为 (source):

    BASE_DIR = Path(__file__).resolve().parent.parent
    

    / 与 os.path.join() 相同(pathlib 是 python 3.4 中引入的新模块)作为documented

    斜杠运算符有助于创建子路径,类似于 os.path.join()

    例如

    BASE_DIR = Path('/base')
    print(BASE_DIR / 'static')
    

    将导致 /base/static

    【讨论】:

      【解决方案2】:

      可能BASE_DIR 是一个pathlib.Path 对象。 / 是路径组件连接运算符。

      >>> from pathlib import Path
      >>> BASE_DIR = Path('/tmp')
      >>> BASE_DIR / 'foo' / 'bar'
      PosixPath('/tmp/foo/bar')
      >>> str(BASE_DIR / 'foo' / 'bar')
      '/tmp/foo/bar'
      

      【讨论】:

      猜你喜欢
      • 2016-02-02
      • 2015-04-20
      • 1970-01-01
      • 2014-07-15
      • 2016-03-12
      • 1970-01-01
      • 1970-01-01
      • 2012-03-25
      • 2013-01-04
      相关资源
      最近更新 更多