我无法弄清楚如何通过 Nginx 和 Gunicorn 为我的 Flask 网络应用程序提供静态文件。当客户端请求静态文件时,我在网上看到的所有文档都指向向静态文件夹别名添加一些路径。但是,我不确定完整路径应该是什么,因为该应用程序托管在 Heroku 上。所有对静态文件的请求都返回 404 错误。我还注意到,对存储在目录路径 /static/json/<file>.json
中的 JSON 文件的 XHR 请求成功时不返回 JSON 对象。
项目层次结构:
project/
|_ config/
|_ gunicorn.conf.py
|_ nginx.conf.erb
|_ flask_app/
|_ __init__.py
|_ static/
|_ css/
|_ js/
|_ images/
|_ json/
|_ Procfile
|_ run.py
项目/配置/gunicorn.conf.py:
def when_ready(server):
open('/tmp/app-initialized', 'w').close()
bind = 'unix:///tmp/nginx.socket'
项目/配置/nginx.conf.erb:
daemon off;
#Heroku dynos have at least 4 cores.
worker_processes <%= ENV['NGINX_WORKERS'] || 4 %>;
events {
use epoll;
accept_mutex on;
worker_connections <%= ENV['NGINX_WORKER_CONNECTIONS'] || 1024 %>;
}
http {
server_tokens off;
log_format l2met 'measure#nginx.service=$request_time request_id=$http_x_request_id';
access_log <%= ENV['NGINX_ACCESS_LOG_PATH'] || 'logs/nginx/access.log' %> l2met;
error_log <%= ENV['NGINX_ERROR_LOG_PATH'] || 'logs/nginx/error.log' %>;
include mime.types;
default_type application/octet-stream;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
#Must read the body in 5 seconds.
client_body_timeout 5;
upstream app_server {
server unix:/tmp/nginx.socket fail_timeout=0;
}
server {
listen <%= ENV["PORT"] %>;
server_name _;
keepalive_timeout 5;
# Configure NGINX to deliver static content from the specified folder
location /static {
alias /static;
}
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://app_server;
}
}
}
项目/过程文件
web: bin/start-nginx gunicorn -c config/gunicorn.conf.py 'run:create_app()'
worker: python worker.py
clock: python clock.py
例子.js
export function getData() {
$.ajax({
type: 'GET',
url: '/static/json/data.json',
async: false,
success : function(data) {
currentPageIndex = 0;
numberOfPages = data.length; // Getting undefined error here on "data"
}
});
}
最佳答案
在您给定的配置中,有(至少)两种托管静态内容的方法。我不清楚您决定使用以下两种选择中的哪一种 - 我的印象是您希望同时拥有这两种选择?
我确定您阅读了 https://flask.palletsprojects.com/en/1.1.x/tutorial/static/这说
Flask automatically adds a static view that takes a path relative to the
flaskr/static
directory and serves it.URL 与您的 flask 相同SPA后面有一个额外的
static
,参见例如Link to Flask static files with url_for或 https://flask.palletsprojects.com/en/1.1.x/quickstart/#url-building静态内容的文件位置将是您的flask-app-目录中的
/static
。另请注意How to serve static files in Flask这说
The preferred method is to use nginx or another web server to serve static files; they'll be able to do it more efficiently than Flask.
在这种情况下,Nginx docu on Serving Static Content是你的 friend :
URL 将只是
www.example.com/whateverHerokuPutsHere/static
。文件位置 可以是您在
nginx.conf
中指定的任何位置,通常会将绝对路径放在那里。免责声明:我从未使用过 heroku ,所以我不确定是否真的会有一个
whateverHerokuPutsHere
。很可能它只是example.com
,因为您在 Heroku 的 UI 上的某处进行了配置。对于我找到的文件位置 a blog Nginx as a static site server on Heroku .
关于nginx - 获取静态文件的正确路径以通过 nginx 为它们提供服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62054564/