3

My app contains a large folder structure of images. In production, the images are served from a CDN. In dev, we have a small sampling of the images available on a dev server.

I'm familiar with using url_for to serve files from the /static folder:

<img src="{{ url_for('static', filename='images/logo.png') }}"/>

I want to only use the /static folder for application-ish things (like js, css and images such as the logo and button icons -- things that go with the templates)

The application's main data is a huge repo of images. That's on the CDN, not in with the source code.

I'd like to do this:

<img src="{{ url_for('image_repo', filename=viewmodel.imagename) }}"/>

And have that translate to this:

Development:

http://devbox/folder/images/blahblah.png

Production:

http://cdn.domain.com/bucket/blahblah.png

The Flask documentation talks about creating an endpoint function. I'm not doing it right because it's throwing an error. The error is not on this endpoint function, but on the url_for. It says "werkzeug.routing.BuildError" and shows me: BuildError: ('image_repo', {'filename': u'blahblah.png'}, None)

Here is my endpoint function. I know it's wrong.

@app.endpoint('image_repo')
def image_repo(filename):
    # use settings to figure out if this is dev or prod
    # then what ????
    pass
eyquem
  • 26,771
  • 7
  • 38
  • 46
101010
  • 14,866
  • 30
  • 95
  • 172

1 Answers1

1

I afraid you can't use url_for to creating links to another host (no subdomain). But you can create your own function and use it:

import urlparse

def image_repo_url_for(filename):
    if app.config['PRODUCTION']:
       return urlparse.urljoin(app.config['IMG_HOST_PROD'], filename)
    else:
       return urlparse.urljoin(app.config['IMG_HOST_DEV'], filename)

And also add it to jinja:

app.jinja_env.globals.update(image_repo_url_for=image_repo_url_for)
tbicr
  • 24,790
  • 12
  • 81
  • 106
  • This worked. You have to also register the image_repo_url_for() function with Jinja2. (I edited your answer to include that) Got it from here: http://stackoverflow.com/questions/6036082/call-a-python-function-from-jinja2 – 101010 Jun 29 '13 at 19:19
  • I updated my ansver with your. – tbicr Jun 29 '13 at 20:20