python – 使用带有flask和flask-restplus的Google App Engine时出现404错误

我的根文件夹中的main.py文件如下所示.

app = Flask(__name__)

def configure_app(app):
    app.config['SERVER_NAME'] = settings.FLASK_SERVER_NAME
    app.config['SWAGGER_UI_DOC_EXPANSION'] = settings.RESTPLUS_SWAGGER_UI_DOC_EXPANSION
    app.config['RESTPLUS_VALIDATE'] = settings.RESTPLUS_VALIDATE
    app.config['RESTPLUS_MASK_SWAGGER'] = settings.RESTPLUS_MASK_SWAGGER
    app.config['ERROR_404_HELP'] = settings.RESTPLUS_ERROR_404_HELP

def initialize_app(app):
    configure_app(app)
    blueprint = Blueprint('api',__name__,url_prefix='/api')
    api.init_app(blueprint)
    api.namespaces.pop(0) #this is to remove default namespace from swagger doc
    api.add_namespace(user_namespace)
    app.register_blueprint(blueprint)

def main():
    initialize_app(app)
    app.run(debug=settings.FLASK_DEBUG)


if __name__ == "__main__":
    main()

我的app.yaml文件如下所示.

runtime: python
env: flex
entrypoint: gunicorn -b :$PORT main:app

runtime_config:
  python_version: 3

manual_scaling:
  instances: 1
resources:
  cpu: 1
  memory_gb: 0.5
  disk_size_gb: 10

以下是requirements.txt文件.

Flask==1.0.2
flask-restplus==0.11.0
gunicorn==19.9.0

我在灵活的环境中运行GAE.

我按照https://cloud.google.com/appengine/docs/flexible/python/quickstart中的步骤操作,并成功将应用程序部署到应用程序引擎.

当我转到appspot链接时,我得到404错误,gcloud日志尾部如下所示.

2018-09-09 01:49:00 default[20180909t113222]  "GET /" 404
2018-09-09 01:49:01 default[20180909t113222]  "GET /favicon.ico" 404
2018-09-09 01:49:09 default[20180909t113222]  "GET /api/" 404

我尝试寻找解决方案,但从未找到与我的方案类似的解决方案.

在此非常感谢任何帮助.

谢谢.

最佳答案
部署到App Engine时,不会调用您的主函数.相反,App Engine使用Gunicorn和您在app.yaml文件中定义的入口点.

因为main没有被调用,所以你的initialize_app函数也没有被调用,这就是添加你正在寻找的端点.

相反,您应该执行以下操作:

app = Flask(__name__)
initialize_app(app)

def configure_app(app):
    ...

def initialize_app(app):
    ... 

if __name__ == "__main__":
    # Only use this for things need to run the app locally,# will not be used when deploying to App Engine
    app.run(debug=settings.FLASK_DEBUG)

编辑:我能够使用这个最小的main.py来实现:

from flask import Flask,Blueprint
from flask_restplus import Api

app = Flask(__name__)
api = Api()
blueprint = Blueprint('api',url_prefix='/api')
api.init_app(blueprint)
app.register_blueprint(blueprint)

相关文章

Python中的函数(二) 在上一篇文章中提到了Python中函数的定...
Python中的字符串 可能大多数人在学习C语言的时候,最先接触...
Python 面向对象编程(一) 虽然Python是解释性语言,但是它...
Python面向对象编程(二) 在前面一篇文章中谈到了类的基本定...
Python中的函数(一) 接触过C语言的朋友对函数这个词肯定非...
在windows下如何快速搭建web.py开发框架 用Python进行web开发...