通过Apache服务静态文件
我刚接触mod_wsgi和通过apache来提供文件的相关内容。虽然我对flask很熟悉,但这部分我有点搞不明白。我做了一个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()
我的目录结构大概是这样的:/var/www/hello-world
/hello-world
test.py
yourflaskapp.wsgi
/static
-203.jpg
/templates
-hello.html
我的模板很简单:
<!DOCTYPE html>
<html><head><title>hi</title></head>
<body>
<img src="{{url_for('static',filename=file)}}"/>
</body></html>
而我的apache配置文件是:
<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>
不过当我打开浏览器,输入我的IP地址时,图片文件没有显示出来。我哪里做错了?有没有其他的方法我可以尝试?如果有人能推荐一些好的链接,让我能更好地理解flask+mod_wsgi+apache2的工作方式,那就太好了。
1 个回答
7
在给静态文件设置子网址的时候,通常保持最后有一个斜杠是个好主意。也就是说,不要这样:
Alias /static/ /var/www/hello-world/static
而是应该这样:
Alias /static /var/www/hello-world/static