GAE app.yaml 使用 Flask-Restless 进行路由

GAE app.yaml routing with Flask-Restless

我正在使用 AngularJS 前端 + GAE 后端(Python 和 Flask)开发一个应用程序。我在设置 app.yaml 以路由我使用 Flask-Restless 扩展创建的 API 端点时遇到了麻烦。我的 app.yaml 文件如下所示:

application: myAppID
version: 1
runtime: python27
threadsafe: true
api_version: 1

handlers:
# handler 1
- url: /favicon\.ico
  static_files: favicon.ico
  upload: favicon\.ico

# handler 2
- url: /api/.*
  script: main.app

# handler 3
- url: /test
  script: main.app

# handler 4
- url: (.*)/
  static_files: app/index.html
  upload: app #this is the frontend folder for Angular

# handler 5
- url: (.*)
  static_files: app
  upload: app #this is the frontend folder for Angular

在Angular中,路由配置如下所示:

App.config(['$stateProvider', '$locationProvider', '$urlRouterProvider', 'RouteHelpersProvider',
function ($stateProvider, $locationProvider, $urlRouterProvider, helper) {
  'use strict';

  $locationProvider.html5Mode(false);

  // default route
  $urlRouterProvider.otherwise('/app/dashboard');

  // other routes ...
}]);

main.py 文件如下所示:

from flask import Flask
import os
from werkzeug import debug
from flask import jsonify
from google.appengine.ext.webapp.util import run_wsgi_app

app = Flask('myApp')

if os.getenv('SERVER_SOFTWARE') and os.getenv('SERVER_SOFTWARE').startswith('Google App Engine/'):
    app.debug = False
else:
    app.debug = True

if app.debug:
    app.wsgi_app = debug.DebuggedApplication(app.wsgi_app, True)

@app.route('/test')
def test():
    return jsonify(test={"json": "test"})

import models

run_wsgi_app(app)

models 是包含 Flask-SQLAlchemy 模型和 Flask-Restless 端点的文件。

Angular 部分正确加载,例如这个 URL 工作正常:

但是 GAE 后端部分响应 URL 的 500 错误,如下所示:

如果我删除 handler 4handler 5,那么 BC URLs 工作正常,但 Angular 前端停止工作。

我做错了什么?

我在路上,所以用我的 phone 写东西不是那么有趣...

无论如何,我在我的应用程序中所做的是我只有一个触发烧瓶应用程序的处理程序。

在 flask 应用程序中,通常 / 路由将 return angular 网络应用程序作为静态文件。

您需要配置您的 Flask 应用程序,它会知道静态(HTML、JS 等)文件夹。

已编辑:

app.yaml 应该是这样的:

handlers:
- url: .*  # This regex directs all routes to main.app
   script: main.app

main.app 是烧瓶应用程序.. 现在让我们看看如何从路由 '/'

为 angular 应用提供服务
from flask import Flask, render_template
app = Flask(__name__, static_folder='/templates') # This sets /templates to be the folder for all JS HTML CSS files

@app.route('/')
def wellcomePage():
    return app.send_static_file('index.html')

angular 您的 app.js 文件中的路由配置:

app.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
    $routeProvider
        .when('/', {
            templateUrl: 'templates/views/home.html'
        }).... Some More Routes..

注意templateUrl:'templates/...'

请看看我的应用程序。我想这会帮助你理解我在这里想说的...

SE Hub at github

当我遇到一个该死的键盘时我会编辑这个答案:)

如果有帮助请告诉我。