I am developing an app with AngularJS frontend + GAE backend (Python and Flask). I am having troubles to setting app.yaml for routing my API endpoints created with Flask-Restless extention. My app.yaml file looks like this:
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\1/index.html
upload: app #this is the frontend folder for Angular
# handler 5
- url: (.*)
static_files: app\1
upload: app #this is the frontend folder for Angular
In Angular, the routes configuration looks like this:
App.config(['$stateProvider', '$locationProvider', '$urlRouterProvider', 'RouteHelpersProvider',
function ($stateProvider, $locationProvider, $urlRouterProvider, helper) {
'use strict';
$locationProvider.html5Mode(false);
// default route
$urlRouterProvider.otherwise('/app/dashboard');
// other routes ...
}]);
The main.py file looks like this:
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 is the file that contains Flask-SQLAlchemy models and Flask-Restless endpoints.
The Angular part loads correctly, for example this URL works fine:
A) http://localhost:8080/#/app/dashboard
But the GAE backend part responses with a 500 error for URLs like these:
B) http://localhost:8080/api/person
C) http://localhost:8080/test
If I remove the handler 4 and handler 5 then B and C URLs works fine but Angular frontend stop working.
What I'm doing wrong?
Im on the go, so writing from my phone isn't that fun...
Any way, what i did in my app is that i have only one handler that triggers the flask app.
In the flask app usually the / route will return the angular web app as a static file.
You need to configure your Flask app , that it will know about the statics (HTML, JS etc.) Folder.
EDITED:
app.yaml should look like this:
handlers:
- url: .* # This regex directs all routes to main.app
script: main.app
main.app is the flask app..
now lets see how to serve the angular app from the route '/'
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 routing configuration in your app.js file:
app.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'templates/views/home.html'
}).... Some More Routes..
Note that templateUrl: 'templates/...'
Please take a look at my app. I think it will help you understand what I'm trying to say here...
SE Hub at github
Ill edit this answer when i get to a freaking keyboard :)
Let me know if this helps.
Related
I have this app engine project structure:
and the this yaml file:
but only chicken.jpg will appear in index.html and not the images inside img/cats or img/puppys.
/img intercepts the others. Put your url handlers in this order:
- url: /img/puppys
static_dir: img/puppys
- url: /img/cats
static_dir: img/cats
- url: /img
static_dir: img
Hi I have an angular 2 application which i would like to deploy to gae. So back end I am using app engine python. I am trying to do a simple post request from angular front end to app engine python. So following is my app.yaml
runtime: python27
api_version: 1
threadsafe: true
service: federation-bipedal-hominids
handlers:
- url: /.*
script: main.app
- url: (.*)/
static_files: federation-bipedal-hominids/src/app\1/index.html
upload: app
- url: (.*)
static_files: app/home\1
upload: app
main.py
import json
import webapp2
import time
# app = StaticURLParser("federation-bipedal-hominids")
def AsDict():
return {"Hello World !": "try now"}
class RestHandler(webapp2.RequestHandler):
def dispatch(self):
#time.sleep(1)
super(RestHandler, self).dispatch()
def SendJson(self, r):
self.response.headers['content-type'] = 'text/plain'
self.response.write(json.dumps(r))
class HelloWorld(RestHandler):
def post(self):
r = AsDict()
self.SendJson(r)
class QueryHandler(RestHandler):
def get(self):
r = AsDict()
self.SendJson(r)
app = webapp2.WSGIApplication([
('/HelloWorld', HelloWorld)
], debug=True)
now, how should i do it from angular front end ?
I include google's angularjs scripts but they don't seem to work with the app. If I open the html webpage directly with an internet browser it works fine.
The page is just a simple test with ng-model to see what you are typing and it doesn't print {{name}}
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
this is the app:
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
class MainHandler(webapp.RequestHandler):
def get (self, q):
if q is None:
q = 'index.html'
path = os.path.join (os.path.dirname (__file__), q)
self.response.headers ['Content-Type'] = 'text/html'
self.response.out.write (template.render (path, {}))
def main ():
application = webapp.WSGIApplication ([('/(.*html)?', MainHandler)], debug=True)
util.run_wsgi_app (application)
if __name__ == '__main__':
main ()
this is my app.yaml
application: sixth-tribute-676
version: 2
runtime: python27
api_version: 1
threadsafe: no
handlers:
- url: /(.*\.(gif|png|jpg|ico|js|css))
static_files: \1
upload: (.*\.(gif|png|jpg|ico|js|css))
- url: .*
script: main.py
The problem was that I was using template.render and {{name}} disappeared. I should serve the html without rendering it.
Long time listener, first time caller.
I'm having some frustrating, seemingly inexplicable issues with Google App Engine, Jinja2, and CSS.
My templates are working, the functionality of my app works (users, blog posts, etc.), but the CSS file shows a big, fat 404 in my Chrome debugging tools and in my Google App Engine logs. Why isn't my /stylesheets/main.css loading?
Dear internet, I'd love to hear that this is just a typo. I'm sure that I'm just an idiot.
Here's my file directory:
stylesheets
main.css
templates
base.html
blog.html
front.html
login.html
newpost.html
signup.html
welcome.html
app.yaml
blogs.py
favicon.ico
index.yaml
main.py
users.py
utilities.py
Here's my YAML file:
application: hello-udacity-5681
version: 1
runtime: python27
api_version: 1
threadsafe: yes
handlers:
- url: /favicon\.ico
static_files: favicon.ico
upload: favicon\.ico
- url: /.*
script: main.app
- url: /stylesheets
static_dir: stylesheets
libraries:
- name: webapp2
version: "2.5.2"
- name: jinja2
version: latest
Here's my main.py:
import webapp2
import os
import jinja2
from google.appengine.ext import db
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True)
class Handler(webapp2.RequestHandler):
def write(self, *a, **kw):
self.response.out.write(*a, **kw)
def render_str(self, template, **params):
t = jinja_env.get_template(template)
return t.render(params)
def render(self, template, **kw):
self.write(self.render_str(template, **kw))
class MainHandler(Handler):
def render_front(self):
self.render("base.html")
def get(self):
self.render_front()
Here's my base.html:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="/stylesheets/main.css"/>
<title>Blog</title>
</head>
<body>
Blog
</body>
</html>
I ran my main.css through http://jigsaw.w3.org/css-validator/ without any issues, so I won't bore you with that.
Why am I still getting a 404 for my /stylesheets/main.css ?
Your app.yaml handler section should be like this
handlers:
- url: /favicon\.ico
static_files: favicon.ico
upload: favicon\.ico
- url: /stylesheets
static_dir: stylesheets
- url: /.*
script: main.app
In this case, the /stylesheets pattern will match before the /.* pattern will for the appropriate paths. For more information on URL mapping and other options you can specify in app.yaml, see the app.yaml reference.
I am new to Google App Engine and I am attempting to create a simple multi-page application (index.htm, sites.htm, topics.htm). When I run the application without file name everything works great http://localhost:9080. But when I attempt to load a specific page http://localhost:9080/index.htm or http://localhost:9080/sites.htm or http://localhost:9080/topics.htm, I receive 404 error
Here's my app.yaml
application: msa
version: 1
runtime: python27
api_version: 1
threadsafe: yes
handlers:
- url: /favicon\.ico
static_files: favicon.ico
upload: favicon\.ico
- url: /static
static_dir: static
- url: .*
script: main.app
libraries:
- name: webapp2
version: "2.5.2"
My MainHandler is as below
class MainHandler(webapp2.RequestHandler):
def get(self):
path = self.request.path
temp = os.path.join(os.path.dirname(__file__),'templates/' + path)
self.response.write(temp + '<br />')
if not os.path.isfile(temp):
temp = os.path.join(os.path.dirname(__file__),'templates/index.htm')
outstr = template.render(temp, { })
self.response.out.write(outstr)
app = webapp2.WSGIApplication([
('/', MainHandler)
], debug=True)
All my files have been organized in this fashion
/
/app.yaml
/index.yaml
/main.py
/static
/static/glike.css
/templates
/templates/_base.htm
/templates/index.htm
/templates/topics.htm
/templates/sites.htm
Any guidance would be much appreciated
You have to create routes: http://webapp-improved.appspot.com/guide/routing.html#simple-routes
('/', MainHandler) will only handle: /
To handle all requests use:
app = webapp2.WSGIApplication(
[
('/.*', MainHandler),
], debug=True)