简体   繁体   English

从 Google Cloud Storage Bucket 提供静态文件(用于 GCE 上托管的 Django 应用)

[英]Serve Static files from Google Cloud Storage Bucket (for Django App hosted on GCE)

I'm trying to serve the static Files for my django App from Cloud Storage Bucket but don't know the exact process.我正在尝试从 Cloud Storage Bucket 为我的 django 应用程序提供静态文件,但不知道确切的过程。 Can someone please suggest a proper way to do so ?有人可以建议一个正确的方法吗?

Steps I did:我做的步骤:

  1. Uploaded all the static files on Google Cloud Storage Bucket( www.example.com ) using gsutil command.使用 gsutil 命令上传 Google Cloud Storage Bucket ( www.example.com ) 上的所有静态文件。
  2. Edited /etc/apache2/sites-available/default-ssl.conf File.编辑/etc/apache2/sites-available/default-ssl.conf文件。

File Content:文件内容:

<VirtualHost *:443>
        ServerName example.com
        ServerAdmin admin@example.com

 #       Alias /static /opt/projects/example-google/example_static
        Alias /static https://storage.googleapis.com/www.example.com/static
        <Directory /opt/projects/example-google/example_static>
           Require all granted
        </Directory>

        <Directory /opt/projects/example-google/example/example>
            <Files wsgi.py>
                Require all granted
            </Files>
        </Directory>

        WSGIDaemonProcess example python-path=/opt/projects/example-google/example:/opt/projects/example-google/venv/lib/python2.7/site-packages
        WSGIProcessGroup example
WSGIApplicationGroup %{GLOBAL}
        WSGIScriptAlias / /opt/projects/example-google/example/example/wsgi.py

        SSLEngine on
        SSLCertificateFile  /etc/apache2/ssl/example.com.crt
        SSLCertificateKeyFile /etc/apache2/ssl/example.com.key
        SSLCertificateChainFile /etc/apache2/ssl/intermediate.crt
</VirtualHost>

settings.py File: settings.py 文件:

# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
# STATIC_URL = 'https://storage.googleapis.com/www.example.com/static/'
STATIC_ROOT = os.path.join(BASE_DIR, '../example_static')

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, '../example_media')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), MEDIA_ROOT,)

Any suggestion on what all additional changes are required for this task ?有关此任务需要进行哪些所有其他更改的任何建议?

Thanks,谢谢,

Main references:主要参考资料:

Prerequisite steps先决条件步骤

  1. Go to GCP: Cloud Storage (GCS) and click on CREATE BUCKET (fill-up as needed)转到 GCP:Cloud Storage (GCS) 并单击 CREATE BUCKET(根据需要填写)

  2. Once created, you can make it public if you want it to act like a CDN of your website (storage of your static files such as css, images, videos, etc.)创建后,如果您希望它像您网站的 CDN(存储您的静态文件,如 css、图像、视频等),您可以将其公开

    • Go to your newly created bucket转到您新创建的存储桶
    • Go to Permissions and then Click Add members转到权限,然后单击添加成员
    • Add a new member "allUsers" with role "Cloud Storage - Storage Object Viewer"添加角色为“Cloud Storage - Storage Object Viewer”的新成员“allUsers”
    • Reference: https://cloud.google.com/storage/docs/quickstart-console参考: https ://cloud.google.com/storage/docs/quickstart-console


Method 1 (easier and faster, but requires constant manual copying of files to the GCS)方法 1(更简单、更快,但需要不断手动将文件复制到 GCS)

  1. Configure your Django's static file settings in your settings.py在 settings.py 中配置 Django 的静态文件设置
# Tell Django about the different locations to where the static files used by the project can be found
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'templates'),
    os.path.join(BASE_DIR, "yourapp1", "templates"),
    os.path.join(BASE_DIR, "yourapp2", "static"),
    os.path.join(BASE_DIR, "watever"),
    "/home/me/Music/TaylorSwift/",
    "/home/me/Videos/notNsfw/",
]

# If the command "collectstatic" is invoked, tell Django where to place all the collected static
# files from all the directories included in STATICFILES_DIRS. Be aware that configuring it with a
# path outside your /home/me means that you need to have permissions to write to that folder later
# on when you invoke "collectstatic", so you might need to login as root first or run it as sudo.
STATIC_ROOT = "/var/www/mywebsite/"

# Tell Django the base url to access the static files. Think of this as the "prefix" of the URL
# to where your static files are. Note that if you browse through your bucket and happen to see a
# URL such as "https://storage.cloud.google.com/<your_bucket_name>/someFileYouHaveUploaded", such
# URL requires that whoever accesses it should be currently logged-in with their Google accounts. If
# you want your static files to be publicly accessible by anyone whether they are logged-in or not,
# use the link "https://storage.googleapis.com/<your_bucket_name>/someFileYouHaveUploaded" instead.
STATIC_URL = "https://storage.googleapis.com/<your_bucket_name>/"

# References:
# https://docs.djangoproject.com/en/3.0/howto/static-files/
# https://docs.djangoproject.com/en/3.0/howto/static-files/deployment/
# https://docs.djangoproject.com/en/3.0/ref/settings/

  1. If you have HTML files or CSS files that access other static files, make sure that they reference those other static files with this updated STATIC_URL setting.如果您有访问其他静态文件的 HTML 文件或 CSS 文件,请确保它们使用此更新的 STATIC_URL 设置引用这些其他静态文件。

In your home.html在你的 home.html

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'home/css/home.css' %}">

Then in your home.css file然后在你的 home.css 文件中

background-image: url("../assets/img/myHandsomeImage.jpg");

The home.css link now would translate to: home.css 链接现在将转换为:

https://storage.googleapis.com/[your_bucket_name]/home/css/home.css https://storage.googleapis.com/[your_bucket_name]/home/css/home.css

While the myHandsomeImage.jpg would be:而 myHandsomeImage.jpg 将是:

https://storage.googleapis.com/[your_bucket_name]/home/assets/img/myHandsomeImage.jpg https://storage.googleapis.com/[your_bucket_name]/home/assets/img/myHandsomeImage.jpg

Of course if you wish, you could just put the absolute path (complete URL), but such configuration would always require you to update the used URLs manually, like if you switched to development mode and wanted to just access the static files locally instead of from GCS.当然,如果你愿意,你可以只放绝对路径(完整的 URL),但这样的配置总是需要你手动更新使用的 URL,就像你切换到开发模式并只想在本地访问静态文件而不是来自 GCS。

  1. Run below.下面跑。 This would copy all files from each directory in STATICFILES_DIRS to STATIC_ROOT directory.这会将所有文件从 STATICFILES_DIRS 中的每个目录复制到 STATIC_ROOT 目录。
python3 manage.py collectstatic

# or if your STATIC_ROOT folder requires permissions to write to it then:
# sudo python3 manage.py collectstatic
  1. Go to the STATIC_ROOT folder and upload its contents to GCS.转到 STATIC_ROOT 文件夹并将其内容上传到 GCS。 Either upload them manually through the GCS GUI Console or through the Google provided tool "gsutil" along with rsync通过 GCS GUI 控制台或通过 Google 提供的工具“gsutil”和 rsync 手动上传它们

  2. Now, your GCS bucket already contains your static files, with your Django project configured to directly access those files through the configured STATIC_URL.现在,您的 GCS 存储桶已包含您的静态文件,您的 Django 项目已配置为通过配置的 STATIC_URL 直接访问这些文件。


Method 2 (longer, but do not require manual copying after)方法2(更长,但之后不需要手动复制)

  1. [OPTIONAL STEP] Prepare your python virtual environment [可选步骤] 准备你的 python 虚拟环境
python3 -m venv path/to/the/target/location/for/the/virtual/environment
source path/to/the/target/location/for/the/virtual/environment/bin/activate
  1. Install the necessary packages to be able to access and store directly to your GCS安装必要的软件包,以便能够直接访问和存储到您的 GCS
pip3 install django-storages # https://pypi.org/project/django-storages/
pip3 install google-cloud-storage # https://pypi.org/project/google-cloud-storage/
  1. [MANDATORY STEP if you are on a computer outside the Google Infrastructure] Go to GCP: IAM, Service Accounts, and click on CREATE SERVICE ACCOUNT [如果您使用的是 Google 基础架构之外的计算机,则必须执行的步骤] 转到 GCP:IAM,服务帐户,然后点击创建服务帐户

    • Name: SomeName姓名:某名
    • ID / email: somename身份证/电子邮件:somename
    • Role: Project - Owner角色:项目 - 所有者
    • CREATE KEY, select JSON创建密钥,选择 JSON
    • Store the downloaded JSON file.存储下载的 JSON 文件。 This generated json key would be used later for authentication purposes once we start accessing and storing to the GCS一旦我们开始访问并存储到 GCS,这个生成的 json 密钥将在以后用于身份验证
    • Reference: https://cloud.google.com/docs/authentication/getting-started参考: https ://cloud.google.com/docs/authentication/getting-started
  2. Configure your Django's static file settings in your settings.py在 settings.py 中配置 Django 的静态文件设置

STATICFILES_DIRS = ['same_values_as_in_method_1_above']
DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage'
GS_BUCKET_NAME = 'your_bucket_name'
STATICFILES_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage'
STATIC_URL = 'https://storage.googleapis.com/<your_bucket_name>/'
from google.oauth2 import service_account
GS_CREDENTIALS = service_account.Credentials.from_service_account_file(
    'path/to/the/downloaded/json/key/credentials.json' # see step 3
)

# There are 2 ways to authenticate, you could either do 1 of the following
# 1. Define the variable GS_CREDENTIALS in the settings.py (as done above), or just
# 2. write the command "export GOOGLE_APPLICATION_CREDENTIALS='path/to/credentials.json'" in the shell where you would run the "collectstatic" command
  1. Run below.下面跑。 This would copy all files from each directory in STATICFILES_DIRS directly to your GCS bucket.这会将所有文件从 STATICFILES_DIRS 中的每个目录直接复制到您的 GCS 存储桶。 This might take a while.这可能需要一段时间。
python3 manage.py collectstatic
  1. Now, your GCS bucket already contains your static files, with your Django project configured to directly access those files through the configured STATIC_URL.现在,您的 GCS 存储桶已包含您的静态文件,您的 Django 项目已配置为通过配置的 STATIC_URL 直接访问这些文件。

Basically you need to:基本上你需要:

  1. create cloud storage bucket and set it to public readable.创建云存储桶并将其设置为公共可读。
  2. collect static file local收集本地静态文件
  3. copy file to cloud storage将文件复制到云存储
  4. set STATIC_URL设置 STATIC_URL

Check the step 1-4 https://cloud.google.com/python/django/container-engine#deploy_the_app_to_container_engine检查步骤 1-4 https://cloud.google.com/python/django/container-engine#deploy_the_app_to_container_engine

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从 GOOGLE CLOUD STORAGE BUCKET 下载多个文件 - Download multiple files from GOOGLE CLOUD STORAGE BUCKET 使用 Python API 从 Google Cloud Datalab 上传文件到 Google Cloud Storage Bucket - Upload files to Google Cloud Storage Bucket from Google Cloud Datalab using Python API 用于从Google Cloud Storage渲染静态图像的Django设置 - Django Settings for Rendering static images from Google Cloud storage 如何将 Google Cloud Storage 中的文件从一个存储桶移动到另一个存储桶 Python - How to move files in Google Cloud Storage from one bucket to another bucket by Python 从 Google App Engine 修改 Google Cloud Storage 中的文件 - Modifying files in Google Cloud Storage from Google App Engine Django 静态 - 谷歌云存储 - CDN - Django Static - Google Cloud Storage - CDN 从Kubernetes窗格将大文件上传到Google Storage GCE - Uploading large files to Google Storage GCE from a Kubernetes pod 如何在谷歌应用引擎上提供静态文件 - how to serve static files on google app engine Google Cloud Function:访问 Google Storage 存储桶中的文件夹并处理其中的文件 - Google Cloud Function: Access folders in a Google Storage bucket and process files from them Django直接从外部存储服务文件 - Django Serve Files From External Storage Directly
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM