Google App Engineã§åçã«ã¤ã¡ã¼ã¸ãæä¾ãã
ã¤ãã§ã«ã
http://code.google.com/intl/ja/appengine/articles/images.html
ã¯ããã«
ç¾èã¯ä¸è¦ã«ããããè¦è´è ã¸ã®ã¢ãã¼ã«ã¨ããç¹ã§ç»åã大ããªå½¹å²ãæ¼ããã¨ããã®ã¯ä»æ¥ã®ã¦ã§ãã¢ããªã±ã¼ã·ã§ã³ã«ããã¦ãçå®ã ãGoogle App Engineã§ããã¼ã¿ã¹ãã¢ãéãã¦ãã°ããç°¡åã«ç»åãä¿åãããæä¾ãããã§ãããPythonã¤ã³ã¿ã¼ãã§ã¼ã¹ã«ã¯ãã¼ã¿ã¢ããªã³ã°APIã¨GQLãour very own query languageãå«ã¾ããããã®çãè¨äºã§ã¯ãä¾ã¨ãã¦Moview Review sample applicationã®ã³ã¼ãã使ã£ã¦ãデータストアAPIãç»åãä¿åã»æä¾ããããã«ä½¿ç¨ããæ¹æ³ã«ã¤ãã¦ã®ä¸éãã説æãããã
ãã¼ã¿ã¹ãã¢ã«ç»åãä¿å
ã¾ãã¯ããã«ããã¼ã¿ã¹ãã¢ã®ãªãã¸ã§ã¯ãã¨ãã¦ã¢ããªã±ã¼ã·ã§ã³ã«ããããã®ã ã¼ãã¼ãä¿åããããããã¯ã ã¼ãã¼ãã¢ããªã³ã°ããã¯ã©ã¹ãå®ç¾©ãããã¨ã§å®ç¾ã§ããã以ä¸ã®Movieã¯ã©ã¹ã§ã¯Movieãªãã¸ã§ã¯ããæã¤ãã¹ã¦ã®å±æ§ãå®ç¾©ããã¦ãããå®ç¾©ãããå±æ§ã®ã²ã¨ã¤ã¨ãã¦ãpictureãããããããããã ã¼ãã¼ã®jpegã¤ã¡ã¼ã¸ã®ãã¤ããªãã¼ã¿ã表ãã¦ãããç»åãé©åã«æ±ãããã«ããããã¯Blobã¨ãã¦ä¿åããªããã°ãªããããã®ããã«ã¯pictureãBlobPropertyã¨ãã¦å®£è¨ããªããã°ãããªãã
Class Movie(db.Model)
title = db.StringProperty()
picture = db.BlobProperty(default=None)
...
ããã§ã¢ãã«ãå®ç¾©ãããã®ã§ããã®ã¢ãã«ãå©ç¨ãã¦ã ã¼ãã¼ãªãã¸ã§ã¯ããä¿åãããã¨ãã§ããããªã¢ã¼ãã®ã½ã¼ã¹ããã ã¼ãã¼ãã¼ã¿ãåã£ã¦ãã¦ã¢ããªã±ã¼ã·ã§ã³ã«é£ããããã¨ãå¯è½ã ãããã«ã¯Google App Engineã®URL Fetch APIã使ã£ã¦HTTPã¾ãã¯HTTPS URLãããã¼ã¿ãåå¾ãããurlfetch.Fetch()ã¡ã½ããã使ãã°ãªã¢ã¼ãã«ããã¤ã¡ã¼ã¸ã®ãã¤ããªã³ã³ãã³ãããã§ããã§ãããåã«å¼æ°ã¨ãã¦ç»åã®URLã渡ãã¦ããã ãã ã
ãããããã§ãããããçµæã®contentå±æ§ãå¼æ°ã¨ãã¦æ¸¡ãã¦Blobãªãã¸ã§ã¯ããä½ããMovieãªãã¸ã§ã¯ãã®pictureå±æ§ã«è¨å®ãããæå¾ã«put()ã¡ã½ãããå¼ã³åºãã¦å¤æ´ããã¼ã¿ã¹ãã¢ã«ä¿åããã
ç»åã®åå¾ã¨è¡¨ç¤º
ããã§ãªãã¸ã§ã¯ããMovieãã¼ã¿ã¹ãã¢ã«ä¿åãããã®ã§ããã¼ã¿ã¹ãã¢ããåçã«åãåºãã¦ãã©ã¦ã¶ã«ç»åã¨ãã¦è¡¨ç¤ºããªãããªã¯ã¨ã¹ããã³ãã©ãä½æãããã
åãã«GETãªã¯ã¨ã¹ããå¦çããGetImageã¯ã©ã¹ãä½æããããªã¯ã¨ã¹ããã³ãã©ã¯æåã«'title'ã®å¤ãURLãã©ã¡ã¼ã¿ããæ½åºãããããã¦getMovie()ã¡ã½ãããå¼ãã§ã¿ã¤ãã«ãä¸è´ããMovieãªãã¸ã§ã¯ãããã¼ã¿ã¹ãã¢ããèªã¿è¾¼ãã
Movieãªãã¸ã§ã¯ãã®åç §ãæã«å ¥ãã°ããã®"picture"å±æ§ã«ãã¢ã¯ã»ã¹ã§ããããã©ã¦ã¶ã§ç»åãé©åã«ã¬ã³ããªã³ã°ããããã«HTTP Content-Typeãããã¼ã¯'image/jpg'ã«è¨å®ãã¦ããã
class GetImage(webapp.RequestHandler): def get(self): title = self.request.get('title') movie = getMovie(title) if (movie and movie.picture): self.response.headers['Content-Type'] = 'image/jpg' self.response.out.write(movie.picture) else: self.redirect('/static/noimage.jpg')
getMoive()ã¡ã½ããã¯ã¿ã¤ãã«ã®ä¸è´ããã ã¼ãã¼ãªãã¸ã§ã¯ããåå¾ããç°¡åãªGQLãããªãã
def getMovie(title): result = db.GqlQuery("SELECT * FROM Movie WHERE title = :1 LIMIT 1", title).fetch(1) if (len(result) > 0): return result[0] else: return None
ã¢ããªã±ã¼ã·ã§ã³ã§ã ã¼ãã¼ã®ç»åã«ç°¡åã«ã¢ã¯ã»ã¹ã§ããããã«GetImageã¯ã©ã¹ã'/image'ã¨ããURLãã¹ã«ãããããããä»åã¯GETãªã¯ã¨ã¹ããå¦çããã®ã«webappã¢ã¸ã¥ã¼ã«ãå©ç¨ãããã¨ã«ããã
apps_binding = [] ... apps_binding.append(('/image', GetImage)) application = webapp.WSGIApplication(apps_binding, debug=True) wsgiref.handlers.CGIHandler().run(application)
ããã§ãã¸ã¿ã¼ãhttp://mydomain.com/image?title=matrixã¨ããURLã«ã¢ã¯ã»ã¹ããã¨"matrix"ã ã¼ãã¼ã®ç»åããã©ã¦ã¶ã«è¿ãããã