获取静态文件的正确路径,并通过nginx提供给它们。

问题描述 投票:1回答:1

我不知道如何通过Nginx和Gunicorn为我的Flask网络应用提供静态文件。我在网上看到的所有文档都指出,当客户端请求静态文件时,需要添加一些路径到静态文件夹的别名。然而,我不确定完整的路径应该是什么,因为应用程序是在Heroku上托管的。所有对静态文件的请求都返回404错误。我还注意到,对存储在目录路径中的JSON文件的XHR请求是 /static/json/<file>.json 没有在成功时返回一个JSON对象。

项目层次结构。

project/
|_ config/
   |_ gunicorn.conf.py
   |_ nginx.conf.erb
|_ flask_app/
   |_ __init__.py
   |_ static/
      |_ css/
      |_ js/
      |_ images/
      |_ json/
|_ Procfile
|_ run.py

projectconfiggunicorn.conf.py。

def when_ready(server):
    open('/tmp/app-initialized', 'w').close()

bind = 'unix:///tmp/nginx.socket'

projectconfignginx.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;
        }
    }
}

projectProcfile

web: bin/start-nginx gunicorn -c config/gunicorn.conf.py 'run:create_app()'
worker: python worker.py
clock: python clock.py

例子.js,我有个问题,如何通过Nginx和Gunicorn为我的Flask网页应用提供静态文件。

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"
    }
  });
}
nginx flask heroku static gunicorn
1个回答
0
投票

在你给定的配置中,有(至少)两种方式来托管静态内容。我不清楚你决定采用下面两种方式中的哪一种--我的印象是,你想以某种方式两者兼得?

  1. 我相信你阅读 https:/flask.palletsprojects.comen1.1.xtutorialstatic。 其中说

    Flask会自动添加一个静态视图,该视图的路径相对于 flaskr/static 目录并为其服务。

    网址 就像你的烧瓶一样 SPA 另加 static 后面的内容,例如 用url_for链接到Flask静态文件。https:/flask.palletsprojects.comen1.1.xquickstart#url建设。

    文件位置 静态内容是 /static 在您的flask-app-目录中。

  2. 请注意 如何在Flask中服务静态文件 其中说

    首选的方法是使用nginx或其他Web服务器来服务静态文件;它们会比Flask更有效地完成这项工作。

    在这种情况下,使用 Nginx关于服务静态内容的文档。 是你的朋友。

    The 网址 只会 www.example.com/whateverHerokuPutsHere/static.

    文件位置 可以是您在 nginx.conf,通常人们会把绝对路径放在那里。

    免责声明。 我从来没有工作过 鹭鸟所以,我不知道是否真的会有一个。whateverHerokuPutsHere. 这很可能是,它只是 example.com 在Heroku的用户界面上进行配置。对于文件的位置,我发现 博客 Nginx作为Heroku上的静态网站服务器。.


-1
投票

用python代码来渲染文件

@app.route("/")
def main():
    return render_template('main.html')

例子flaskstattemplatesmain.html。

如果您使用静态图像,请使用相对路径

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport"
     content="width=device-width, initial-scale=1, user-scalable=yes">

  <link href="/static/css/style.css" rel="stylesheet">
</head>
<body>
<h1>Hello World</h1>

<img src="static/img/code_maven_128.png" />

</body>
</html>

The CSS itself is also very simple, its content is not relevant for our purposes.

examples/flask/stat/static/css/style.css

h1 { color: blue;}如何运行这个有两种简单的方法在devellent中运行这个。对于这两种方法,你都需要打开你的终端(cmd窗口,如果你是在Windows上),改变到应用程序文件(在我们的例子中是web.py)可以找到的目录。

python web.py一个更好的方法,提供了更多的控制如何运行这个是使用。

https:/code-maven.comflask-serve-static-files。

enter code here

-1
投票

我发现这个问题是由于别名路径不正确造成的,一开始很难确定,因为Heroku的根目录设置与我的本地机器不同。一开始很难确定,因为Heroku的根目录设置与我的本地机器不同。Heroku应用程序的根目录是 /app 所以我根据我的项目层次结构,把别名改成了这个。这对其他面临类似问题的人来说应该是可行的。

location /static {
   alias /app/flask_app/static;
}
© www.soinside.com 2019 - 2024. All rights reserved.