[英]How to deploy a Flask app to Google Cloud (App Engine) with an application factory, and how to write the app.yaml file?
我在這里發現了一個類似的問題,但該解決方案對我不起作用。
我按照官方教程編寫了一個 Flask 應用程序。 我正在嘗試使用 Google App Engine 部署它。 我用過藍圖。 我的應用程序的目錄結構如下所示:
app
│ .gcloudignore
│ app.yaml
│ main.py
│ requirements.txt
│ __init__.py
│
├───googleutils
│ │ utils.py
│
├───home
│ │ home.py
│ │
│ ├───static
│ ├───templates
│ │ home.html
│
├───models
│ │ Message.py
│ │ User.py
│
├───profile
│ │ profile.py
│ │
│ ├───static
│ ├───templates
│ │ edit_message.html
│ │ profile.html
│
├───sessions
│ │ sessions.py
│ │
│ ├───templates
│ │ login.html
│ │ logout.html
│ │ register.html
│
├───static
│ style.css
│
├───templates
│ layout.html
│ wrapper.html
在我的應用程序目錄中,我有我的app.yaml
和requirements.txt
。 我在我的 venv 中使用了pip freeze
並將它吐出的所有內容都扔到了requirements.txt
中。
當前的 Flask 教程指導您使用flask run
通過命令行啟動您的應用程序。 因此,我的應用程序從__init__.py
開始:
from flask import Flask
def create_app():
app = Flask(__name__, instance_relative_config=True)
# Application imports
from .home import home
from .sessions import sessions
from .profile import profile
# Blueprints
app.register_blueprint(home.home_bp)
app.register_blueprint(sessions.sessions_bp)
app.register_blueprint(profile.profile_bp)
return app
但是,正如我在上面鏈接的問題中所述, gcloud 會查找main.py
,因此我將其添加到我的根目錄中:
from app import create_app
app = create_app()
目前我只是想加載我的索引,它在home.py
中定義:
@home_bp.route('/', methods=['GET', 'POST'])
def home():
...
這是我的 app.yaml:
runtime: python39
entrypoint: gunicorn "app:create_app()"
handlers:
- url: /static
static_dir: static
- url: /.*
script: auto
說實話,我不知道如何編寫這個文件,尤其是對於帶有變量的目錄,例如在profile.py
中定義的這個:
@profile_bp.route('/profile/<string:user_id>', methods=['GET', 'POST'])
def profile(user_id):
...
當我運行gcloud app deploy
時,當我在瀏覽器中查看我的站點時收到 500 服務器錯誤,“服務器遇到錯誤,無法完成您的請求。”。
我究竟做錯了什么?
嗯,我想通了。 我的目錄結構錯誤。 它應該是:
│ app.yaml
│ main.py
│ requirements.txt
├───app
│ │ __init__.py
│ └
其中app.yaml
僅包含:
runtime: python39
handlers:
- url: /.*
script: auto
這會導致 GCloud 自動查找包含以下內容的main.py
文件:
from app import create_app
app = create_app()
整個 webapp 都是這樣工作的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.