Avatar image save/get in directory (not database)

This commit is contained in:
resteve 2014-12-16 14:26:27 +01:00
parent 6ab2490bf2
commit ed2370616b
2 changed files with 79 additions and 4 deletions

81
team.py
View File

@ -4,11 +4,16 @@
from trytond.model import ModelSQL, ModelView, fields
from trytond.pool import Pool
from trytond.transaction import Transaction
from trytond.config import config
from trytond.cache import Cache
from .tools import slugify
from datetime import datetime
from mimetypes import guess_type
import os
import hashlib
__all__ = ['GalateaTeam', 'GalateaTeamWebSite']
IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/gif']
class GalateaTeam(ModelSQL, ModelView):
@ -17,7 +22,9 @@ class GalateaTeam(ModelSQL, ModelView):
name = fields.Char('Name', required=True, on_change=['name', 'slug'])
slug = fields.Char('slug', required=True, translate=True,
help='Cannonical uri.')
avatar = fields.Binary('Avatar')
avatar = fields.Function(fields.Binary('Avatar', filename='file_name'), 'get_image',
setter='set_image')
file_name = fields.Char('File Name', required=True)
description = fields.Text('Description', required=True, translate=True,
help='You could write wiki markup to create html content. Formats text following '
'the MediaWiki (http://meta.wikimedia.org/wiki/Help:Editing) syntax.')
@ -45,15 +52,28 @@ class GalateaTeam(ModelSQL, ModelView):
Website = Pool().get('galatea.website')
return [p.id for p in Website.search([('registration','=',True)])]
@staticmethod
def _create_team_dir():
db_name = Transaction().cursor.dbname
directory = os.path.join(config.get('database', 'path'), db_name)
if not os.path.isdir(directory):
os.makedirs(directory, 0770)
directory = os.path.join(directory, 'team')
if not os.path.isdir(directory):
os.makedirs(directory, 0770)
@classmethod
def __setup__(cls):
super(GalateaTeam, cls).__setup__()
cls._order.insert(0, ('name', 'ASC'))
cls._error_messages.update({
'delete_teams': ('You can not delete '
'teams because you will get error 404 NOT Found. '
'Dissable active field.'),
'delete_teams': ('You can not delete teams because you will get error ' \
'404 NOT Found. Dissable active field.'),
'not_file_mime': ('Not know file mime "%(file_name)s"'),
'not_file_mime_image': ('"%(file_name)s" file mime is not an image ' \
'(jpg, png or gif)'),
})
cls._create_team_dir()
def on_change_name(self):
res = {}
@ -75,6 +95,59 @@ class GalateaTeam(ModelSQL, ModelView):
cls.raise_user_error('delete_teams')
def get_image(self, name):
db_name = Transaction().cursor.dbname
filename = self.file_name
filename = os.path.join(config.get('database', 'path'), db_name,
'team', filename[0:2], filename[2:4], self.file_name)
value = None
try:
with open(filename, 'rb') as file_p:
value = buffer(file_p.read())
except IOError:
pass
return value
@classmethod
def set_image(cls, teams, name, value):
if value is None:
return
db_name = Transaction().cursor.dbname
teamdir = os.path.join(
config.get('database', 'path'), db_name, 'team')
for team in teams:
file_name = team['file_name']
file_mime, _ = guess_type(file_name)
if not file_mime:
cls.raise_user_error('not_file_mime', {
'file_name': file_name,
})
if file_mime not in IMAGE_TYPES:
cls.raise_user_error('not_file_mime_image', {
'file_name': file_name,
})
_, ext = file_mime.split('/')
digest = '%s.%s' % (hashlib.md5(value).hexdigest(), ext)
subdir1 = digest[0:2]
subdir2 = digest[2:4]
directory = os.path.join(teamdir, subdir1, subdir2)
filename = os.path.join(directory, digest)
if not os.path.isdir(directory):
os.makedirs(directory, 0770)
with open(filename, 'wb') as file_p:
file_p.write(value)
cls.write([team], {
'file_name': digest,
})
class GalateaTeamWebSite(ModelSQL):
'Galatea Team - Website'
__name__ = 'galatea.team-galatea.website'

View File

@ -10,6 +10,8 @@ this repository contains the full copyright notices and license terms. -->
<field name="active"/>
<label name="avatar"/>
<field name="avatar"/>
<label name="file_name" invisible="1"/>
<field name="file_name" invisible="1"/>
<notebook colspan="4">
<page string="Descriptions" id="descriptions">
<field name="description" colspan="4"/>