将Flask Restful Google App Engine与Angular结合使用

时间:2019-06-20 00:29:03

标签: python angular google-app-engine google-cloud-platform

我正试图嫁给这个angular python project和这个restful flask project

Directory

- /app
    - css/app.css
    - js/app.js
    - index.html
- app.yaml
- main.py
- appengine_config.py
- vendor.py
- requirements.txt

app.yaml

application: your-application-id-here
version: 1
runtime: python37
api_version: 1
threadsafe: yes

handlers:
- url: /rest/.*
  script: main.APP

- url: /(.+)
  static_files: app/\1
  upload: app/.*

- url: /
  static_files: app/index.html
  upload: app/index.html

main.py

from flask import Flask
from flask.ext import restful


APP = Flask(__name__)
api = restful.Api(APP)


class HelloWorld(restful.Resource):
    def get(self):
        return {'hello': 'world'}


api.add_resource(HelloWorld, '/rest/query/')


@app.errorhandler(404)
def page_not_found(e):
    """Return a custom 404 error."""
    return 'Sorry, Nothing at this URL.', 404


@app.errorhandler(500)
def page_not_found(e):
    """Return a custom 500 error."""
    return 'Sorry, unexpected error: {}'.format(e), 500

app/文件夹中的所有内容都与python angular项目完全相同。

如果我从app.yaml中注释掉以下内容,则可以访问/rest/query并获得预期的输出。

- url: /(.+)
  static_files: app/\1
  upload: app/.*

- url: /
  static_files: app/index.html
  upload: app/index.html

但是,如果未将其注释掉,我将得到404的{​​{1}}。在/rest/query,我可以看到静态的/页面,上面装有角钩。由于index.html无法查询app.js,因此不会填充任何数据。

如何设置使用Angular的GAE Flask宁静项目?

2 个答案:

答案 0 :(得分:1)

我必须执行的方式是将Flask api与数据库作为Web服务和独立应用程序进行部署。

接下来,您必须添加CORS以允许您的服务与其他应用(在这种情况下是使用angular框架的前端客户端)进行通信。

然后,我部署我的angular应用程序,该应用程序将接受对您的后端Web服务的api调用。

我的项目将SQL Server和.net核心Web API用于部署到Azure的Web服务器。并将Angular应用部署到Google云。我还部署了另一个有角度的应用程序来蔚蓝。

我正在为我的Google Cloud Angle前端应用程序开发新的api和dB,以使事情更易于测试和开发。

答案 1 :(得分:0)

我不是这种解决方法的忠实拥护者,但我将路由从app.yaml移到了main.py

main.py

from flask import Flask, render_template
from flask.ext import restful


class HelloWorld(restful.Resource):
    def get(self):
        return {'hello': 'world'}


app = Flask(__name__)
api = restful.Api(app)
api.add_resource(HelloWorld, '/rest/query')


@app.route('/')
def root():
    return render_template('index.html')


@app.errorhandler(404)
def page_not_found(e):
    """Return a custom 404 error."""
    return 'Sorry, Nothing at this URL.', 404


@app.errorhandler(500)
def page_not_found(e):
    """Return a custom 500 error."""
    return 'Sorry, unexpected error: {}'.format(e), 500

app.yaml

application: application-id-here
version: 1
runtime: python37
api_version: 1
threadsafe: yes

handlers:
- url: /static
  static_dir: static

- url: /.*
  script: main.app

directory

- /static
    - css/app.css
    - js/app.js
    - partials/...
- /templates/index.html
- app.yaml
- main.py
- appengine_config.py
- vendor.py
- requirements.txt
相关问题