Le repo des sources pour le site web des JM2L
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

592 lines
24 KiB

  1. # -*- coding: utf8 -*-
  2. from pyramid.view import view_config, view_defaults
  3. from pyramid.response import Response
  4. from pyramid.exceptions import NotFound
  5. from pyramid.httpexceptions import HTTPNotFound, HTTPBadRequest
  6. from PIL import Image
  7. import re, os, shutil
  8. from os import path
  9. import mimetypes
  10. import magic
  11. import subprocess
  12. import cStringIO as StringIO
  13. # Database access imports
  14. from .models import User, Place, Tiers, Event, SallePhy
  15. from .blenderthumbnailer import blend_extract_thumb, write_png
  16. from jm2l.const import CurrentYear
  17. from slugify import slugify
  18. MIN_FILE_SIZE = 1 # bytes
  19. MAX_FILE_SIZE = 500000000 # bytes
  20. IMAGE_TYPES = re.compile('image/(gif|p?jpeg|(x-)?png)')
  21. ACCEPTED_MIMES = ['application/pdf',
  22. 'application/vnd.oasis.opendocument.text',
  23. 'application/vnd.oasis.opendocument.text-template',
  24. 'application/vnd.oasis.opendocument.graphics',
  25. 'application/vnd.oasis.opendocument.graphics-template',
  26. 'application/vnd.oasis.opendocument.presentation',
  27. 'application/vnd.oasis.opendocument.presentation-template',
  28. 'application/vnd.oasis.opendocument.spreadsheet',
  29. 'application/vnd.oasis.opendocument.spreadsheet-template',
  30. 'image/svg+xml',
  31. 'application/x-blender'
  32. ]
  33. ACCEPT_FILE_TYPES = IMAGE_TYPES
  34. THUMBNAIL_SIZE = 80
  35. EXPIRATION_TIME = 300 # seconds
  36. IMAGEPATH = [ 'images' ]
  37. DOCPATH = [ 'document' ]
  38. THUMBNAILPATH = [ 'images', 'thumbnails' ]
  39. # change the following to POST if DELETE isn't supported by the webserver
  40. DELETEMETHOD="DELETE"
  41. mimetypes.init()
  42. class MediaPath():
  43. def get_all(self, media_table, linked_id, MediaType=None):
  44. filelist = list()
  45. curpath = self.get_mediapath(media_table, linked_id, None)
  46. thumbpath = os.path.join( curpath, 'thumbnails')
  47. if not os.path.isdir(curpath) or not os.path.isdir(thumbpath):
  48. return list()
  49. for f in os.listdir(curpath):
  50. filename, ext = os.path.splitext( f )
  51. if os.path.isdir(os.path.join(curpath,f)):
  52. continue
  53. if f.endswith('.type'):
  54. continue
  55. if f:
  56. ress_url = '/image/%s/%d/%s' % (media_table, linked_id, f.replace(" ", "%20"))
  57. thumb_url = '/image/%s/%d/thumbnails/%s' % (media_table, linked_id, f.replace(" ","%20"))
  58. if MediaType is None:
  59. filelist.append((ress_url, thumb_url))
  60. elif MediaType=='Image' and len( os.path.splitext(filename)[1] )==0:
  61. filelist.append((ress_url, thumb_url))
  62. elif MediaType=='Other' and len( os.path.splitext(filename)[1] ):
  63. filelist.append((ress_url, thumb_url))
  64. return filelist
  65. def get_list(self, media_table, linked_id, MediaType=None):
  66. filelist = list()
  67. curpath = self.get_mediapath(media_table, linked_id, None)
  68. if not os.path.isdir(curpath):
  69. return list()
  70. for f in os.listdir(curpath):
  71. if os.path.isdir(os.path.join(curpath,f)):
  72. continue
  73. if f.endswith('.type'):
  74. continue
  75. if f:
  76. filename, ext = os.path.splitext( f )
  77. tmpurl = '/image/%s/%d/%s' % (media_table, linked_id, f.replace(" ","%20"))
  78. if MediaType is None:
  79. filelist.append(tmpurl)
  80. elif MediaType=='Image' and ext.lower() in ['.gif','.jpg','.png','.svg','.jpeg']:
  81. filelist.append(tmpurl)
  82. elif MediaType=='Other' and ext.lower() not in ['.gif','.jpg','.png','.svg','.jpeg']:
  83. filelist.append(tmpurl)
  84. return filelist
  85. def get_thumb(self, media_table, linked_id, MediaType=None):
  86. filelist = list()
  87. curpath = self.get_mediapath(media_table, linked_id, None)
  88. curpath = os.path.join( curpath, 'thumbnails')
  89. if not os.path.isdir(curpath):
  90. return list()
  91. for f in os.listdir(curpath):
  92. filename, ext = os.path.splitext( f )
  93. if os.path.isdir(os.path.join(curpath,f)):
  94. continue
  95. if f.endswith('.type'):
  96. continue
  97. if f:
  98. tmpurl = '/image/%s/%d/thumbnails/%s' % (media_table, linked_id, f.replace(" ","%20"))
  99. if MediaType is None:
  100. filelist.append(tmpurl)
  101. elif MediaType=='Image' and len( os.path.splitext(filename)[1] )==0:
  102. filelist.append(tmpurl)
  103. elif MediaType=='Other' and len( os.path.splitext(filename)[1] ):
  104. filelist.append(tmpurl)
  105. return filelist
  106. def move_mediapath(self, media_table, from_id, to_id):
  107. """
  108. Move target media folder to follow database
  109. :param media_table: type of media
  110. :param from_id: source
  111. :param to_id: destination
  112. :return: Error if any
  113. """
  114. if media_table in ['tiers', 'place', 'salle', 'users']:
  115. src = IMAGEPATH + [ media_table, from_id ]
  116. dst = IMAGEPATH + [ media_table, to_id ]
  117. else:
  118. raise RuntimeError("Sorry, Media '%s' not supported yet for move." % media_table)
  119. src_path = os.path.join('jm2l/upload', *src)
  120. dst_path = os.path.join('jm2l/upload', *dst)
  121. if not os.path.isdir(src_path):
  122. # Nothing to do ...
  123. return False
  124. if os.path.isdir(dst_path):
  125. raise RuntimeError('Destination path already exist')
  126. shutil.move(src_path, dst_path)
  127. return True
  128. def get_mediapath(self, media_table, linked_id, name):
  129. """
  130. :param media_table: type of media
  131. :param linked_id: id of media
  132. :param name: filename
  133. :return: full relative path on server side
  134. """
  135. linked_id = str(linked_id)
  136. if media_table in ['tiers', 'place', 'salle']:
  137. # Retrieve Slug
  138. if media_table=='tiers':
  139. slug = Tiers.by_id(linked_id).slug
  140. if media_table=='place':
  141. slug = Place.by_id(linked_id).slug or slugify(Place.by_id(linked_id).name)
  142. if media_table=='salle':
  143. slug = SallePhy.by_id(linked_id).slug
  144. p = IMAGEPATH + [ media_table, slug ]
  145. elif media_table=='presse':
  146. # Use Year in linked_id
  147. p = IMAGEPATH + [ media_table, linked_id ]
  148. elif media_table=='tasks':
  149. # Use Current Year
  150. p = IMAGEPATH + [ str(CurrentYear), media_table, linked_id ]
  151. elif media_table=='poles':
  152. # Use Current Year
  153. p = IMAGEPATH + [ str(CurrentYear), media_table, linked_id ]
  154. elif media_table in ['RIB', 'Justif']:
  155. slug = User.by_id(linked_id).slug
  156. p = IMAGEPATH + ['users', slug , media_table ]
  157. elif media_table in ['users', 'badge']:
  158. user = User.by_id(linked_id)
  159. if not user:
  160. raise HTTPNotFound()
  161. else:
  162. slug = user.slug
  163. p = IMAGEPATH + [media_table, slug ]
  164. elif media_table=='event':
  165. ev = Event.by_id(linked_id)
  166. slug = ev.slug
  167. year = ev.for_year
  168. p = IMAGEPATH + ['event', str(year), slug ]
  169. if name:
  170. p += [ name ]
  171. TargetPath = os.path.join('jm2l/upload', *p)
  172. if not os.path.isdir(os.path.dirname(TargetPath)):
  173. try:
  174. os.makedirs(os.path.dirname(TargetPath))
  175. except OSError, e:
  176. if e.errno != 17:
  177. raise e
  178. return os.path.join('jm2l/upload', *p)
  179. def ExtMimeIcon(self, mime):
  180. if mime=='application/pdf':
  181. return "/img/PDF.png"
  182. def check_blend_file(self, fileobj):
  183. head = fileobj.read(12)
  184. fileobj.seek(0)
  185. if head[:2] == b'\x1f\x8b': # gzip magic
  186. import zlib
  187. head = zlib.decompress(fileobj.read(), 31)[:12]
  188. fileobj.seek(0)
  189. if head.startswith(b'BLENDER'):
  190. return True
  191. def get_mimetype_from_file(self, fileobj):
  192. mimetype = magic.from_buffer(fileobj.read(1024), mime=True)
  193. fileobj.seek(0)
  194. # Check if the binary file is a blender file
  195. if ( mimetype == "application/octet-stream" or mimetype == "application/x-gzip" ) and self.check_blend_file(fileobj):
  196. return "application/x-blender", True
  197. else:
  198. return mimetype, False
  199. def get_mimetype(self, name):
  200. """ This function return the mime-type based on .type file """
  201. try:
  202. with open(self.mediapath(name) + '.type', 'r', 16) as f:
  203. mime = f.read()
  204. return mime
  205. except IOError:
  206. return None
  207. @view_defaults(route_name='media_upload')
  208. class MediaUpload(MediaPath):
  209. def __init__(self, request):
  210. self.request = request
  211. self.media_table = self.request.matchdict.get('media_table')
  212. self.display_only = False
  213. if self.media_table.startswith('_'):
  214. self.display_only = True
  215. self.media_table = self.media_table[1:]
  216. self.linked_id = self.request.matchdict.get('uid')
  217. if not self.linked_id.isdigit():
  218. raise HTTPBadRequest('Wrong Parameter')
  219. request.response.headers['Access-Control-Allow-Origin'] = '*'
  220. request.response.headers['Access-Control-Allow-Methods'] = 'OPTIONS, HEAD, GET, POST, PUT, DELETE'
  221. def mediapath(self, name):
  222. return self.get_mediapath(self.media_table, self.linked_id, name)
  223. def validate(self, result, filecontent):
  224. """ Do some basic check to the uploaded file before to accept it """
  225. # Try to determine mime type from content uploaded
  226. found_mime = magic.from_buffer(filecontent.read(1024), mime=True)
  227. filecontent.seek(0)
  228. # Do a special statement for specific detected mime type
  229. if found_mime in ["application/octet-stream", "application/x-gzip"]:
  230. # Lets see if it's a bender file
  231. if self.check_blend_file(filecontent):
  232. found_mime = "application/x-blender"
  233. # MonKey Patch of content type
  234. result['type'] = found_mime
  235. # Reject mime type that don't match
  236. if found_mime!=result['type']:
  237. result['error'] = 'L\'extension du fichier ne correspond pas à son contenu - '
  238. result['error'] += "( %s vs %s )" % (found_mime, result['type'])
  239. return False
  240. # Accept images and mime types listed
  241. if not found_mime in ACCEPTED_MIMES:
  242. if not (IMAGE_TYPES.match(found_mime)):
  243. result['error'] = 'Ce type fichier n\'est malheureusement pas supporté. '
  244. return False
  245. if result['size'] < MIN_FILE_SIZE:
  246. result['error'] = 'le fichier est trop petit'
  247. elif result['size'] > MAX_FILE_SIZE:
  248. result['error'] = 'le fichier est trop voluminueux'
  249. #elif not ACCEPT_FILE_TYPES.match(file['type']):
  250. # file['error'] = u'les type de fichiers acceptés sont png, jpg et gif'
  251. else:
  252. return True
  253. return False
  254. def get_file_size(self, fileobj):
  255. fileobj.seek(0, 2) # Seek to the end of the file
  256. size = fileobj.tell() # Get the position of EOF
  257. fileobj.seek(0) # Reset the file position to the beginning
  258. return size
  259. def thumbnailurl(self,name):
  260. return self.request.route_url('media_view',name='thumbnails',
  261. media_table=self.media_table,
  262. uid=self.linked_id) + '/' + name
  263. def thumbnailpath(self,name):
  264. origin = self.mediapath(name)
  265. TargetPath = os.path.join( os.path.dirname(origin), 'thumbnails', name)
  266. if not os.path.isdir(os.path.dirname(TargetPath)):
  267. os.makedirs(os.path.dirname(TargetPath))
  268. return TargetPath
  269. def createthumbnail(self, filename):
  270. image = Image.open( self.mediapath(filename) )
  271. image.thumbnail((THUMBNAIL_SIZE, THUMBNAIL_SIZE), Image.ANTIALIAS)
  272. timage = Image.new('RGBA', (THUMBNAIL_SIZE, THUMBNAIL_SIZE), (255, 255, 255, 0))
  273. timage.paste(
  274. image,
  275. ((THUMBNAIL_SIZE - image.size[0]) / 2, (THUMBNAIL_SIZE - image.size[1]) / 2))
  276. TargetFileName = self.thumbnailpath(filename)
  277. timage.save( TargetFileName )
  278. return self.thumbnailurl( os.path.basename(TargetFileName) )
  279. def pdfthumbnail(self, filename):
  280. TargetFileName = self.thumbnailpath(filename)
  281. Command = ["convert","./%s[0]" % self.mediapath(filename),"./%s_.jpg" % TargetFileName]
  282. Result = subprocess.call(Command)
  283. if Result==0:
  284. image = Image.open( TargetFileName+"_.jpg" )
  285. pdf_indicator = Image.open( "jm2l/static/img/PDF_Thumb_Stamp.png" )
  286. image.thumbnail((THUMBNAIL_SIZE, THUMBNAIL_SIZE), Image.ANTIALIAS)
  287. timage = Image.new('RGBA', (THUMBNAIL_SIZE, THUMBNAIL_SIZE), (255, 255, 255, 0))
  288. # Add thumbnail
  289. timage.paste(
  290. image,
  291. ((THUMBNAIL_SIZE - image.size[0]) / 2, (THUMBNAIL_SIZE - image.size[1]) / 2))
  292. # Stamp with PDF file type
  293. timage.paste(
  294. pdf_indicator,
  295. (timage.size[0]-30, timage.size[1]-30),
  296. pdf_indicator,
  297. )
  298. timage.convert('RGB').save( TargetFileName+".jpg", 'JPEG')
  299. os.unlink(TargetFileName+"_.jpg")
  300. return self.thumbnailurl( os.path.basename(TargetFileName+".jpg") )
  301. return self.ExtMimeIcon('application/pdf')
  302. def svgthumbnail(self, filename):
  303. TargetFileName = self.thumbnailpath(filename)
  304. Command = ["convert","./%s[0]" % self.mediapath(filename),"./%s_.jpg" % TargetFileName]
  305. Result = subprocess.call(Command)
  306. if Result==0:
  307. image = Image.open( TargetFileName+"_.jpg" )
  308. pdf_indicator = Image.open( "jm2l/static/img/svg-icon.png" )
  309. image.thumbnail((THUMBNAIL_SIZE, THUMBNAIL_SIZE), Image.ANTIALIAS)
  310. timage = Image.new('RGBA', (THUMBNAIL_SIZE, THUMBNAIL_SIZE), (255, 255, 255, 0))
  311. # Add thumbnail
  312. timage.paste(
  313. image,
  314. ((THUMBNAIL_SIZE - image.size[0]) / 2, (THUMBNAIL_SIZE - image.size[1]) / 2))
  315. # Stamp with PDF file type
  316. timage.paste(
  317. pdf_indicator,
  318. (timage.size[0]-30, timage.size[1]-30),
  319. pdf_indicator,
  320. )
  321. timage.convert('RGB').save( TargetFileName+".jpg", 'JPEG')
  322. os.unlink(TargetFileName+"_.jpg")
  323. return self.thumbnailurl( os.path.basename(TargetFileName+".jpg") )
  324. return self.ExtMimeIcon('image/svg+xml')
  325. def docthumbnail(self, filename):
  326. TargetFileName = self.thumbnailpath(filename)
  327. # let's take the thumbnail generated inside the document
  328. Command = ["unzip", "-p", self.mediapath(filename), "Thumbnails/thumbnail.png"]
  329. ThumbBytes = subprocess.check_output(Command)
  330. image = Image.open( StringIO.StringIO(ThumbBytes) )
  331. image.thumbnail((THUMBNAIL_SIZE, THUMBNAIL_SIZE), Image.ANTIALIAS)
  332. # Use the correct stamp
  333. f, ext = os.path.splitext( filename )
  334. istamp = [ ('Writer','odt'),
  335. ('Impress','odp'),
  336. ('Calc','ods'),
  337. ('Draw','odg')]
  338. stampfilename = filter(lambda (x,y): ext.endswith(y), istamp)
  339. stamp = Image.open( "jm2l/static/img/%s-icon.png" % stampfilename[0][0])
  340. timage = Image.new('RGBA', (THUMBNAIL_SIZE, THUMBNAIL_SIZE), (255, 255, 255, 0))
  341. # Add thumbnail
  342. timage.paste(
  343. image,
  344. ((THUMBNAIL_SIZE - image.size[0]) / 2, (THUMBNAIL_SIZE - image.size[1]) / 2))
  345. # Stamp with PDF file type
  346. timage.paste(
  347. stamp,
  348. (timage.size[0]-30, timage.size[1]-30),
  349. stamp,
  350. )
  351. timage.convert('RGB').save( TargetFileName+".jpg", 'JPEG')
  352. return self.thumbnailurl( os.path.basename(TargetFileName+".jpg") )
  353. def blendthumbnail(self, filename):
  354. blendfile = self.mediapath(filename)
  355. # Extract Thumb
  356. if 0:
  357. head = fileobj.read(12)
  358. fileobj.seek(0)
  359. if head[:2] == b'\x1f\x8b': # gzip magic
  360. import zlib
  361. head = zlib.decompress(fileobj.read(), 31)[:12]
  362. fileobj.seek(0)
  363. buf, width, height = blend_extract_thumb(blendfile)
  364. if buf:
  365. png = write_png(buf, width, height)
  366. TargetFileName = self.thumbnailpath(filename)
  367. image = Image.open(StringIO.StringIO(png))
  368. blender_indicator = Image.open( "jm2l/static/img/Blender_Thumb_Stamp.png" )
  369. image.thumbnail((THUMBNAIL_SIZE, THUMBNAIL_SIZE), Image.ANTIALIAS)
  370. timage = Image.new('RGBA', (THUMBNAIL_SIZE, THUMBNAIL_SIZE), (255, 255, 255, 0))
  371. # Add thumbnail
  372. timage.paste(
  373. image,
  374. ((THUMBNAIL_SIZE - image.size[0]) / 2, (THUMBNAIL_SIZE - image.size[1]) / 2))
  375. # Stamp with Blender file type
  376. timage.paste(
  377. blender_indicator,
  378. (timage.size[0]-30, timage.size[1]-30),
  379. blender_indicator,
  380. )
  381. timage.save( TargetFileName+".png")
  382. return self.thumbnailurl( os.path.basename(TargetFileName+".png") )
  383. return self.ExtMimeIcon('application/x-blender')
  384. def fileinfo(self,name):
  385. filename = self.mediapath(name)
  386. f, ext = os.path.splitext(name)
  387. if ext!='.type' and os.path.isfile(filename):
  388. info = {}
  389. info['name'] = name
  390. info['size'] = os.path.getsize(filename)
  391. info['url'] = self.request.route_url('media_view',
  392. name=name,
  393. media_table=self.media_table,
  394. uid=self.linked_id)
  395. mime = self.get_mimetype(name)
  396. if IMAGE_TYPES.match(mime):
  397. info['thumbnailUrl'] = self.thumbnailurl(name)
  398. elif mime in ACCEPTED_MIMES:
  399. thumb = self.thumbnailpath("%s%s" % (f, ext))
  400. thumbext = ".jpg"
  401. if mime == "application/x-blender":
  402. thumbext = ".png"
  403. if os.path.exists( thumb + thumbext ):
  404. info['thumbnailUrl'] = self.thumbnailurl(name)+thumbext
  405. else:
  406. info['thumbnailUrl'] = self.ExtMimeIcon(mime)
  407. else:
  408. info['thumbnailUrl'] = self.ExtMimeIcon(mime)
  409. if not self.display_only:
  410. info['deleteType'] = DELETEMETHOD
  411. info['deleteUrl'] = self.request.route_url('media_upload',
  412. sep='',
  413. name='',
  414. media_table=self.media_table,
  415. uid=self.linked_id) + '/' + name
  416. if DELETEMETHOD != 'DELETE':
  417. info['deleteUrl'] += '&_method=DELETE'
  418. return info
  419. else:
  420. return None
  421. @view_config(request_method='OPTIONS')
  422. def options(self):
  423. return Response(body='')
  424. @view_config(request_method='HEAD')
  425. def options(self):
  426. return Response(body='')
  427. @view_config(request_method='GET', renderer="json")
  428. def get(self):
  429. p = self.request.matchdict.get('name')
  430. if p:
  431. return self.fileinfo(p)
  432. else:
  433. filelist = []
  434. content = self.mediapath('')
  435. if content and path.exists(content):
  436. for f in os.listdir(content):
  437. n = self.fileinfo(f)
  438. if n:
  439. filelist.append(n)
  440. return { "files":filelist }
  441. @view_config(request_method='DELETE', xhr=True, accept="application/json", renderer='json')
  442. def delete(self):
  443. filename = self.request.matchdict.get('name')
  444. try:
  445. os.remove(self.mediapath(filename) + '.type')
  446. except IOError:
  447. pass
  448. except OSError:
  449. pass
  450. try:
  451. os.remove(self.thumbnailpath(filename))
  452. except IOError:
  453. pass
  454. except OSError:
  455. pass
  456. try:
  457. os.remove(self.thumbnailpath(filename+".jpg"))
  458. except IOError:
  459. pass
  460. except OSError:
  461. pass
  462. try:
  463. os.remove(self.mediapath(filename))
  464. except IOError:
  465. return False
  466. return True
  467. @view_config(request_method='POST', xhr=True, accept="application/json", renderer='json')
  468. def post(self):
  469. if self.request.matchdict.get('_method') == "DELETE":
  470. return self.delete()
  471. results = []
  472. for name, fieldStorage in self.request.POST.items():
  473. if isinstance(fieldStorage,unicode):
  474. continue
  475. result = {}
  476. result['name'] = os.path.basename(fieldStorage.filename)
  477. result['type'] = fieldStorage.type
  478. result['size'] = self.get_file_size(fieldStorage.file)
  479. if self.validate(result, fieldStorage.file):
  480. filename, file_extension = os.path.splitext( result['name'] )
  481. local_filename = slugify( filename ) + file_extension
  482. # Keep mime-type in .type file
  483. with open( self.mediapath( local_filename ) + '.type', 'w') as f:
  484. f.write(result['type'])
  485. # Store uploaded file
  486. fieldStorage.file.seek(0)
  487. with open( self.mediapath( local_filename ), 'wb') as f:
  488. shutil.copyfileobj( fieldStorage.file , f)
  489. if re.match(IMAGE_TYPES, result['type']):
  490. result['thumbnailUrl'] = self.createthumbnail(local_filename)
  491. elif result['type']=='application/pdf':
  492. result['thumbnailUrl'] = self.pdfthumbnail(local_filename)
  493. elif result['type']=='image/svg+xml':
  494. result['thumbnailUrl'] = self.svgthumbnail(local_filename)
  495. elif result['type'].startswith('application/vnd'):
  496. result['thumbnailUrl'] = self.docthumbnail(local_filename)
  497. elif result['type']=='application/x-blender':
  498. result['thumbnailUrl'] = self.blendthumbnail(local_filename)
  499. else:
  500. result['thumbnailUrl'] = self.ExtMimeIcon(result['type'])
  501. result['deleteType'] = DELETEMETHOD
  502. result['deleteUrl'] = self.request.route_url('media_upload',
  503. sep='',
  504. name='',
  505. media_table=self.media_table,
  506. uid=self.linked_id) + '/' + local_filename
  507. result['url'] = self.request.route_url('media_view',
  508. media_table=self.media_table,
  509. uid=self.linked_id,
  510. name=local_filename)
  511. if DELETEMETHOD != 'DELETE':
  512. result['deleteUrl'] += '&_method=DELETE'
  513. results.append(result)
  514. return {"files":results}
  515. @view_defaults(route_name='media_view')
  516. class MediaView(MediaPath):
  517. def __init__(self,request):
  518. self.request = request
  519. self.media_table = self.request.matchdict.get('media_table')
  520. self.linked_id = self.request.matchdict.get('uid')
  521. def mediapath(self,name):
  522. return self.get_mediapath(self.media_table, self.linked_id, name)
  523. @view_config(request_method='GET', http_cache = (EXPIRATION_TIME, {'public':True}))
  524. def get(self):
  525. name = self.request.matchdict.get('name')
  526. self.request.response.content_type = self.get_mimetype(name)
  527. try:
  528. self.request.response.body_file = open( self.mediapath(name), 'rb', 10000)
  529. except IOError:
  530. raise NotFound
  531. return self.request.response
  532. ##return Response(app_iter=ImgHandle, content_type = 'image/png')