towards supporting python 2 and 3

- use absolute_imports
- make use of six.moves
- use exec instead of execfile
- use list(dict) instead if dict.keys()
This commit is contained in:
j 2016-08-23 12:27:06 +02:00
parent 728ed14499
commit 1468ddbecb
89 changed files with 400 additions and 265 deletions

View file

@ -1,9 +1,10 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function, absolute_import
from django.contrib import admin from django.contrib import admin
import models from . import models
class AnnotationAdmin(admin.ModelAdmin): class AnnotationAdmin(admin.ModelAdmin):

View file

@ -2,6 +2,7 @@
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
import unicodedata import unicodedata
from six import string_types
from django.db.models import Q, Manager from django.db.models import Q, Manager
from oxdjango.query import QuerySet from oxdjango.query import QuerySet
@ -68,7 +69,7 @@ def parseCondition(condition, user):
else: else:
key = k + get_operator(op, 'istr' if k in case_insensitive_keys else 'str') key = k + get_operator(op, 'istr' if k in case_insensitive_keys else 'str')
key = str(key) key = str(key)
if isinstance(v, unicode): if isinstance(v, string_types):
v = unicodedata.normalize('NFKD', v) v = unicodedata.normalize('NFKD', v)
if k not in case_sensitive_keys: if k not in case_sensitive_keys:
v = v.lower() v = v.lower()

View file

@ -1,6 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, with_statement from __future__ import division, print_function, absolute_import
import re import re
import unicodedata import unicodedata
@ -15,10 +16,9 @@ import ox
from clip.models import Clip from clip.models import Clip
from item.utils import sort_string, get_by_key from item.utils import sort_string, get_by_key
import managers
import utils
from tasks import update_matches
from . import managers
from . import utils
def get_super_matches(obj, model): def get_super_matches(obj, model):
super_matches = [] super_matches = []
@ -133,6 +133,8 @@ class Annotation(models.Model):
return {} return {}
def save(self, *args, **kwargs): def save(self, *args, **kwargs):
from .tasks import update_matches
set_public_id = not self.id or not self.public_id set_public_id = not self.id or not self.public_id
layer = self.get_layer() layer = self.get_layer()
if self.value: if self.value:

View file

@ -1,12 +1,14 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function, absolute_import
import ox import ox
from django.conf import settings from django.conf import settings
from django.db import transaction from django.db import transaction
from celery.task import task from celery.task import task
import models from .models import Annotation
@task(ignore_results=True, queue='default') @task(ignore_results=True, queue='default')
@ -16,7 +18,7 @@ def update_matches(id, type):
elif type == 'event': elif type == 'event':
from event.models import Event as Model from event.models import Event as Model
a = models.Annotation.objects.get(pk=id) a = Annotation.objects.get(pk=id)
a_matches = getattr(a, type == 'place' and 'places' or 'events') a_matches = getattr(a, type == 'place' and 'places' or 'events')
#remove undefined matches that only have this annotation #remove undefined matches that only have this annotation
@ -52,16 +54,16 @@ def update_matches(id, type):
if not filter(lambda n: n in name_matches, if not filter(lambda n: n in name_matches,
[n.lower() for n in p.get_super_matches()]): [n.lower() for n in p.get_super_matches()]):
new.append(i) new.append(i)
removed = filter(lambda p: p not in new, current) removed = list(filter(lambda p: p not in new, current))
added = filter(lambda p: p not in current, new) added = list(filter(lambda p: p not in current, new))
update = removed + added update = removed + added
if update: if update:
for e in Model.objects.filter(id__in=update): for e in Model.objects.filter(id__in=update):
e.update_matches(models.Annotation.objects.filter(pk=a.id)) e.update_matches(Annotation.objects.filter(pk=a.id))
else: else:
#annotation has no value, remove all exisint matches #annotation has no value, remove all exisint matches
for e in a_matches.all(): for e in a_matches.all():
e.update_matches(models.Annotation.objects.filter(pk=a.id)) e.update_matches(Annotation.objects.filter(pk=a.id))
@task(ignore_results=False, queue='default') @task(ignore_results=False, queue='default')
def add_annotations(data): def add_annotations(data):
@ -85,7 +87,7 @@ def add_annotations(data):
continue continue
else: else:
value = a['value'] value = a['value']
annotation = models.Annotation( annotation = Annotation(
item=item, item=item,
layer=layer_id, layer=layer_id,
user=user, user=user,
@ -107,7 +109,7 @@ def add_annotations(data):
def update_item(id, force=False): def update_item(id, force=False):
from item.models import Item from item.models import Item
from clip.models import Clip from clip.models import Clip
a = models.Annotation.objects.get(pk=id) a = Annotation.objects.get(pk=id)
if force or a.modified >= a.item.annotations.order_by('-modified')[0].modified: if force or a.modified >= a.item.annotations.order_by('-modified')[0].modified:
#cleanup orphaned clips #cleanup orphaned clips
Clip.objects.filter(item__id=a.item.id, annotations__id=None).delete() Clip.objects.filter(item__id=a.item.id, annotations__id=None).delete()
@ -129,7 +131,7 @@ def update_annotations(layers, value):
items = {} items = {}
with transaction.atomic(): with transaction.atomic():
for a in models.Annotation.objects.filter( for a in Annotation.objects.filter(
layer__in=layers, layer__in=layers,
value=value value=value
): ):

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division from __future__ import division, print_function, absolute_import
from django.conf import settings from django.conf import settings
from django.db.models import Count, Sum, F, Value from django.db.models import Count, Sum, F, Value
@ -20,8 +20,8 @@ from item.utils import get_by_id
from entity.models import Entity from entity.models import Entity
from changelog.models import add_changelog from changelog.models import add_changelog
import models from . import models
from tasks import update_item, add_annotations from .tasks import update_item, add_annotations
def get_annotation_or_404_json(id): def get_annotation_or_404_json(id):
try: try:

View file

@ -1,9 +1,10 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function, absolute_import
from django.contrib import admin from django.contrib import admin
import models from . import models
class PageAdmin(admin.ModelAdmin): class PageAdmin(admin.ModelAdmin):

View file

@ -1,17 +1,17 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, with_statement, print_function from __future__ import division, print_function, absolute_import
import os import os
import sys import sys
import shutil import shutil
import subprocess import subprocess
import time import time
import thread
import codecs import codecs
from os.path import dirname, exists, join from os.path import dirname, exists, join
from glob import glob from glob import glob
from six.moves import _thread as thread
from django.conf import settings from django.conf import settings
from django.contrib.auth.models import User from django.contrib.auth.models import User
@ -33,7 +33,7 @@ def get_version():
if exists(git_dir): if exists(git_dir):
env = {'GIT_DIR': git_dir} env = {'GIT_DIR': git_dir}
cmd = ['git', 'rev-list', 'HEAD', '--count'] cmd = ['git', 'rev-list', 'HEAD', '--count']
return subprocess.check_output(cmd, env=env).strip() return subprocess.check_output(cmd, env=env).strip().decode('utf-8')
elif exists(info): elif exists(info):
f = open(info) f = open(info)
rev = int(f.read().split()[0]) rev = int(f.read().split()[0])
@ -101,7 +101,7 @@ def load_config(init=False):
'site', 'tv', 'user.ui', 'user.ui.part', 'user.ui.showFolder', 'site', 'tv', 'user.ui', 'user.ui.part', 'user.ui.showFolder',
'menuExtras', 'languages' 'menuExtras', 'languages'
)): )):
parts = map(lambda p: p.replace('\0', '\\.'), section.replace('\\.', '\0').split('.')) parts = [p.replace('\0', '\\.') for p in section.replace('\\.', '\0').split('.')]
# print('checking', section) # print('checking', section)
c = config c = config
d = default d = default

View file

@ -18,7 +18,7 @@ def get(config_jsonc='config.pandora.jsonc'):
if key not in docs: if key not in docs:
print(config_jsonc, 'missing', key) print(config_jsonc, 'missing', key)
''' '''
for key in docs.keys(): for key in list(docs):
if key not in config: if key not in config:
print('parse error, invalid config key:', key) print('parse error, invalid config key:', key)
del docs[key] del docs[key]

View file

@ -1,13 +1,13 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, with_statement from __future__ import division, print_function, absolute_import
import json import json
from django.db import models from django.db import models
import monkey_patch from . import monkey_patch
import tasks from . import tasks
class Page(models.Model): class Page(models.Model):

View file

@ -1,10 +1,12 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function, absolute_import
from django.contrib.auth.models import User, Group from django.contrib.auth.models import User, Group
from django.core.validators import MaxLengthValidator from django.core.validators import MaxLengthValidator
#load config from json # load config from json
import config from . import config
config.init() config.init()
NEW_LENGTH = { NEW_LENGTH = {

View file

@ -1,5 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function, absolute_import
import datetime import datetime
from celery.task import periodic_task from celery.task import periodic_task

View file

@ -1,8 +1,11 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function, absolute_import
import copy import copy
from datetime import datetime from datetime import datetime
from six import string_types
from django.shortcuts import render, redirect from django.shortcuts import render, redirect
from django.conf import settings from django.conf import settings
from django.http import HttpResponse from django.http import HttpResponse
@ -13,7 +16,7 @@ from oxdjango.decorators import login_required_json
import ox import ox
from ox.utils import json, ET from ox.utils import json, ET
import models from . import models
from user.models import init_user from user.models import init_user
from changelog.models import add_changelog from changelog.models import add_changelog
@ -102,7 +105,7 @@ def getPage(request, data):
} }
see: editPage see: editPage
''' '''
if isinstance(data, basestring): if isinstance(data, string_types):
name = data name = data
else: else:
name = data['name'] name = data['name']

View file

@ -1,9 +1,10 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function, absolute_import
from django.contrib import admin from django.contrib import admin
import models from . import models
class FileAdmin(admin.ModelAdmin): class FileAdmin(admin.ModelAdmin):

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function from __future__ import division, print_function, absolute_import
import json import json
import subprocess import subprocess
@ -14,7 +14,7 @@ from django.conf import settings
from item.models import Item from item.models import Item
from item.tasks import load_subtitles from item.tasks import load_subtitles
import models from . import models
info_keys = [ info_keys = [
'title', 'title',

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, with_statement, print_function from __future__ import division, print_function, absolute_import
import os import os
from os.path import exists from os.path import exists
@ -14,6 +14,7 @@ import shutil
from distutils.spawn import find_executable from distutils.spawn import find_executable
from glob import glob from glob import glob
from six import string_types
import numpy as np import numpy as np
import ox import ox
import ox.image import ox.image
@ -54,6 +55,7 @@ def supported_formats():
p = subprocess.Popen([settings.FFMPEG, '-codecs'], p = subprocess.Popen([settings.FFMPEG, '-codecs'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
stdout, stderr = p.communicate() stdout, stderr = p.communicate()
stdout = stdout.decode('utf-8')
return { return {
'ogg': 'libtheora' in stdout and 'libvorbis' in stdout, 'ogg': 'libtheora' in stdout and 'libvorbis' in stdout,
'webm': 'libvpx' in stdout and 'libvorbis' in stdout, 'webm': 'libvpx' in stdout and 'libvorbis' in stdout,
@ -453,7 +455,7 @@ def timeline(video, prefix, modes=None, size=None):
modes = ['antialias', 'slitscan', 'keyframes', 'audio', 'data'] modes = ['antialias', 'slitscan', 'keyframes', 'audio', 'data']
if size is None: if size is None:
size = [64, 16] size = [64, 16]
if isinstance(video, basestring): if isinstance(video, string_types):
video = [video] video = [video]
cmd = ['../bin/oxtimelines', cmd = ['../bin/oxtimelines',
'-s', ','.join(map(str, reversed(sorted(size)))), '-s', ','.join(map(str, reversed(sorted(size)))),
@ -621,7 +623,7 @@ def chop(video, start, end):
stderr=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'),
close_fds=True) close_fds=True)
p.wait() p.wait()
f = open(choped_video, 'r') f = open(choped_video, 'rb')
os.unlink(choped_video) os.unlink(choped_video)
os.rmdir(tmp) os.rmdir(tmp)
return f return f

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, with_statement from __future__ import division, print_function, absolute_import
import json import json
import os.path import os.path
@ -8,6 +8,7 @@ import shutil
import tempfile import tempfile
import time import time
from six import string_types, PY2
from django.conf import settings from django.conf import settings
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.db import models from django.db import models
@ -22,8 +23,11 @@ import item.models
from person.models import get_name_sort from person.models import get_name_sort
from taskqueue.models import Task from taskqueue.models import Task
from chunk import save_chunk from .chunk import save_chunk
import extract from . import extract
if not PY2:
unicode = str
def data_path(f, x): def data_path(f, x):
return f.get_path('data.bin') return f.get_path('data.bin')
@ -155,7 +159,7 @@ class File(models.Model):
if self.item: if self.item:
for key in self.ITEM_INFO: for key in self.ITEM_INFO:
data[key] = self.item.get(key) data[key] = self.item.get(key)
if isinstance(data[key], basestring): if isinstance(data[key], string_types):
data[key] = ox.decode_html(data[key]) data[key] = ox.decode_html(data[key])
elif isinstance(data[key], list): elif isinstance(data[key], list):
data[key] = [ox.decode_html(e) for e in data[key]] data[key] = [ox.decode_html(e) for e in data[key]]
@ -351,7 +355,7 @@ class File(models.Model):
stream.available = True stream.available = True
stream.info = {} stream.info = {}
stream.save() stream.save()
if self.info.keys() == ['extension']: if list(self.info) == ['extension']:
self.info.update(stream.info) self.info.update(stream.info)
self.parse_info() self.parse_info()
self.save() self.save()
@ -416,7 +420,7 @@ class File(models.Model):
data['users'] = list(set([i['user'] for i in data['instances']])) data['users'] = list(set([i['user'] for i in data['instances']]))
data['item'] = self.item.public_id data['item'] = self.item.public_id
if keys: if keys:
for k in data.keys(): for k in list(data):
if k not in keys: if k not in keys:
del data[k] del data[k]
return data return data
@ -450,14 +454,14 @@ class File(models.Model):
''' '''
extract stream from direct upload extract stream from direct upload
''' '''
import tasks from . import tasks
return tasks.extract_stream.delay(self.id) return tasks.extract_stream.delay(self.id)
def process_stream(self): def process_stream(self):
''' '''
extract derivatives from webm upload extract derivatives from webm upload
''' '''
import tasks from . import tasks
return tasks.process_stream.delay(self.id) return tasks.process_stream.delay(self.id)
def extract_tracks(self): def extract_tracks(self):

View file

@ -1,5 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function, absolute_import
from glob import glob from glob import glob
from celery.task import task from celery.task import task
@ -11,9 +13,9 @@ from item.models import Item
from item.tasks import update_poster from item.tasks import update_poster
from taskqueue.models import Task from taskqueue.models import Task
import models from . import models
import extract from . import extract
import external from . import external
_INSTANCE_KEYS = ('mtime', 'path') _INSTANCE_KEYS = ('mtime', 'path')
@ -104,7 +106,7 @@ def update_files(user, volume, files):
@task(ignore_results=True, queue='default') @task(ignore_results=True, queue='default')
def update_info(user, info): def update_info(user, info):
user = models.User.objects.get(username=user) user = models.User.objects.get(username=user)
files = models.File.objects.filter(oshash__in=info.keys()) files = models.File.objects.filter(oshash__in=list(info))
for f in files: for f in files:
f.update_info(info[f.oshash], user) f.update_info(info[f.oshash], user)
f.save() f.save()

View file

@ -1,6 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division from __future__ import division, print_function, absolute_import
import os.path import os.path
from datetime import datetime from datetime import datetime
@ -8,6 +9,7 @@ from django.shortcuts import get_object_or_404, redirect, render
from django.conf import settings from django.conf import settings
from django.db.models import Count, Q from django.db.models import Count, Q
from six import string_types
from celery.utils import get_full_cls_name from celery.utils import get_full_cls_name
from celery.backends import default_backend from celery.backends import default_backend
import ox import ox
@ -404,7 +406,7 @@ def moveMedia(request, data):
data['public_id'] = data.pop('item').strip() data['public_id'] = data.pop('item').strip()
if len(data['public_id']) != 7: if len(data['public_id']) != 7:
del data['public_id'] del data['public_id']
if 'director' in data and isinstance(data['director'], basestring): if 'director' in data and isinstance(data['director'], string_types):
if data['director'] == '': if data['director'] == '':
data['director'] = [] data['director'] = []
else: else:
@ -556,7 +558,7 @@ def getPath(request, data):
''' '''
response = json_response() response = json_response()
ids = data['id'] ids = data['id']
if isinstance(ids, basestring): if isinstance(ids, string_types):
ids = [ids] ids = [ids]
for f in models.File.objects.filter(oshash__in=ids).values('path', 'oshash').order_by('sort_path'): for f in models.File.objects.filter(oshash__in=ids).values('path', 'oshash').order_by('sort_path'):
response['data'][f['oshash']] = f['path'] response['data'][f['oshash']] = f['path']

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, with_statement from __future__ import division, print_function, absolute_import
from datetime import datetime from datetime import datetime
@ -10,7 +10,8 @@ from oxdjango import fields
import ox import ox
import websocket import websocket
import managers
from . import managers
''' '''
FIXME: remove this table more migrate to new ChangeLog FIXME: remove this table more migrate to new ChangeLog
@ -21,7 +22,7 @@ class Changelog(models.Model):
value = fields.DictField(default={}) value = fields.DictField(default={})
def __unicode__(self): def __unicode__(self):
return u'%s %s' %(self.type, self.created) return u'%s %s' % (self.type, self.created)
def json(self): def json(self):
return self.value return self.value
@ -67,7 +68,7 @@ class Log(models.Model):
'user': self.user.username, 'user': self.user.username,
} }
if keys: if keys:
for k in r.keys(): for k in list(r):
if k not in keys: if k not in keys:
del r[k] del r[k]
return r return r

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division from __future__ import division, print_function, absolute_import
import ox import ox
@ -12,7 +12,7 @@ from oxdjango.api import actions
from item import utils from item import utils
from user.decorators import capability_required_json from user.decorators import capability_required_json
import models from . import models
def parse_query(data, user): def parse_query(data, user):

View file

@ -2,6 +2,7 @@
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
import unicodedata import unicodedata
from six import string_types
from django.db.models import Q, Manager from django.db.models import Q, Manager
from django.conf import settings from django.conf import settings
@ -78,7 +79,7 @@ def parseCondition(condition, user):
else: else:
key = k + get_operator(op, 'istr' if k in case_insensitive_keys else 'str') key = k + get_operator(op, 'istr' if k in case_insensitive_keys else 'str')
key = str(key) key = str(key)
if isinstance(v, unicode) and op != '===': if isinstance(v, string_types) and op != '===':
v = unicodedata.normalize('NFKD', v).lower() v = unicodedata.normalize('NFKD', v).lower()
if exclude: if exclude:
q = ~Q(**{key: v}) q = ~Q(**{key: v})
@ -140,14 +141,14 @@ class ClipManager(Manager):
def parse(condition): def parse(condition):
key = 'findvalue' + get_operator(condition.get('operator', '')) key = 'findvalue' + get_operator(condition.get('operator', ''))
v = condition['value'] v = condition['value']
if isinstance(v, unicode): if isinstance(v, string_types):
v = unicodedata.normalize('NFKD', v).lower() v = unicodedata.normalize('NFKD', v).lower()
q = Q(**{key: v}) q = Q(**{key: v})
if condition['key'] in layer_ids: if condition['key'] in layer_ids:
q = q & Q(layer=condition['key']) q = q & Q(layer=condition['key'])
return q return q
conditions = map(parse, conditions) conditions = [parse(c) for c in conditions]
if conditions: if conditions:
q = conditions[0] q = conditions[0]
for c in conditions[1:]: for c in conditions[1:]:

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, with_statement from __future__ import division, print_function, absolute_import
from django.db import models from django.db import models
from django.conf import settings from django.conf import settings
@ -8,7 +8,8 @@ from django.conf import settings
import ox import ox
from archive import extract from archive import extract
import managers
from . import managers
def get_layers(item, interval=None, user=None): def get_layers(item, interval=None, user=None):
@ -107,7 +108,7 @@ class MetaClip(object):
if not j['videoRatio']: if not j['videoRatio']:
j['videoRatio'] = 4/3 j['videoRatio'] = 4/3
if keys: if keys:
for key in j.keys(): for key in list(j):
if key not in keys: if key not in keys:
del j[key] del j[key]
#needed here to make item find with clips work #needed here to make item find with clips work

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division from __future__ import division, print_function, absolute_import
from django.conf import settings from django.conf import settings
import ox import ox
@ -14,7 +14,7 @@ from item.models import Item
from item import utils from item import utils
from changelog.models import add_changelog from changelog.models import add_changelog
import models from . import models
def parse_query(data, user): def parse_query(data, user):

View file

@ -1,11 +1,13 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, with_statement from __future__ import division, print_function, absolute_import
import os import os
import re import re
from glob import glob from glob import glob
from urllib import quote, unquote
from six import string_types
from six.moves.urllib.parse import quote
from django.db import models from django.db import models
from django.db.models import Max from django.db.models import Max
from django.contrib.auth.models import User from django.contrib.auth.models import User
@ -18,8 +20,8 @@ from item.models import Item
from archive.extract import resize_image from archive.extract import resize_image
from archive.chunk import save_chunk from archive.chunk import save_chunk
import managers from . import managers
import utils from . import utils
def get_path(f, x): return f.path(x) def get_path(f, x): return f.path(x)
@ -174,7 +176,7 @@ class Document(models.Model):
elif hasattr(self, _map.get(key, key)): elif hasattr(self, _map.get(key, key)):
response[key] = getattr(self, _map.get(key,key)) or '' response[key] = getattr(self, _map.get(key,key)) or ''
if item: if item:
if isinstance(item, basestring): if isinstance(item, string_types):
item = Item.objects.get(public_id=item) item = Item.objects.get(public_id=item)
d = self.descriptions.filter(item=item) d = self.descriptions.filter(item=item)
if d.exists(): if d.exists():
@ -228,7 +230,7 @@ class Document(models.Model):
elif self.extension in ('jpg', 'png', 'gif'): elif self.extension in ('jpg', 'png', 'gif'):
if os.path.exists(src): if os.path.exists(src):
if size and page: if size and page:
crop = map(int, page.split(',')) crop = list(map(int, page.split(',')))
if len(crop) == 4: if len(crop) == 4:
path = os.path.join(folder, '%s.jpg' % ','.join(map(str, crop))) path = os.path.join(folder, '%s.jpg' % ','.join(map(str, crop)))
if not os.path.exists(path): if not os.path.exists(path):

View file

@ -1,9 +1,11 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division from __future__ import division, print_function, absolute_import
import os import os
from glob import glob from glob import glob
from six import string_types
import ox import ox
from ox.utils import json from ox.utils import json
from oxdjango.api import actions from oxdjango.api import actions
@ -20,7 +22,7 @@ from entity.models import Entity
from archive.chunk import process_chunk from archive.chunk import process_chunk
from changelog.models import add_changelog from changelog.models import add_changelog
import models from . import models
def get_document_or_404_json(id): def get_document_or_404_json(id):
try: try:
@ -49,7 +51,7 @@ def addDocument(request, data):
else: else:
ids = [data['id']] ids = [data['id']]
if 'item' in data: if 'item' in data:
if isinstance(data['item'], basestring): if isinstance(data['item'], string_types):
item = Item.objects.get(public_id=data['item']) item = Item.objects.get(public_id=data['item'])
if item.editable(request.user): if item.editable(request.user):
for id in ids: for id in ids:
@ -66,7 +68,7 @@ def addDocument(request, data):
document.add(item) document.add(item)
add_changelog(request, data, data['item']) add_changelog(request, data, data['item'])
elif 'entity' in data: elif 'entity' in data:
if isinstance(data['entity'], basestring): if isinstance(data['entity'], string_types):
entity = Entity.get(data['entity']) entity = Entity.get(data['entity'])
if entity.editable(request.user): if entity.editable(request.user):
for id in ids: for id in ids:

View file

@ -1,15 +1,15 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, with_statement from __future__ import division, print_function, absolute_import
import re import re
import os import os
import shutil import shutil
from glob import glob from glob import glob
import subprocess import subprocess
from urllib import quote
import tempfile import tempfile
from six.moves.urllib.parse import quote
import ox import ox
from oxdjango.fields import DictField, TupleField from oxdjango.fields import DictField, TupleField
from django.conf import settings from django.conf import settings
@ -24,7 +24,7 @@ import clip.models
from archive import extract from archive import extract
import managers from . import managers
def get_path(f, x): return f.path(x) def get_path(f, x): return f.path(x)
def get_icon_path(f, x): return get_path(f, 'icon.jpg') def get_icon_path(f, x): return get_path(f, 'icon.jpg')

View file

@ -1,6 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division from __future__ import division, print_function, absolute_import
import os import os
import re import re
@ -16,7 +17,7 @@ from django.conf import settings
from item import utils from item import utils
from changelog.models import add_changelog from changelog.models import add_changelog
import models from . import models
def get_edit_or_404_json(id): def get_edit_or_404_json(id):
id = id.split(':') id = id.split(':')
@ -400,7 +401,7 @@ def findEdits(request, data):
x['value'] == 'featured' and \ x['value'] == 'featured' and \
x['operator'] in ('=', '==') x['operator'] in ('=', '==')
is_featured = len(filter(is_featured_condition, data.get('query', {}).get('conditions', []))) > 0 is_featured = any(filter(is_featured_condition, data.get('query', {}).get('conditions', [])))
if is_section_request: if is_section_request:
qs = query['qs'] qs = query['qs']

View file

@ -1,12 +1,14 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, with_statement from __future__ import division, print_function, absolute_import
import os import os
import re import re
from glob import glob from glob import glob
from urllib import quote, unquote
import unicodedata import unicodedata
from six import string_types
from six.moves.urllib.parse import quote, unquote
from django.db import models, transaction from django.db import models, transaction
from django.db.models import Max from django.db.models import Max
from django.contrib.auth.models import User from django.contrib.auth.models import User
@ -20,7 +22,7 @@ from person.models import get_name_sort
from item.utils import get_by_id from item.utils import get_by_id
from document.models import Document from document.models import Document
import managers from . import managers
class Entity(models.Model): class Entity(models.Model):
@ -139,14 +141,14 @@ class Entity(models.Model):
self.alternativeNames = tuple(ox.escape_html(n) for n in names) self.alternativeNames = tuple(ox.escape_html(n) for n in names)
else: else:
#FIXME: more data validation #FIXME: more data validation
if isinstance(data[key], basestring): if isinstance(data[key], string_types):
self.data[key] = ox.sanitize_html(data[key]) self.data[key] = ox.sanitize_html(data[key])
else: else:
self.data[key] = data[key] self.data[key] = data[key]
def json(self, keys=None, user=None): def json(self, keys=None, user=None):
if not keys: if not keys:
keys=[ keys = [
'alternativeNames', 'alternativeNames',
'editable', 'editable',
'id', 'id',
@ -155,7 +157,7 @@ class Entity(models.Model):
'type', 'type',
'user', 'user',
'documents', 'documents',
] + self.data.keys() ] + list(self.data)
response = {} response = {}
for key in keys: for key in keys:
if key == 'id': if key == 'id':
@ -186,7 +188,7 @@ class Entity(models.Model):
f, created = Find.objects.get_or_create(entity=self, key=key) f, created = Find.objects.get_or_create(entity=self, key=key)
if isinstance(value, bool): if isinstance(value, bool):
value = value and 'true' or 'false' value = value and 'true' or 'false'
if isinstance(value, basestring): if isinstance(value, string_types):
value = ox.decode_html(ox.strip_tags(value.strip())) value = ox.decode_html(ox.strip_tags(value.strip()))
value = unicodedata.normalize('NFKD', value).lower() value = unicodedata.normalize('NFKD', value).lower()
f.value = value f.value = value

View file

@ -1,7 +1,8 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division from __future__ import division, print_function, absolute_import
from six import string_types
import ox import ox
from ox.utils import json from ox.utils import json
from oxdjango.api import actions from oxdjango.api import actions
@ -18,8 +19,8 @@ from item.models import Item
from itemlist.models import List from itemlist.models import List
from changelog.models import add_changelog from changelog.models import add_changelog
import models from . import models
from managers import namePredicate from .managers import namePredicate
def get_entity_or_404_json(id): def get_entity_or_404_json(id):
try: try:
@ -64,7 +65,7 @@ def addEntity(request, data):
for key in ('type', 'alternativeNames'): for key in ('type', 'alternativeNames'):
if key in data and data[key]: if key in data and data[key]:
value = data[key] value = data[key]
if isinstance(value, basestring): if isinstance(value, string_types):
value = ox.escape_html(value) value = ox.escape_html(value)
if key == 'alternativeNames': if key == 'alternativeNames':
value = tuple([ox.escape_html(v) for v in value]) value = tuple([ox.escape_html(v) for v in value])

View file

@ -1,9 +1,10 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function, absolute_import
from django.contrib import admin from django.contrib import admin
import models from . import models
class EventAdmin(admin.ModelAdmin): class EventAdmin(admin.ModelAdmin):

View file

@ -2,6 +2,7 @@
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
import unicodedata import unicodedata
from six import string_types
from django.db.models import Q, Manager from django.db.models import Q, Manager
from oxdjango.query import QuerySet from oxdjango.query import QuerySet
@ -30,7 +31,7 @@ def parseCondition(condition, user):
key = k + get_operator(op, 'istr') key = k + get_operator(op, 'istr')
key = str(key) key = str(key)
if isinstance(v, unicode): if isinstance(v, string_types):
v = unicodedata.normalize('NFKD', v).lower() v = unicodedata.normalize('NFKD', v).lower()
if exclude: if exclude:
q = ~Q(**{k: v}) q = ~Q(**{k: v})

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, with_statement from __future__ import division, print_function, absolute_import
from django.db import models, transaction from django.db import models, transaction
from django.contrib.auth.models import User from django.contrib.auth.models import User
@ -13,7 +13,7 @@ from item import utils
from person.models import get_name_sort from person.models import get_name_sort
from title.models import get_title_sort from title.models import get_title_sort
import managers from . import managers
class Event(models.Model): class Event(models.Model):

View file

@ -1,9 +1,10 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function, absolute_import
from celery.task import task from celery.task import task
from models import Event from .models import Event
''' '''

View file

@ -1,10 +1,11 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division from __future__ import division, print_function, absolute_import
from django.db.models import Count from django.db.models import Count
from django.conf import settings from django.conf import settings
from six import string_types
import ox import ox
from ox.utils import json from ox.utils import json
from oxdjango.decorators import login_required_json from oxdjango.decorators import login_required_json
@ -14,7 +15,7 @@ from oxdjango.api import actions
from item import utils from item import utils
from changelog.models import add_changelog from changelog.models import add_changelog
import models from . import models
@login_required_json @login_required_json
def addEvent(request, data): def addEvent(request, data):
@ -47,7 +48,7 @@ def addEvent(request, data):
'type', 'alternativeNames'): 'type', 'alternativeNames'):
if key in data and data[key]: if key in data and data[key]:
value = data[key] value = data[key]
if isinstance(value, basestring): if isinstance(value, string_types):
value = ox.escape_html(value) value = ox.escape_html(value)
if key == 'alternativeNames': if key == 'alternativeNames':
value = tuple([ox.escape_html(v) for v in value]) value = tuple([ox.escape_html(v) for v in value])
@ -101,7 +102,7 @@ def editEvent(request, data):
'type', 'alternativeNames'): 'type', 'alternativeNames'):
if key in data: if key in data:
value = data[key] value = data[key]
if isinstance(value, basestring): if isinstance(value, string_types):
value = ox.escape_html(value) value = ox.escape_html(value)
if key == 'alternativeNames': if key == 'alternativeNames':
value = tuple([ox.escape_html(v) for v in value]) value = tuple([ox.escape_html(v) for v in value])

View file

@ -1,9 +1,10 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function, absolute_import
from django.contrib import admin from django.contrib import admin
import models from . import models
class ItemAdmin(admin.ModelAdmin): class ItemAdmin(admin.ModelAdmin):

View file

@ -1,16 +1,18 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function, absolute_import
from datetime import datetime from datetime import datetime
import unicodedata import unicodedata
from six import string_types
from django.db.models import Q, Manager from django.db.models import Q, Manager
from django.conf import settings from django.conf import settings
from archive.models import Volume from archive.models import Volume
from itemlist.models import List from itemlist.models import List
from django.contrib.auth.models import Group from django.contrib.auth.models import Group
import models from . import utils
import utils
from oxdjango.query import QuerySet from oxdjango.query import QuerySet
from oxdjango.managers import get_operator from oxdjango.managers import get_operator
@ -29,6 +31,7 @@ def parseCondition(condition, user, owner=None):
} }
... ...
''' '''
from . import models
k = condition.get('key', '*') k = condition.get('key', '*')
k = {'id': 'public_id'}.get(k, k) k = {'id': 'public_id'}.get(k, k)
if not k: if not k:
@ -119,7 +122,7 @@ def parseCondition(condition, user, owner=None):
else: else:
value_key = k value_key = k
if not k.startswith('public_id'): if not k.startswith('public_id'):
if isinstance(v, unicode): if isinstance(v, string_types):
v = unicodedata.normalize('NFKD', v).lower() v = unicodedata.normalize('NFKD', v).lower()
if k in facet_keys: if k in facet_keys:
in_find = False in_find = False
@ -237,6 +240,7 @@ class ItemManager(Manager):
return QuerySet(self.model) return QuerySet(self.model)
def filter_list(self, qs, l, user): def filter_list(self, qs, l, user):
from . import models
if l != "*": if l != "*":
l = l.split(":") l = l.split(":")
only_public = True only_public = True

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, with_statement from __future__ import division, print_function, absolute_import
import json import json
import os import os
@ -12,8 +12,9 @@ import unicodedata
import uuid import uuid
from datetime import datetime from datetime import datetime
from glob import glob from glob import glob
from urllib import quote
from six import PY2, string_types
from six.moves.urllib.parse import quote
from django.db import models, transaction, connection from django.db import models, transaction, connection
from django.db.models import Q, Sum, Max from django.db.models import Q, Sum, Max
from django.conf import settings from django.conf import settings
@ -26,11 +27,11 @@ from oxdjango import fields
import ox.web.imdb import ox.web.imdb
import ox.image import ox.image
import managers from . import managers
import utils from . import utils
import tasks from . import tasks
from .timelines import join_tiles from .timelines import join_tiles
from data_api import external_data from .data_api import external_data
from annotation.models import Annotation from annotation.models import Annotation
from archive import extract from archive import extract
@ -40,6 +41,10 @@ from sequence.tasks import get_sequences
from title.models import get_title_sort from title.models import get_title_sort
import archive.models import archive.models
if not PY2:
unicode = str
def get_id(info): def get_id(info):
q = Item.objects.all() q = Item.objects.all()
for key in ('title', 'director', 'year'): for key in ('title', 'director', 'year'):
@ -270,7 +275,7 @@ class Item(models.Model):
if key in self.data: if key in self.data:
del self.data[key] del self.data[key]
else: else:
k = filter(lambda i: i['id'] == key, settings.CONFIG['itemKeys']) k = list(filter(lambda i: i['id'] == key, settings.CONFIG['itemKeys']))
ktype = k and k[0].get('type') or '' ktype = k and k[0].get('type') or ''
if ktype == 'text': if ktype == 'text':
self.data[key] = ox.sanitize_html(data[key]) self.data[key] = ox.sanitize_html(data[key])
@ -280,11 +285,11 @@ class Item(models.Model):
self.data[key] = [ox.escape_html(t) for t in data[key]] self.data[key] = [ox.escape_html(t) for t in data[key]]
elif key in ('episodeTitle', 'seriesTitle', 'episodeDirector', 'seriesYear'): elif key in ('episodeTitle', 'seriesTitle', 'episodeDirector', 'seriesYear'):
self.data[key] = ox.escape_html(data[key]) self.data[key] = ox.escape_html(data[key])
elif isinstance(data[key], basestring): elif isinstance(data[key], string_types):
self.data[key] = ox.escape_html(data[key]) self.data[key] = ox.escape_html(data[key])
elif isinstance(data[key], list): elif isinstance(data[key], list):
def cleanup(i): def cleanup(i):
if isinstance(i, basestring): if isinstance(i, string_types):
i = ox.escape_html(i) i = ox.escape_html(i)
return i return i
self.data[key] = [cleanup(i) for i in data[key]] self.data[key] = [cleanup(i) for i in data[key]]
@ -314,9 +319,9 @@ class Item(models.Model):
def expand_connections(self): def expand_connections(self):
c = self.get('connections') c = self.get('connections')
if c: if c:
for t in c.keys(): for t in list(c):
if c[t]: if c[t]:
if isinstance(c[t][0], basestring): if isinstance(c[t][0], string_types):
c[t] = [{'id': i, 'title': None} for i in c[t]] c[t] = [{'id': i, 'title': None} for i in c[t]]
ids = [i['id'] for i in c[t]] ids = [i['id'] for i in c[t]]
known = {} known = {}
@ -442,7 +447,7 @@ class Item(models.Model):
def delete_files(self): def delete_files(self):
path = os.path.join(settings.MEDIA_ROOT, self.path()) path = os.path.join(settings.MEDIA_ROOT, self.path())
if isinstance(path, unicode): if not isinstance(path, bytes):
path = path.encode('utf-8') path = path.encode('utf-8')
if os.path.exists(path): if os.path.exists(path):
shutil.rmtree(path) shutil.rmtree(path)
@ -498,7 +503,7 @@ class Item(models.Model):
if settings.DATA_SERVICE: if settings.DATA_SERVICE:
url = self.prefered_poster_url() url = self.prefered_poster_url()
external_posters = self.external_data.get('posters', {}) external_posters = self.external_data.get('posters', {})
services = external_posters.keys() services = list(external_posters)
for service in settings.POSTER_PRECEDENCE: for service in settings.POSTER_PRECEDENCE:
if service in services: if service in services:
index.append(service) index.append(service)
@ -593,7 +598,7 @@ class Item(models.Model):
if value: if value:
i[key] = value i[key] = value
if 'cast' in i and isinstance(i['cast'][0], basestring): if 'cast' in i and isinstance(i['cast'][0], string_types):
i['cast'] = [i['cast']] i['cast'] = [i['cast']]
if 'cast' in i and isinstance(i['cast'][0], list): if 'cast' in i and isinstance(i['cast'][0], list):
i['cast'] = [{'actor': x[0], 'character': x[1]} for x in i['cast']] i['cast'] = [{'actor': x[0], 'character': x[1]} for x in i['cast']]
@ -639,7 +644,7 @@ class Item(models.Model):
if keys and 'frames' in keys: if keys and 'frames' in keys:
i['frames'] = frames i['frames'] = frames
selected_frame = filter(lambda f: f['selected'], frames) selected_frame = [f for f in frames if f['selected']]
if selected_frame: if selected_frame:
i['posterFrame'] = selected_frame[0]['position'] i['posterFrame'] = selected_frame[0]['position']
elif self.poster_frame != -1.0: elif self.poster_frame != -1.0:
@ -650,7 +655,7 @@ class Item(models.Model):
if keys: if keys:
dkeys = filter(lambda k: k in keys, dkeys) dkeys = filter(lambda k: k in keys, dkeys)
for key in dkeys: for key in dkeys:
k = filter(lambda i: i['id'] == key, settings.CONFIG['itemKeys']) k = list(filter(lambda i: i['id'] == key, settings.CONFIG['itemKeys']))
if isinstance((k and k[0].get('type') or ''), list): if isinstance((k and k[0].get('type') or ''), list):
i['%sdescription' % key] = {} i['%sdescription' % key] = {}
if key == 'name': if key == 'name':
@ -760,7 +765,7 @@ class Item(models.Model):
f, created = ItemFind.objects.get_or_create(item=self, key=key) f, created = ItemFind.objects.get_or_create(item=self, key=key)
if isinstance(value, bool): if isinstance(value, bool):
value = value and 'true' or 'false' value = value and 'true' or 'false'
if isinstance(value, basestring): if isinstance(value, string_types):
value = ox.decode_html(ox.strip_tags(value.strip())) value = ox.decode_html(ox.strip_tags(value.strip()))
value = unicodedata.normalize('NFKD', value).lower() value = unicodedata.normalize('NFKD', value).lower()
f.value = value f.value = value
@ -879,7 +884,7 @@ class Item(models.Model):
return sort_value return sort_value
def set_value(s, name, value): def set_value(s, name, value):
if isinstance(value, basestring): if isinstance(value, string_types):
value = ox.decode_html(value.lower()) value = ox.decode_html(value.lower())
if not value: if not value:
value = None value = None
@ -1011,7 +1016,7 @@ class Item(models.Model):
set_value(s, name, value) set_value(s, name, value)
elif sort_type == 'date': elif sort_type == 'date':
value = self.get(source) value = self.get(source)
if isinstance(value, basestring): if isinstance(value, string_types):
value = datetime_safe.datetime.strptime(value, '%Y-%m-%d') value = datetime_safe.datetime.strptime(value, '%Y-%m-%d')
set_value(s, name, value) set_value(s, name, value)
@ -1045,6 +1050,7 @@ class Item(models.Model):
current_values = [] current_values = []
else: else:
current_values = [unicode(current_values)] current_values = [unicode(current_values)]
filter_map = utils.get_by_id(settings.CONFIG['itemKeys'], key).get('filterMap') filter_map = utils.get_by_id(settings.CONFIG['itemKeys'], key).get('filterMap')
if filter_map: if filter_map:
filter_map = re.compile(filter_map) filter_map = re.compile(filter_map)
@ -1231,7 +1237,7 @@ class Item(models.Model):
return return
base = self.path('torrent') base = self.path('torrent')
base = os.path.abspath(os.path.join(settings.MEDIA_ROOT, base)) base = os.path.abspath(os.path.join(settings.MEDIA_ROOT, base))
if isinstance(base, unicode): if not isinstance(base, bytes):
base = base.encode('utf-8') base = base.encode('utf-8')
if os.path.exists(base): if os.path.exists(base):
shutil.rmtree(base) shutil.rmtree(base)
@ -1250,9 +1256,9 @@ class Item(models.Model):
quote(filename.encode('utf-8')), quote(filename.encode('utf-8')),
extension) extension)
video = "%s.%s" % (base, extension) video = "%s.%s" % (base, extension)
if isinstance(media_path, unicode): if not isinstance(media_path, bytes):
media_path = media_path.encode('utf-8') media_path = media_path.encode('utf-8')
if isinstance(video, unicode): if not isinstance(video, bytes):
video = video.encode('utf-8') video = video.encode('utf-8')
media_path = os.path.relpath(media_path, os.path.dirname(video)) media_path = os.path.relpath(media_path, os.path.dirname(video))
os.symlink(media_path, video) os.symlink(media_path, video)
@ -1267,9 +1273,9 @@ class Item(models.Model):
extension = media_path.split('.')[-1] extension = media_path.split('.')[-1]
video = "%s/%s.Part %d.%s" % (base, filename, part, extension) video = "%s/%s.Part %d.%s" % (base, filename, part, extension)
part += 1 part += 1
if isinstance(media_path, unicode): if not isinstance(media_path, bytes):
media_path = media_path.encode('utf-8') media_path = media_path.encode('utf-8')
if isinstance(video, unicode): if not isinstance(video, bytes):
video = video.encode('utf-8') video = video.encode('utf-8')
media_path = os.path.relpath(media_path, os.path.dirname(video)) media_path = os.path.relpath(media_path, os.path.dirname(video))
os.symlink(media_path, video) os.symlink(media_path, video)
@ -1360,7 +1366,7 @@ class Item(models.Model):
def save_poster(self, data): def save_poster(self, data):
self.poster.name = self.path('poster.jpg') self.poster.name = self.path('poster.jpg')
poster = self.poster.path poster = self.poster.path
with open(poster, 'w') as f: with open(poster, 'wb') as f:
f.write(data) f.write(data)
self.poster_height = self.poster.height self.poster_height = self.poster.height
self.poster_width = self.poster.width self.poster_width = self.poster.width
@ -1425,7 +1431,7 @@ class Item(models.Model):
data = ox.net.read_url(url) data = ox.net.read_url(url)
self.save_poster(data) self.save_poster(data)
elif os.path.exists(poster): elif os.path.exists(poster):
with open(poster) as f: with open(poster, 'rb') as f:
data = f.read() data = f.read()
if data: if data:
self.save_poster(data) self.save_poster(data)
@ -1450,7 +1456,7 @@ class Item(models.Model):
data['oxdbId'] = self.oxdbId or self.oxdb_id() or self.public_id data['oxdbId'] = self.oxdbId or self.oxdb_id() or self.public_id
ox.makedirs(os.path.join(settings.MEDIA_ROOT, self.path())) ox.makedirs(os.path.join(settings.MEDIA_ROOT, self.path()))
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, close_fds=True) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, close_fds=True)
p.communicate(json.dumps(data, default=fields.to_json)) p.communicate(json.dumps(data, default=fields.to_json).encode('utf-8'))
self.clear_poster_cache(poster) self.clear_poster_cache(poster)
return poster return poster

View file

@ -1,5 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function, absolute_import
import os import os
from datetime import timedelta, datetime from datetime import timedelta, datetime
import gzip import gzip
@ -15,8 +17,6 @@ from app.utils import limit_rate
from text.models import Text from text.models import Text
from taskqueue.models import Task from taskqueue.models import Task
import models
@periodic_task(run_every=timedelta(days=1), queue='encoding') @periodic_task(run_every=timedelta(days=1), queue='encoding')
def cronjob(**kwargs): def cronjob(**kwargs):
@ -25,6 +25,7 @@ def cronjob(**kwargs):
update_random_clip_sort() update_random_clip_sort()
def update_random_sort(): def update_random_sort():
from . import models
if filter(lambda f: f['id'] == 'random', settings.CONFIG['itemKeys']): if filter(lambda f: f['id'] == 'random', settings.CONFIG['itemKeys']):
random.seed() random.seed()
ids = [f['item'] for f in models.ItemSort.objects.values('item')] ids = [f['item'] for f in models.ItemSort.objects.values('item')]
@ -52,11 +53,13 @@ def update_random_clip_sort():
@task(ignore_results=True, queue='default') @task(ignore_results=True, queue='default')
def update_clips(public_id): def update_clips(public_id):
from . import models
item = models.Item.objects.get(public_id=public_id) item = models.Item.objects.get(public_id=public_id)
item.clips.all().update(user=item.user.id) item.clips.all().update(user=item.user.id)
@task(ignore_results=True, queue='default') @task(ignore_results=True, queue='default')
def update_poster(public_id): def update_poster(public_id):
from . import models
item = models.Item.objects.get(public_id=public_id) item = models.Item.objects.get(public_id=public_id)
item.remove_poster() item.remove_poster()
item.make_poster() item.make_poster()
@ -71,22 +74,26 @@ def update_poster(public_id):
@task(ignore_results=True, queue='default') @task(ignore_results=True, queue='default')
def update_file_paths(public_id): def update_file_paths(public_id):
from . import models
item = models.Item.objects.get(public_id=public_id) item = models.Item.objects.get(public_id=public_id)
item.update_file_paths() item.update_file_paths()
@task(ignore_results=True, queue='default') @task(ignore_results=True, queue='default')
def update_external(public_id): def update_external(public_id):
from . import models
item = models.Item.objects.get(public_id=public_id) item = models.Item.objects.get(public_id=public_id)
item.update_external() item.update_external()
@task(queue="encoding") @task(queue="encoding")
def update_timeline(public_id): def update_timeline(public_id):
from . import models
item = models.Item.objects.get(public_id=public_id) item = models.Item.objects.get(public_id=public_id)
item.update_timeline(async=False) item.update_timeline(async=False)
Task.finish(item) Task.finish(item)
@task(queue="encoding") @task(queue="encoding")
def rebuild_timeline(public_id): def rebuild_timeline(public_id):
from . import models
i = models.Item.objects.get(public_id=public_id) i = models.Item.objects.get(public_id=public_id)
for s in i.streams(): for s in i.streams():
s.make_timeline() s.make_timeline()
@ -94,6 +101,7 @@ def rebuild_timeline(public_id):
@task(queue="encoding") @task(queue="encoding")
def load_subtitles(public_id): def load_subtitles(public_id):
from . import models
item = models.Item.objects.get(public_id=public_id) item = models.Item.objects.get(public_id=public_id)
if item.load_subtitles(): if item.load_subtitles():
item.update_find() item.update_find()
@ -102,6 +110,7 @@ def load_subtitles(public_id):
@task(ignore_results=True, queue='default') @task(ignore_results=True, queue='default')
def update_sitemap(base_url): def update_sitemap(base_url):
from . import models
sitemap = os.path.abspath(os.path.join(settings.MEDIA_ROOT, 'sitemap.xml.gz')) sitemap = os.path.abspath(os.path.join(settings.MEDIA_ROOT, 'sitemap.xml.gz'))
def absolute_url(url): def absolute_url(url):

View file

@ -53,8 +53,8 @@ def plural_key(term):
def sort_title(title): def sort_title(title):
title = title.replace(u'Æ', 'Ae') title = title.replace(u'Æ', 'Ae')
if isinstance(title, str): if isinstance(title, bytes):
title = unicode(title) title = title.decode('utf-8')
title = sort_string(title) title = sort_string(title)
#title #title

View file

@ -1,13 +1,14 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function from __future__ import division, print_function, absolute_import
import os.path import os.path
import mimetypes import mimetypes
import random import random
from urlparse import urlparse
from urllib import quote
import time import time
from six import PY2
from six.moves.urllib.parse import quote, urlparse
from PIL import Image from PIL import Image
from django.db.models import Count, Sum from django.db.models import Count, Sum
from django.http import HttpResponse, HttpResponseForbidden, Http404 from django.http import HttpResponse, HttpResponseForbidden, Http404
@ -23,9 +24,9 @@ from oxdjango.shortcuts import render_to_json_response, get_object_or_404_json,
from oxdjango.http import HttpFileResponse from oxdjango.http import HttpFileResponse
import ox import ox
import models from . import models
import utils from . import utils
import tasks from . import tasks
from archive.models import File, Stream from archive.models import File, Stream
from archive import extract from archive import extract
@ -35,6 +36,8 @@ from changelog.models import add_changelog
from oxdjango.api import actions from oxdjango.api import actions
if not PY2:
unicode = str
def _order_query(qs, sort, prefix='sort__'): def _order_query(qs, sort, prefix='sort__'):
order_by = [] order_by = []
@ -869,6 +872,7 @@ def timeline(request, id, size, position=-1, format='jpg', mode=None):
modes.pop(modes.index(mode)) modes.pop(modes.index(mode))
prefix = os.path.join(item.timeline_prefix, 'timeline') prefix = os.path.join(item.timeline_prefix, 'timeline')
position = int(position)
def timeline(): def timeline():
timeline = '%s%s%sp' % (prefix, mode, size) timeline = '%s%s%sp' % (prefix, mode, size)

View file

@ -1,6 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, with_statement from __future__ import division, print_function, absolute_import
import os import os
import re import re
import subprocess import subprocess
@ -15,7 +16,9 @@ import ox
from oxdjango.fields import DictField, TupleField from oxdjango.fields import DictField, TupleField
from archive import extract from archive import extract
import managers
from . import managers
def get_path(f, x): return f.path(x) def get_path(f, x): return f.path(x)
def get_icon_path(f, x): return get_path(f, 'icon.jpg') def get_icon_path(f, x): return get_path(f, 'icon.jpg')

View file

@ -1,6 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division from __future__ import division, print_function, absolute_import
import os import os
import re import re
@ -13,7 +14,7 @@ from oxdjango.shortcuts import render_to_json_response, get_object_or_404_json,
from oxdjango.http import HttpFileResponse from oxdjango.http import HttpFileResponse
import models from . import models
from oxdjango.api import actions from oxdjango.api import actions
from item import utils from item import utils
from item.models import Item from item.models import Item

View file

@ -1,12 +1,12 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, with_statement from __future__ import division, print_function, absolute_import
from django.db import models from django.db import models
from django.contrib.auth.models import User from django.contrib.auth.models import User
import ox import ox
import managers from . import managers
class Log(models.Model): class Log(models.Model):
created = models.DateTimeField(auto_now_add=True, db_index=True) created = models.DateTimeField(auto_now_add=True, db_index=True)
@ -32,7 +32,7 @@ class Log(models.Model):
'user': self.user and self.user.username or '', 'user': self.user and self.user.username or '',
} }
if keys: if keys:
for key in j.keys(): for key in list(j):
if key not in keys: if key not in keys:
del j[key] del j[key]
return j return j

View file

@ -1,10 +1,12 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function, absolute_import
from datetime import timedelta, datetime from datetime import timedelta, datetime
from celery.task import periodic_task from celery.task import periodic_task
import models from . import models
@periodic_task(run_every=timedelta(days=1), queue='encoding') @periodic_task(run_every=timedelta(days=1), queue='encoding')
def cronjob(**kwargs): def cronjob(**kwargs):

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, with_statement from __future__ import division, print_function, absolute_import
import logging import logging
import sys import sys
@ -19,7 +19,7 @@ class ErrorHandler(logging.Handler):
import traceback import traceback
from django.views.debug import ExceptionReporter from django.views.debug import ExceptionReporter
from django.conf import settings from django.conf import settings
import models from . import models
user = None user = None
line = 0 line = 0
text = '' text = ''

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division from __future__ import division, print_function, absolute_import
import ox import ox
from ox.utils import json from ox.utils import json
@ -12,7 +12,7 @@ from oxdjango.api import actions
from item import utils from item import utils
import models from . import models
def logError(request, data): def logError(request, data):

View file

@ -5,9 +5,12 @@ import sys
root_dir = os.path.normpath(os.path.abspath(os.path.dirname(__file__))) root_dir = os.path.normpath(os.path.abspath(os.path.dirname(__file__)))
os.chdir(root_dir) os.chdir(root_dir)
#using virtualenv's activate_this.py to reorder sys.path # using virtualenv's activate_this.py to reorder sys.path
activate_this = os.path.join(root_dir, '..', 'bin', 'activate_this.py') activate_this = os.path.join(root_dir, '..', 'bin', 'activate_this.py')
execfile(activate_this, dict(__file__=activate_this)) with open(activate_this) as f:
code = compile(f.read(), activate_this, 'exec')
exec(code, dict(__file__=activate_this))
# execfile(activate_this, dict(__file__=activate_this))
if __name__ == "__main__": if __name__ == "__main__":

View file

@ -1,9 +1,10 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function, absolute_import
from django.contrib import admin from django.contrib import admin
import models from . import models
class NewsAdmin(admin.ModelAdmin): class NewsAdmin(admin.ModelAdmin):

View file

@ -1,11 +1,11 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, with_statement from __future__ import division, print_function, absolute_import
from django.db import models from django.db import models
import ox import ox
import managers from . import managers
class News(models.Model): class News(models.Model):
@ -35,7 +35,7 @@ class News(models.Model):
'text': self.text, 'text': self.text,
} }
if keys: if keys:
for key in j.keys(): for key in list(j):
if key not in keys: if key not in keys:
del j[key] del j[key]
return j return j

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division from __future__ import division, print_function, absolute_import
import ox import ox
from ox.utils import json from ox.utils import json
@ -11,7 +11,7 @@ from oxdjango.shortcuts import render_to_json_response, get_object_or_404_json,
from oxdjango.api import actions from oxdjango.api import actions
from changelog.models import add_changelog from changelog.models import add_changelog
import models from . import models
def getNews(request, data): def getNews(request, data):
''' '''

View file

@ -1 +1,3 @@
from actions import actions from __future__ import absolute_import
from .actions import actions

View file

@ -1,6 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, with_statement from __future__ import division, absolute_import
import inspect import inspect
import sys import sys
@ -8,7 +9,7 @@ from django.conf import settings
from ..shortcuts import render_to_json_response, json_response from ..shortcuts import render_to_json_response, json_response
def autodiscover(): def autodiscover(self=None):
# Register api actions from all installed apps # Register api actions from all installed apps
from importlib import import_module from importlib import import_module
from django.utils.module_loading import module_has_submodule from django.utils.module_loading import module_has_submodule
@ -50,6 +51,9 @@ def trim(docstring):
class ApiActions(dict): class ApiActions(dict):
properties = {} properties = {}
versions = {} versions = {}
autodiscover = autodiscover
def __init__(self): def __init__(self):
def api(request, data): def api(request, data):
@ -74,10 +78,10 @@ class ApiActions(dict):
code = data.get('code', False) code = data.get('code', False)
version = getattr(request, 'version', None) version = getattr(request, 'version', None)
if version: if version:
_actions = self.versions.get(version, {}).keys() _actions = list(self.versions.get(version, {}))
_actions = list(set(_actions + self.keys())) _actions = list(set(_actions + list(self)))
else: else:
_actions = self.keys() _actions = list(self)
_actions.sort() _actions.sort()
actions = {} actions = {}
for a in _actions: for a in _actions:
@ -111,7 +115,10 @@ class ApiActions(dict):
def register(self, method, action=None, cache=True, version=None): def register(self, method, action=None, cache=True, version=None):
if not action: if not action:
if hasattr(method, 'func_name'):
action = method.func_name action = method.func_name
else:
action = method.__name__
if version: if version:
if not version in self.versions: if not version in self.versions:
self.versions[version] = {} self.versions[version] = {}

View file

@ -1,11 +1,12 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import absolute_import
from django.conf.urls import url from django.conf.urls import url
import views from . import views
import actions from . import actions
actions.autodiscover() actions.autodiscover()
urlpatterns = [ urlpatterns = [

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, with_statement from __future__ import division, absolute_import
import json import json
@ -10,7 +10,7 @@ from django.conf import settings
from ..shortcuts import render_to_json_response, json_response, HttpErrorJson from ..shortcuts import render_to_json_response, json_response, HttpErrorJson
from actions import actions from .actions import actions
def api(request): def api(request):
if request.META['REQUEST_METHOD'] == "OPTIONS": if request.META['REQUEST_METHOD'] == "OPTIONS":
@ -21,7 +21,7 @@ def api(request):
if request.META['REQUEST_METHOD'] != "POST" or ( if request.META['REQUEST_METHOD'] != "POST" or (
not 'action' in request.POST and request.META.get('CONTENT_TYPE') != 'application/json' not 'action' in request.POST and request.META.get('CONTENT_TYPE') != 'application/json'
): ):
methods = actions.keys() methods = list(actions)
api = [] api = []
for f in sorted(methods): for f in sorted(methods):
api.append({'name': f, api.append({'name': f,

View file

@ -1,11 +1,12 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import absolute_import
try: try:
from django.contrib.auth.decorators import wraps from django.contrib.auth.decorators import wraps
except: except:
from django.utils.functional import wraps from django.utils.functional import wraps
from shortcuts import render_to_json_response from .shortcuts import render_to_json_response
def login_required_json(function=None): def login_required_json(function=None):
""" """

View file

@ -27,15 +27,16 @@ def _to_json(python_object):
raise TypeError(u'%s %s is not JSON serializable' % (repr(python_object), type(python_object))) raise TypeError(u'%s %s is not JSON serializable' % (repr(python_object), type(python_object)))
def render_to_json_response(dictionary, content_type="text/json", status=200): def render_to_json_response(dictionary, content_type="text/json", status=200):
indent=None indent = None
if settings.DEBUG: if settings.DEBUG:
content_type = "text/javascript" content_type = "text/javascript"
indent = 2 indent = 2
if getattr(settings, 'JSON_DEBUG', False): if getattr(settings, 'JSON_DEBUG', False):
print(json.dumps(dictionary, indent=2, default=_to_json, ensure_ascii=False).encode('utf-8')) print(json.dumps(dictionary, indent=2, default=_to_json, ensure_ascii=False).encode('utf-8'))
response = json.dumps(dictionary, indent=indent, default=_to_json, ensure_ascii=False)
return HttpResponse(json.dumps(dictionary, indent=indent, default=_to_json, if not isinstance(response, bytes):
ensure_ascii=False).encode('utf-8'), content_type=content_type, status=status) response = response.encode('utf-8')
return HttpResponse(response, content_type=content_type, status=status)
def get_object_or_404_json(klass, *args, **kwargs): def get_object_or_404_json(klass, *args, **kwargs):
from django.shortcuts import _get_queryset from django.shortcuts import _get_queryset

View file

@ -2,6 +2,7 @@
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
import unicodedata import unicodedata
from six import string_types
from django.db.models import Q, Manager from django.db.models import Q, Manager
from item.utils import decode_id from item.utils import decode_id
@ -56,7 +57,7 @@ def parseCondition(condition, user):
else: else:
key = k + get_operator(op, 'istr') key = k + get_operator(op, 'istr')
key = str(key) key = str(key)
if isinstance(v, unicode): if isinstance(v, string_types):
v = unicodedata.normalize('NFKD', v).lower() v = unicodedata.normalize('NFKD', v).lower()
if exclude: if exclude:
q = ~Q(**{key: v}) q = ~Q(**{key: v})

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, with_statement from __future__ import division, print_function, absolute_import
import unicodedata import unicodedata
@ -12,8 +12,7 @@ import ox
from item import utils from item import utils
import item.models import item.models
import managers from . import managers
import tasks
def get_name_sort(name, sortname=None): def get_name_sort(name, sortname=None):
name = unicodedata.normalize('NFKD', name).strip() name = unicodedata.normalize('NFKD', name).strip()
@ -95,7 +94,7 @@ class Person(models.Model):
'numberofnames': self.numberofnames, 'numberofnames': self.numberofnames,
} }
if keys: if keys:
for key in j.keys(): for key in list(j):
if key not in keys: if key not in keys:
del j[key] del j[key]
return j return j

View file

@ -1,8 +1,10 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function, absolute_import
from celery.task import task from celery.task import task
import models from . import models
@task(ignore_results=True, queue='default') @task(ignore_results=True, queue='default')

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division from __future__ import division, print_function, absolute_import
import ox import ox
from ox.utils import json from ox.utils import json
@ -11,8 +11,8 @@ from oxdjango.shortcuts import render_to_json_response, get_object_or_404_json,
from oxdjango.api import actions from oxdjango.api import actions
from item import utils from item import utils
import models from . import models
import tasks from . import tasks
from user.decorators import capability_required_json from user.decorators import capability_required_json
from changelog.models import add_changelog from changelog.models import add_changelog

View file

@ -1,9 +1,10 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function, absolute_import
from django.contrib import admin from django.contrib import admin
import models from . import models
class PlaceAdmin(admin.ModelAdmin): class PlaceAdmin(admin.ModelAdmin):

View file

@ -2,6 +2,7 @@
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
import unicodedata import unicodedata
from six import string_types
from django.db.models import Q, Manager from django.db.models import Q, Manager
from item.utils import decode_id from item.utils import decode_id
@ -55,7 +56,7 @@ def parseCondition(condition, user):
key = k + get_operator(op, 'istr') key = k + get_operator(op, 'istr')
key = str(key) key = str(key)
if isinstance(v, unicode): if isinstance(v, string_types):
v = unicodedata.normalize('NFKD', v).lower() v = unicodedata.normalize('NFKD', v).lower()
if exclude: if exclude:

View file

@ -1,16 +1,17 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, with_statement from __future__ import division, print_function, absolute_import
from django.db import models, transaction from django.db import models, transaction
from django.contrib.auth.models import User from django.contrib.auth.models import User
import ox import ox
from oxdjango import fields from oxdjango import fields
import managers
from annotation.models import Annotation, get_matches, get_super_matches from annotation.models import Annotation, get_matches, get_super_matches
from item.models import Item from item.models import Item
from . import managers
class Place(models.Model): class Place(models.Model):
''' '''

View file

@ -1,9 +1,10 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function, absolute_import
from celery.task import task from celery.task import task
import models from . import models
''' '''

View file

@ -1,10 +1,11 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division from __future__ import division, print_function, absolute_import
from django.db.models import Max, Min, Count from django.db.models import Max, Min, Count
from django.conf import settings from django.conf import settings
from six import string_types
import ox import ox
from ox.utils import json from ox.utils import json
@ -15,7 +16,7 @@ from oxdjango.api import actions
from item import utils from item import utils
from changelog.models import add_changelog from changelog.models import add_changelog
import models from . import models
@login_required_json @login_required_json
def addPlace(request, data): def addPlace(request, data):
@ -116,7 +117,7 @@ def editPlace(request, data):
''' '''
place = get_object_or_404_json(models.Place, pk=ox.fromAZ(data['id'])) place = get_object_or_404_json(models.Place, pk=ox.fromAZ(data['id']))
names = data.get('name', []) names = data.get('name', [])
if isinstance(names, basestring): if isinstance(names, string_types):
names = [names] names = [names]
names = [ox.escape_html(n) for n in names] names = [ox.escape_html(n) for n in names]
alternative_names = [ox.escape_html(n) for n in data.get('alternativeNames', [])] alternative_names = [ox.escape_html(n) for n in data.get('alternativeNames', [])]
@ -145,7 +146,7 @@ def editPlace(request, data):
for key in data: for key in data:
if key != 'id': if key != 'id':
value = data[key] value = data[key]
if isinstance(value, basestring): if isinstance(value, string_types):
value = ox.escape_html(value) value = ox.escape_html(value)
if isinstance(value, list): if isinstance(value, list):
value = tuple(value) value = tuple(value)

View file

@ -1,5 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function, absolute_import
from django.db.models import Q, Manager from django.db.models import Q, Manager
@ -7,8 +9,6 @@ from item.utils import decode_id
from oxdjango.managers import get_operator from oxdjango.managers import get_operator
from oxdjango.query import QuerySet from oxdjango.query import QuerySet
import models
keymap = { keymap = {
'in': 'start', 'in': 'start',
'out': 'end' 'out': 'end'
@ -29,6 +29,7 @@ def parseCondition(condition, user):
operator: "!=" operator: "!="
} }
''' '''
from . import models
k = condition.get('key', default_key) k = condition.get('key', default_key)
k = keymap.get(k, k) k = keymap.get(k, k)
if not k: if not k:

View file

@ -1,12 +1,13 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, with_statement from __future__ import division, print_function, absolute_import
from django.db import models from django.db import models
import managers
from item.models import ItemSort from item.models import ItemSort
from . import managers
def parse_hash(value): def parse_hash(value):
return int(value, 16) - 9223372036854775808 return int(value, 16) - 9223372036854775808
@ -22,7 +23,7 @@ class Sequence(models.Model):
'shape': 0, 'shape': 0,
'color': 1 'color': 1
} }
mode = models.IntegerField(choices=sorted(zip(MODE.values(), MODE.keys()), key=lambda k: k[0]), default=0) mode = models.IntegerField(choices=sorted(zip(MODE.values(), list(MODE)), key=lambda k: k[0]), default=0)
sort = models.ForeignKey(ItemSort, null=True, related_name='sequences') sort = models.ForeignKey(ItemSort, null=True, related_name='sequences')
hash = models.BigIntegerField(db_index=True, default=-9223372036854775808) hash = models.BigIntegerField(db_index=True, default=-9223372036854775808)

View file

@ -1,14 +1,17 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function, absolute_import
from six import string_types
from django.db import connection, transaction from django.db import connection, transaction
from celery.task import task from celery.task import task
import models
import item.models import item.models
import extract from . import extract
@task(ignore_results=True, queue='encoding') @task(ignore_results=True, queue='encoding')
def get_sequences(public_id): def get_sequences(public_id):
from . import models
i = item.models.Item.objects.get(public_id=public_id) i = item.models.Item.objects.get(public_id=public_id)
models.Sequence.objects.filter(sort=i.sort).delete() models.Sequence.objects.filter(sort=i.sort).delete()
position = 0 position = 0
@ -29,7 +32,7 @@ def get_sequences(public_id):
sequence['duration'] = sequence['end'] - sequence['start'] sequence['duration'] = sequence['end'] - sequence['start']
if not keys: if not keys:
keys = ', '.join(['"%s"'%k for k in sequence.keys()]) keys = ', '.join(['"%s"'%k for k in sequence.keys()])
v = ', '.join([isinstance(v, basestring) and "'%s'"%v or str(v) v = ', '.join([isinstance(v, string_types) and "'%s'"%v or str(v)
for v in sequence.values()]) for v in sequence.values()])
values.append('(%s)'%v) values.append('(%s)'%v)
if values: if values:

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division from __future__ import division, print_function, absolute_import
from ox.utils import json from ox.utils import json
from oxdjango.shortcuts import render_to_json_response, json_response from oxdjango.shortcuts import render_to_json_response, json_response
@ -11,7 +11,7 @@ from item.models import Item
from item import utils from item import utils
from changelog.models import add_changelog from changelog.models import add_changelog
import models from . import models
def parse_query(data, user): def parse_query(data, user):

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function from __future__ import division, print_function, absolute_import
from datetime import datetime, timedelta from datetime import datetime, timedelta
from time import time from time import time

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division from __future__ import division, print_function, absolute_import
import ox import ox
from oxdjango.decorators import login_required_json from oxdjango.decorators import login_required_json

View file

@ -1,12 +1,13 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, with_statement from __future__ import division, print_function, absolute_import
import os import os
import re import re
import subprocess import subprocess
from glob import glob from glob import glob
from urllib import quote
from six.moves.urllib.parse import quote
from django.db import models from django.db import models
from django.db.models import Max from django.db.models import Max
from django.contrib.auth.models import User from django.contrib.auth.models import User
@ -18,7 +19,7 @@ from oxdjango.fields import TupleField
from archive import extract from archive import extract
from archive.chunk import save_chunk from archive.chunk import save_chunk
import managers from . import managers
def get_path(i, x): return i.path(x) def get_path(i, x): return i.path(x)
@ -217,7 +218,7 @@ class Text(models.Model):
else: else:
response['names'] = re.compile('<[^<>]*?data-name="(.+?)"').findall(self.text) response['names'] = re.compile('<[^<>]*?data-name="(.+?)"').findall(self.text)
for key in response.keys(): for key in list(response):
if key not in keys + default_keys: if key not in keys + default_keys:
del response[key] del response[key]
return response return response

View file

@ -1,6 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division from __future__ import division, print_function, absolute_import
import os import os
import re import re
@ -17,7 +18,7 @@ from django.shortcuts import render
from item import utils from item import utils
from archive.chunk import process_chunk from archive.chunk import process_chunk
import models from . import models
from changelog.models import add_changelog from changelog.models import add_changelog
def get_text_or_404_json(id): def get_text_or_404_json(id):

View file

@ -1,6 +1,8 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
import unicodedata import unicodedata
from six import string_types
from django.db.models import Q, Manager from django.db.models import Q, Manager
from item.utils import decode_id from item.utils import decode_id
@ -46,7 +48,7 @@ def parseCondition(condition, user):
return q return q
if k == 'id': if k == 'id':
v = decode_id(v) v = decode_id(v)
elif isinstance(v, unicode): elif isinstance(v, string_types):
v = unicodedata.normalize('NFKD', v).lower() v = unicodedata.normalize('NFKD', v).lower()
if isinstance(v, bool): if isinstance(v, bool):
key = k key = k

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, with_statement from __future__ import division, print_function, absolute_import
import unicodedata import unicodedata
@ -10,11 +10,11 @@ import ox
from item import utils from item import utils
import managers from . import managers
def get_title_sort(title): def get_title_sort(title):
if isinstance(title, str): if isinstance(title, bytes):
title = unicode(title) title = title.decde('utf-8')
title = unicodedata.normalize('NFKD', title).strip() title = unicodedata.normalize('NFKD', title).strip()
if title: if title:
title, created = Title.objects.get_or_create(title=title) title, created = Title.objects.get_or_create(title=title)
@ -70,7 +70,7 @@ class Title(models.Model):
'sorttitle': self.sorttitle, 'sorttitle': self.sorttitle,
} }
if keys: if keys:
for key in j.keys(): for key in list(j):
if key not in keys: if key not in keys:
del j[key] del j[key]
return j return j

View file

@ -1,6 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division from __future__ import division, print_function, absolute_import
import unicodedata import unicodedata
import ox import ox
@ -14,7 +15,7 @@ from item import utils
from user.decorators import capability_required_json from user.decorators import capability_required_json
from changelog.models import add_changelog from changelog.models import add_changelog
import models from . import models
@capability_required_json('canManageTitlesAndNames') @capability_required_json('canManageTitlesAndNames')

View file

@ -1,6 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, with_statement from __future__ import division, print_function, absolute_import
from datetime import datetime, timedelta from datetime import datetime, timedelta
from random import randint from random import randint

View file

@ -1,12 +1,14 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function, absolute_import
from datetime import timedelta from datetime import timedelta
from celery.task import periodic_task from celery.task import periodic_task
from app.utils import limit_rate from app.utils import limit_rate
import models from . import models
@periodic_task(run_every=timedelta(days=1), queue='encoding') @periodic_task(run_every=timedelta(days=1), queue='encoding')

View file

@ -1,14 +1,15 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division from __future__ import division, print_function, absolute_import
import models
from ox.utils import json from ox.utils import json
from oxdjango.shortcuts import render_to_json_response, json_response from oxdjango.shortcuts import render_to_json_response, json_response
from itemlist.views import get_list_or_404_json from itemlist.views import get_list_or_404_json
from oxdjango.api import actions from oxdjango.api import actions
from . import models
def tv(request, data): def tv(request, data):
''' '''
Gets the current TV program for a given list Gets the current TV program for a given list

View file

@ -1,12 +1,15 @@
# Create your views here. # -*- coding: utf-8 -*-
from urllib import quote # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function, absolute_import
import re import re
from six.moves.urllib.parse import quote
from django.shortcuts import get_object_or_404, redirect from django.shortcuts import get_object_or_404, redirect
import app.views import app.views
import models from . import models
def padma_find(request): def padma_find(request):
url = '/' url = '/'

View file

@ -1,5 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function, absolute_import
import copy import copy
from datetime import datetime from datetime import datetime
@ -9,8 +11,6 @@ from django.db.models import Max
from django.conf import settings from django.conf import settings
from django.contrib.gis.geoip2 import GeoIP2 from django.contrib.gis.geoip2 import GeoIP2
import ox import ox
from oxdjango.fields import DictField from oxdjango.fields import DictField
from ox.utils import json from ox.utils import json
@ -19,8 +19,9 @@ from itemlist.models import List, Position
import text import text
import edit import edit
import managers from . import managers
import tasks from . import tasks
class SessionData(models.Model): class SessionData(models.Model):
session_key = models.CharField(max_length=40, primary_key=True) session_key = models.CharField(max_length=40, primary_key=True)
@ -170,7 +171,7 @@ class SessionData(models.Model):
j['notes'] = p.notes j['notes'] = p.notes
j['numberoflists'] = self.numberoflists j['numberoflists'] = self.numberoflists
if keys: if keys:
for key in j.keys(): for key in list(j):
if key not in keys: if key not in keys:
del j[key] del j[key]
return j return j
@ -323,7 +324,7 @@ def get_ui(user_ui, user=None):
ids += add(user.lists.exclude(status="featured"), 'personal') ids += add(user.lists.exclude(status="featured"), 'personal')
ids += add(user.subscribed_lists.filter(status='public'), 'public') ids += add(user.subscribed_lists.filter(status='public'), 'public')
ids += add(List.objects.filter(status='featured'), 'featured') ids += add(List.objects.filter(status='featured'), 'featured')
for i in ui['lists'].keys(): for i in list(ui['lists']):
if i not in ids: if i not in ids:
del ui['lists'][i] del ui['lists'][i]
tids = [''] tids = ['']
@ -373,7 +374,7 @@ def user_json(user, keys=None):
'username': user.username, 'username': user.username,
} }
if keys: if keys:
for key in j.keys(): for key in list(j):
if key not in keys: if key not in keys:
del j[key] del j[key]
return j return j

View file

@ -1,22 +1,24 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function, absolute_import
import json import json
from datetime import timedelta from datetime import timedelta
from itertools import izip_longest
from six.moves import zip_longest
from celery.task import task, periodic_task from celery.task import task, periodic_task
import models
from app.models import Settings from app.models import Settings
from statistics import Statistics from .statistics import Statistics
@periodic_task(run_every=timedelta(hours=1), queue='encoding') @periodic_task(run_every=timedelta(hours=1), queue='encoding')
def cronjob(**kwargs): def cronjob(**kwargs):
update_statistics() update_statistics()
def update_statistics(): def update_statistics():
from . import models
def chunker(iterable, chunksize, filler): def chunker(iterable, chunksize, filler):
return izip_longest(*[iter(iterable)]*chunksize, fillvalue=filler) return zip_longest(*[iter(iterable)]*chunksize, fillvalue=filler)
stats = Statistics() stats = Statistics()
ids = [i['session_key'] ids = [i['session_key']
@ -30,12 +32,14 @@ def update_statistics():
@task(ignore_results=True, queue='default') @task(ignore_results=True, queue='default')
def parse_data(key): def parse_data(key):
from . import models
session_data = models.SessionData.objects.get(session_key=key) session_data = models.SessionData.objects.get(session_key=key)
session_data.parse_data() session_data.parse_data()
session_data.save() session_data.save()
@task(ignore_results=True, queue='default') @task(ignore_results=True, queue='default')
def update_numberoflists(username): def update_numberoflists(username):
from . import models
user = models.User.objects.get(username=username) user = models.User.objects.get(username=username)
models.SessionData.objects.filter( models.SessionData.objects.filter(
user=user user=user

View file

@ -1,5 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, print_function, absolute_import
import random import random
random.seed() random.seed()
import re import re
@ -25,8 +27,8 @@ from item.models import Access, Item
from item import utils from item import utils
from changelog.models import add_changelog from changelog.models import add_changelog
import models from . import models
from decorators import capability_required_json from .decorators import capability_required_json
def get_user_or_404(data): def get_user_or_404(data):
@ -770,10 +772,10 @@ def setUI(request, data):
else: else:
ui = json.loads(request.session.get('ui', '{}')) ui = json.loads(request.session.get('ui', '{}'))
for key in data: for key in data:
keys = map(lambda p: p.replace('\0', '\\.'), key.replace('\\.', '\0').split('.')) keys = [p.replace('\0', '\\.') for p in key.replace('\\.', '\0').split('.')]
value = data[key] value = data[key]
p = ui p = ui
while len(keys)>1: while len(keys) > 1:
key = keys.pop(0) key = keys.pop(0)
if isinstance(p, list): if isinstance(p, list):
p = p[getPositionById(p, key)] p = p[getPositionById(p, key)]

View file

@ -6,9 +6,12 @@ import os
root_dir = os.path.normpath(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) root_dir = os.path.normpath(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
#using virtualenv's activate_this.py to reorder sys.path # using virtualenv's activate_this.py to reorder sys.path
activate_this = os.path.join(root_dir, 'bin', 'activate_this.py') activate_this = os.path.join(root_dir, 'bin', 'activate_this.py')
execfile(activate_this, dict(__file__=activate_this)) if os.path.exists(activate_this):
with open(activate_this) as f:
code = compile(f.read(), activate_this, 'exec')
exec(code, dict(__file__=activate_this))
from PIL import Image from PIL import Image
from optparse import OptionParser from optparse import OptionParser

View file

@ -6,9 +6,12 @@ import os
root_dir = os.path.normpath(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) root_dir = os.path.normpath(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
#using virtualenv's activate_this.py to reorder sys.path # using virtualenv's activate_this.py to reorder sys.path
activate_this = os.path.join(root_dir, 'bin', 'activate_this.py') activate_this = os.path.join(root_dir, 'bin', 'activate_this.py')
execfile(activate_this, dict(__file__=activate_this)) if os.path.exists(activate_this):
with open(activate_this) as f:
code = compile(f.read(), activate_this, 'exec')
exec(code, dict(__file__=activate_this))
from PIL import Image from PIL import Image
from PIL import ImageDraw from PIL import ImageDraw

View file

@ -7,8 +7,11 @@ import os
root_dir = os.path.normpath(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) root_dir = os.path.normpath(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
# using virtualenv's activate_this.py to reorder sys.path # using virtualenv's activate_this.py to reorder sys.path
#activate_this = os.path.join(root_dir, 'bin', 'activate_this.py') activate_this = os.path.join(root_dir, 'bin', 'activate_this.py')
#execfile(activate_this, dict(__file__=activate_this)) if os.path.exists(activate_this):
with open(activate_this) as f:
code = compile(f.read(), activate_this, 'exec')
exec(code, dict(__file__=activate_this))
from PIL import Image from PIL import Image
from PIL import ImageDraw from PIL import ImageDraw

View file

@ -8,7 +8,10 @@ root_dir = os.path.normpath(os.path.abspath(os.path.join(os.path.dirname(__file_
# using virtualenv's activate_this.py to reorder sys.path # using virtualenv's activate_this.py to reorder sys.path
activate_this = os.path.join(root_dir, 'bin', 'activate_this.py') activate_this = os.path.join(root_dir, 'bin', 'activate_this.py')
execfile(activate_this, dict(__file__=activate_this)) if os.path.exists(activate_this):
with open(activate_this) as f:
code = compile(f.read(), activate_this, 'exec')
exec(code, dict(__file__=activate_this))
from PIL import Image from PIL import Image
from PIL import ImageDraw from PIL import ImageDraw

View file

@ -8,7 +8,10 @@ root_dir = os.path.normpath(os.path.abspath(os.path.join(os.path.dirname(__file_
# using virtualenv's activate_this.py to reorder sys.path # using virtualenv's activate_this.py to reorder sys.path
activate_this = os.path.join(root_dir, 'bin', 'activate_this.py') activate_this = os.path.join(root_dir, 'bin', 'activate_this.py')
execfile(activate_this, dict(__file__=activate_this)) if os.path.exists(activate_this):
with open(activate_this) as f:
code = compile(f.read(), activate_this, 'exec')
exec(code, dict(__file__=activate_this))
from PIL import Image from PIL import Image
from PIL import ImageDraw from PIL import ImageDraw

View file

@ -8,7 +8,10 @@ root_dir = os.path.normpath(os.path.abspath(os.path.join(os.path.dirname(__file_
# using virtualenv's activate_this.py to reorder sys.path # using virtualenv's activate_this.py to reorder sys.path
activate_this = os.path.join(root_dir, 'bin', 'activate_this.py') activate_this = os.path.join(root_dir, 'bin', 'activate_this.py')
execfile(activate_this, dict(__file__=activate_this)) if os.path.exists(activate_this):
with open(activate_this) as f:
code = compile(f.read(), activate_this, 'exec')
exec(code, dict(__file__=activate_this))
from PIL import Image from PIL import Image
from PIL import ImageDraw from PIL import ImageDraw