-->

Define query param in app.yaml in Google Appengine

2019-04-10 08:57发布

问题:

I would like to serve static files depending on the query parameter. More specificly I would like to serve prerendered snapshots for search engine optimalization. The pages are hosted on Google Appengine, so I'm using app.yaml to define these urls.

handlers:
# Consider anything matching a dot static content.
- url: /(.*\..*)$
  static_files: dist/\1
  upload: dist/(.*\..*)$

# Serve snapshots for seo
- url: /?_escaped_fragment_=(.*)
  static_files: dist/snapshots/\1
  upload: dist/(.*)$

# Otherwise let Angular handle it.
- url: /(.*)
  static_files: dist/index.html
  upload: dist/index.html

However, when I fetch a url with the query parameter _escaped_fragment_, the last url handler is triggered. Is it possible to define query params in urls? If so, what am I doing wrong?

回答1:

I'm happy to be proven wrong, but I'm pretty sure that query parameters aren't considered when dispatching via app.yaml.



回答2:

I had the exact same problem. It is kind of lame that App Engine hasn't added the ability to dispatch on static query parameters... Anyway.

import webapp2, urllib, logging, json, os

dp = os.path.dirname(os.path.realpath(__file__))
fp = os.path.join(dp, "resources", 'index.html')
w = open(fp, 'r').read()

class Fragment(webapp2.RequestHandler):
  def get(self, pathname):
    if '_escaped_fragment_' in self.request.arguments():
      CODE_GOES_HERE_FOR_BUILDING_YOUR_FRAGMENT_RESPONSE
    else:
      self.response.write(w)

application = webapp2.WSGIApplication(
    [('/(.*)', Fragment)],
  debug=True)

This code basically guesses whether you are dispatching on the _escaped_fragment_ query parameter and modifies the output accordingly. I have no idea how much less (if any) performant this is than being able to just leave index.html in the static_files: handlers in app.yaml.