【发布时间】:2020-09-15 04:04:44
【问题描述】:
我无法弄清楚如何通过 Nginx 和 Gunicorn 为我的 Flask Web 应用程序提供静态文件。我在网上看到的所有文档都指向当客户端请求静态文件时添加一些静态文件夹别名的路径。但是,我不确定完整路径应该是什么,因为该应用程序托管在 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
example.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"
}
});
}
【问题讨论】:
-
它在你的本地主机上工作吗?您的静态文件存储在哪个文件夹中?
-
Heroku 将 git 根文件夹放入其文件系统上的
/app -
我更新了我的项目层次结构,静态文件存储在静态目录中。因此,如果 Herky 将根文件夹置于
/app是否意味着 Nginx 配置文件应该有location /app/flask_app/static {}而不是location /static {}? -
要回答你关于它是否在 localhost 中工作的问题,是的,但那是因为 Flask 在开发环境中的 Werkzeug 上运行,所以我无法在 Nginx 上对其进行测试。而且我无法在 localhost 上的生产环境中测试它,因为我没有浏览器可以识别的 localhost 证书,因为生产环境使用 HTTPS。
标签: nginx flask heroku static gunicorn