通过 apache 提供静态文件

Aar*_*shi 7 python static mod-wsgi apache2 flask

我是整个 mod_wsgi 的新手,并通过 apache 提供文件。我对烧瓶真的很满意,但这是我无法理解的。我做了hello-world程序,成功显示hello world!现在我想显示一个图像文件。所以我将我的 hello-world.py 更新为:

from flask import *
yourflaskapp = Flask(__name__)

@yourflaskapp.route("/")
def hello():
    file="203.jpg"
    return render_template("hello.html",file=file)
#   return"HEY"
if __name__ == "__main__":
    yourflaskapp.run()
Run Code Online (Sandbox Code Playgroud)

我的目录结构类似于:/var/www/hello-world

/hello-world
    test.py
    yourflaskapp.wsgi
    /static
        -203.jpg
    /templates
        -hello.html
Run Code Online (Sandbox Code Playgroud)

我的模板很简单:

<!DOCTYPE html>
<html><head><title>hi</title></head>
<body>
<img src="{{url_for('static',filename=file)}}"/>
</body></html>
Run Code Online (Sandbox Code Playgroud)

我的 apache conf 文件是:

<VirtualHost *:80>
     WSGIDaemonProcess yourflaskapp
     WSGIScriptAlias / /var/www/hello-world/yourflaskapp.wsgi
     Alias /static/ /var/www/hello-world/static
     Alias /templates/ /var/www/hello-world/templates
     <Directory /var/www/hello-world>
            WSGIProcessGroup yourflaskapp
        WSGIApplicationGroup %{GLOBAL}
        Order deny,allow
        Allow from all
     </Directory>
        <Directory /var/www/hello-world/static>
            Order allow,deny
            Allow from all
        </Directory>
        <Directory /var/www/hello-world/templates>
            Order allow,deny
            Allow from all
        </Directory>
     ErrorLog ${APACHE_LOG_DIR}/error.log
     LogLevel warn
     CustomLog ${APACHE_LOG_DIR}/access.log combined
 </VirtualHost>
Run Code Online (Sandbox Code Playgroud)

虽然当我打开浏览器并转到我的 ip 时,它没有显示图像文件。我究竟做错了什么?我应该遵循其他任何方法吗?如果有人可以推荐任何好的链接,我可以从中了解使用flask+mod_wsgi+apache2

Gra*_*ton 7

在子 URL 上安装静态文件时,平衡尾部斜杠通常总是一个好主意。所以而不是:

Alias /static/ /var/www/hello-world/static
Run Code Online (Sandbox Code Playgroud)

使用:

Alias /static /var/www/hello-world/static
Run Code Online (Sandbox Code Playgroud)

  • 因为 Apache 将从路径中删除与 LHS 匹配的内容,并将结果附加到 RHS。因此,如果有'/static/foo',在剥离'/static/'后,如果得到'foo',当添加到RHS时,会尝试打开'/var/www/hello-world/staticfoo',这是'不正确,因为斜杠已被删除。我不记得它发生的确切场景,也不记得它是否与特定的 Apache 版本相关,因此只是建议您进行匹配以避免出现问题。 (4认同)