Commits

catapela committed 8a4095e

re format code,
handle ImportError from timezone wiht django < 1.4,
remove readme.html

  • Participants
  • Parent commits a9bc666

Comments (0)

Files changed (11)

 Copyright (c) 2010, Andreas Fritz
+
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without modification, are permitted 

dynamicLink/__init__.py

 import os
 import django
 import sys
-import django
+
+__author__ = "Andreas Fritz - sources.e-blue.eu"
+__copyright__ = "Copyright (c) " + "28.08.2010" + " Andreas Fritz"
+__licence__ = """New BSD Licence"""
 
 __version__ = VERSION = version.VERSION
 RELEASE_DJANGO = version.RELEASE_DJANGO
 REQUIRES = version.REQUIRES
 
 try:
-    __doc__ = open(os.path.join(os.path.dirname(__file__), 'README_COPY')).read()
+    __doc__ = open(
+                   os.path.join(os.path.dirname(__file__), 'README_COPY')
+                   ).read()
     __docformat__ = 'reStructuredText'
 except IOError:
-    __doc__ = 'For full documentation review the README file in your package or go to:' \
-    'http://pypi.python.org/pypi/django-dynamic-link/'
+    __doc__ = 'For full documentation review the README file in your ' \
+    'package or go to: http://pypi.python.org/pypi/django-dynamic-link/'
     __docformat__ = 'txt'
 
+
 def CKINST():
     """function to find problems of the installation."""
     print('I try to find errors for you!')
-    
+
     djv = django.VERSION[:2]
     greatest_dlv = version.RELEASE_DJANGO[0]
     smalest_dlv = version.RELEASE_DJANGO[0]
 
     def strform(val):
         """returns formated version tuples"""
-        return str(val).strip('()').replace(' ', '').replace(',','.')
+        return str(val).strip('()').replace(' ', '').replace(',', '.')
 
     # find greatest and smallest possible django version for dynamic link
     for dlv in version.RELEASE_DJANGO:
             smalest_dlv = dlv
 
     # Messages
-    part1 = 'Warning! "django-dynamic-link %s" (use: "dynamicLink.VERSION") is not ' \
-            'tested with "Django %s". May it runs with it may not! ' \
-            'With the installed django-dynamic-link is "Django %s" recommended. ' \
-            % (str(version.VERSION), str(django.VERSION), strform(greatest_dlv))
-    part2 = 'Use "pip install django==%s.X". or downgrade django-dynamic-link. ' \
+    part1 = 'Warning! "django-dynamic-link %s" (use: "dynamicLink.VERSION") ' \
+            'is not tested with "Django %s". May it runs with it may not! ' \
+            'With the installed django-dynamic-link is "Django %s" ' \
+            'recommended.' % (
+                              str(version.VERSION),
+                              str(django.VERSION),
+                              strform(greatest_dlv)
+                              )
+    part2 = 'Use "pip install django==%s.X". or downgrade ' \
+            'django-dynamic-link.' % strform(greatest_dlv)
+    part3 = 'Use "pip install django==%s.X" or try ' \
+            '"pip install --upgrade django-dynamic-link".' \
             % strform(greatest_dlv)
-    part3 = 'Use "pip install django==%s.X" or try "pip install --upgrade django-dynamic-link". ' \
-            % strform(greatest_dlv)
-    part4 = 'To display all supported django versions in this release use "dynamicLink.RELEASE_DJANGO". ' \
-            'To display recommended django-dynamic-link versions dynamicLink.REQUIRES'
+    part4 = 'To display all supported django versions in this ' \
+            'release use "dynamicLink.RELEASE_DJANGO". To display ' \
+            'recommended django-dynamic-link versions dynamicLink.REQUIRES'
 
     # check dynaic link dependences
     # Warnings
 
     # Errors
     error = True
-    pyver =  sys.version_info[:2]
+    pyver = sys.version_info[:2]
     if pyver < version.PYTHON_MIN:
         print('')
-        print('Error! Wrong python version. dynamicLink depends on python %s or higher. ' \
-        'With this python installation dynamicLink will not work properly!' \
-        % strform(version.PYTHON_MIN))
+        print(
+            'Error! Wrong python version. dynamicLink depends on python %s ' \
+            'or higher. With this python installation dynamicLink will not ' \
+            'work properly!' % strform(version.PYTHON_MIN)
+              )
     else:
         error = False
 
     # check the python version for the actual django installation
     dja = django.VERSION[:2]
     hint = True
-    if dja == (1,2) and not pyver >= (2,4):
+    if dja == (1, 2) and not pyver >= (2, 4):
         print('')
-        print('Hint! Django %s requires Python 2.4 or greater.' % (dja,pyver))
-    elif dja == (1,3) and not pyver >= (2,4):
+        print('Hint! Django %s requires Python 2.4 or greater.' % (dja, pyver))
+    elif dja == (1, 3) and not pyver >= (2, 4):
         print('')
-        print('Hint! Django %s requires Python 2.4 or greater.' % (dja,pyver))
-    elif dja == (1,4) and not pyver >= (2,5):
+        print('Hint! Django %s requires Python 2.4 or greater.' % (dja, pyver))
+    elif dja == (1, 4) and not pyver >= (2, 5):
         print('')
-        print('Hint! Django %s requires Python 2.5 or greater.' % (dja,pyver))
+        print('Hint! Django %s requires Python 2.5 or greater.' % (dja, pyver))
     else:
         hint = False
 

dynamicLink/admin.py

 __author__ = "Andreas Fritz - sources.e-blue.eu"
 __copyright__ = "Copyright (c) " + "28.08.2010" + " Andreas Fritz"
 __licence__ = """New BSD Licence"""
-__doc__ = """Zur Zeit noch keine Dokumentation."""
 
 from django.contrib import admin
 from models import Download
         return HttpResponse('<a target="new" href="%s/">%s/</a><br/>' % (sitelink, sitelink))
     make_link.short_description = _("Make from selected a download site link")
 
-admin.site.register(Download, DownLinkAdmin)
+admin.site.register(Download, DownLinkAdmin)

dynamicLink/api.py

 
 def file_link_url(request, linkobject, langcode='lg'):
     """returns the access url of the of the dynamicLink object"""
-    return '%s%s/%s/%s/link/%s/%s' % ('http://', request.META.get('HTTP_HOST'), \
-            langcode, presettings.DYNAMIC_LINK_URL_BASE_COMPONENT, linkobject.link_key, \
-            linkobject.get_filename())
+    return '%s%s/%s/%s/link/%s/%s' % (
+                                  'http://',
+                                  request.META.get('HTTP_HOST'),
+                                  langcode,
+                                  presettings.DYNAMIC_LINK_URL_BASE_COMPONENT,
+                                  linkobject.link_key,
+                                  linkobject.get_filename()
+                                      )
+
 
 class DynamicLink:
     """
         """access his url"""
         return file_link_url(request, self.new_link, langcode)
 
+
 class DownloadSiteUrl():
     """
     create a download site with links from the given keys
         if keylist:
             self.keys += keylist
 
-    def add_key(self,key):
-        """add a key to allready given keys"""
+    def add_key(self, key):
+        """add a key to already given keys"""
         self.keys.append(key)
 
     def get_site_url(self, request, langcode='lg'):
-        """returns a site urls form allready given keys"""
-        return '%s%s/%s/%s/site/%s' % ('http://', request.META.get('HTTP_HOST'), \
-        langcode, presettings.DYNAMIC_LINK_URL_BASE_COMPONENT, '-'.join(self.keys))
-
-
-
-
-
-
-
-
+        """returns a site urls form already given keys"""
+        return '%s%s/%s/%s/site/%s' % (
+                                   'http://',
+                                   request.META.get('HTTP_HOST'),
+                                   langcode,
+                                   presettings.DYNAMIC_LINK_URL_BASE_COMPONENT,
+                                   '-'.join(self.keys)
+                                       )

dynamicLink/locale/de/LC_MESSAGES/django.po

 
 #: models.py:39
 msgid "Zero value means no timeout."
-msgstr "Keine Zeitüberschreitung bei Nullwert"
+msgstr "Keine Zeitbeschränkung bei Nullwert"
 
 #: models.py:40
 msgid "maximum allowed clicks"

dynamicLink/models.py

 import random
 import os
 import datetime
-from django.utils import timezone
+try:
+    from django.utils import timezone
+except ImportError as e:
+    from django import VERSION
+    if VERSION < (1, 4):  # there is no timezone in Django < 1.4
+        from datetime import datetime as timezone
+    else:
+        raise ImportError(e)
+
 
 class Download(models.Model):
     slug = models.SlugField(verbose_name=_('slug'), blank=False, unique=True)
                                  verbose_name=_(u'is aktive'),
                                  )
     file_path = models.FilePathField(
-                                      path=presettings.DYNAMIC_LINK_MEDIA,
-                                      help_text=_(u"Select the content your like \
-                                      to provide."),
-                                      verbose_name=_(u'content to serve'),
-                                      blank=True,
-                                      recursive=True
+                                  path=presettings.DYNAMIC_LINK_MEDIA,
+                                  help_text=_(u"Select the content your like \
+                                  to provide."),
+                                  verbose_name=_(u'content to serve'),
+                                  blank=True,
+                                  recursive=True
                                       )
     link_key = models.CharField(max_length=50, editable=False, unique=True)
     timestamp_creation = models.DateTimeField(
                                               editable=False,
                                               verbose_name=_(u'creation time'),
                                               )
-    timeout_hours = models.IntegerField(verbose_name=_(u'timout in hours'), \
-                                        default=72, help_text=_('Zero value means no timeout.'))
-    max_clicks = models.IntegerField(verbose_name=_(u'maximum allowed clicks'), \
-                                     default=3, help_text=_('Zero value means no limitation.'))
-    current_clicks = models.IntegerField(default=0, verbose_name=_(u'current clicks'))
+    timeout_hours = models.IntegerField(
+                                    verbose_name=_(u'timout in hours'),
+                                    default=72,
+                                    help_text=_('Zero value means no timeout.')
+                                        )
+    max_clicks = models.IntegerField(
+                                 verbose_name=_(u'maximum allowed clicks'),
+                                 default=3,
+                                 help_text=_('Zero value means no limitation.')
+                                     )
+    current_clicks = models.IntegerField(
+                                         default=0,
+                                         verbose_name=_(u'current clicks')
+                                         )
 
     def get_filename(self):
         return os.path.basename(self.file_path)
 
     def timeout_clicks(self):
         """If max clicks reached than it returns True"""
-        # dont cange the order
-        if not self.max_clicks == 0: # max clicks 0 means never expired through clicks
-            if self.current_clicks >= self.max_clicks: # if number of max clicks reached
+        # max clicks == 0 means it will never expired through clicks
+        if not self.max_clicks == 0:
+            if self.current_clicks >= self.max_clicks:  # if clicks reached
                 return True
 
     def timeout_time(self):
-        """If timout time is reached it returs True"""
-        if not self.timeout_hours == 0: # never timeout through time
-            if self.timestamp_creation + datetime.timedelta(hours=self.timeout_hours) < timezone.now():
+        """If timeout time is reached it returns True"""
+        if not self.timeout_hours == 0:  # never timeout through time
+            if self.timestamp_creation + datetime.timedelta(
+                                    hours=self.timeout_hours) < timezone.now():
                 return True
 
     def timeout(self):
     def get_timout_time(self):
         """Is shown at the admit list display"""
         if self.timeout_hours == 0:
-            return '<span style="color: #FF7F00; ">%s</span>' % unicode(_(u'never expires'))
-        return (self.timestamp_creation + datetime.timedelta(hours=self.timeout_hours)) - timezone.now()
+            return '<span style="color: #FF7F00; ">%s</span>' \
+                % unicode(_(u'never expires'))
+        return (self.timestamp_creation + \
+                datetime.timedelta(hours=self.timeout_hours)) - timezone.now()
 
-    def set_link(self, file, slug='autogenerated', timeout=None, maxclicks=None):
+    def set_link(self, file, slug='autogenerated',
+                 timeout=None, maxclicks=None):
         self.slug = slug
         self.file_path = file.split(os.path.basename(settings.MEDIA_ROOT))[-1]
         if timeout:
         Check if object instance expired and keep values of the istance actual.
         """
         # Keep the order of the tests
-        
+
         # 1. Test of timeout
         if self.timeout():
             if self.active:
         # 2. set max click values
         if self.current_clicks < self.max_clicks:
             self.current_clicks += 1
-            # check of last cklick
+            # check of last click
             if self.current_clicks == self.max_clicks:
-                self.active = False # if it was the last allowed cklick then set to expired
+                # if it was the last allowed click then set to expired
+                self.active = False
             self.save()
         elif self.max_clicks == 0:
             self.current_clicks += 1
         """
         function for generating random keys
         """
-        #key = str(time.time()).replace('.', '')
-        key = '' # for shorter keys
+        # key = str(time.time()).replace('.', '')
+        key = ''  # for shorter keys
         characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'
         key_length = 30
         for y in range(key_length):
-            key += characters[random.randint(0, len(characters)-1)]
+            key += characters[random.randint(0, len(characters) - 1)]
         return key
 
     def save(self, * args, ** kwargs):
         if not self.link_key:
             self.link_key = self.__gen_key()
         # call the real save method
-        super(Download, self).save(*args, ** kwargs) # Call the "real" save() method
+        super(Download, self).save(*args, ** kwargs)
 
     def __unicode__(self):
-        return '%s: %s, %s: %s' % (unicode(_(u'Slug')), self.slug, unicode(_(u'Filename')), self.get_filename())
+        return '%s: %s, %s: %s' % (
+                                   unicode(_(u'Slug')),
+                                   self.slug, unicode(_(u'Filename')),
+                                   self.get_filename()
+                                   )
+
 
 class IsExpiredError(Exception):
     """Error class for expired link objects"""
     def __init__(self, value=''):
         self.value = presettings.TEXT_REQUEST_IS_EXPIRED + value
+
     def __str__(self):
         return repr(self.value)

dynamicLink/presettings.py

 from django.conf import settings
 from django.utils.translation import ugettext_lazy as _
 
-# This file holds the presettings of the app. 
+# This file holds the pre-settings of the application.
 
 # A path to a directory from witch walk down so you can choose your files.
-DYNAMIC_LINK_MEDIA = getattr(settings, 'DYNAMIC_LINK_MEDIA', settings.MEDIA_ROOT)
+DYNAMIC_LINK_MEDIA = getattr(
+                             settings,
+                             'DYNAMIC_LINK_MEDIA',
+                             settings.MEDIA_ROOT
+                             )
 
 # A string that modify the serve url path:
 # /www.example.com/DYNAMIC_LINK_URL_BASE_COMPONENT/link/3839hd8HKl3/example.zip
-DYNAMIC_LINK_URL_BASE_COMPONENT = getattr(settings, 'DYNAMIC_LINK_URL_BASE_COMPONENT', 'serve')
+DYNAMIC_LINK_URL_BASE_COMPONENT = getattr(
+                                          settings,
+                                          'DYNAMIC_LINK_URL_BASE_COMPONENT',
+                                          'serve'
+                                          )
 
 # It's here because of not violate the DRY priciple.
 TEXT_REQUEST_DOES_NOT_EXIST = _(u'This request is faulty')
-TEXT_REQUEST_IS_EXPIRED = _(u'Sorry, this request is already expired')
+TEXT_REQUEST_IS_EXPIRED = _(u'Sorry, this request is already expired')

dynamicLink/tests.py

 from models import Download
 from api import DynamicLink
 
+
 class Obj:
     pass
 
+
 class DownloadTestCase(unittest.TestCase):
     """Test of the Doanload modell"""
     def setUp(self):
         self.downl = Download.objects.create(
                               slug='download_model_unittest',
                               file_path=self.path,
-                              timeout_hours = 10,
-                              max_clicks = 10,
+                              timeout_hours=10,
+                              max_clicks=10,
                               )
 
     def test_download_methodes(self):
-        self.assertEqual(self.downl.get_filename(), 
+        self.assertEqual(self.downl.get_filename(),
                         self.file,
                         )
         self.assertFalse(self.downl.timeout_clicks())
         self.assertFalse(self.downl.timeout_time())
         self.assertFalse(self.downl.timeout())
         self.assertEqual(self.downl.get_path(), self.path)
-    
+
+
 class DynamicLinkTestCase(unittest.TestCase):
     """Test the DynamicLink API"""
     def setUp(self):
         self.dlink = DynamicLink(
                       slug='api_unittest',
                       file_path=self.path,
-                      timeout_hours = 10,
-                      max_clicks = 10,
+                      timeout_hours=10,
+                      max_clicks=10,
                       )
 
     def test_dynamic_link_methodes(self):
         request = Obj()
-        request.__dict__['META']={}
-        request.META['HTTP_HOST']='www.testrunner.eu'
+        request.__dict__['META'] = {}
+        request.META['HTTP_HOST'] = 'www.testrunner.eu'
         link = '%s/%s/%s/%s/%s' % ('http://www.testrunner.eu',
                                 'lg',
                                 'serve/link',
                                 self.file,
                                 )
         self.assertEqual(link, self.dlink.get_link_url(request))
-        

dynamicLink/version.py

 # -*- coding:utf-8 -*-
 # This Python file uses the following encoding: utf-8
 
-VERSION = (0,5,6,2)
-RELEASE_DJANGO = ((1,2),(1,3),(1,4))
-PYTHON_MIN = (2,4)
-REQUIRES ="""
+VERSION = (0, 5, 7, 0)
+RELEASE_DJANGO = ((1, 2), (1, 3), (1, 4))
+PYTHON_MIN = (2, 4)
+REQUIRES = """
 django-dynamic-link 0.5.5 => Django 1.2, 1.3 :: Python >= 2.4 :: Example project: Django 1.3
 django-dynamic-link 0.6.x => Django 1.2, 1.3, 1.4(Python 2.5) :: Python >= 2.4 :: Example project: Django 1.4, Python 2.5
 
 """
 
 APPLICATION_NAME = "Dynamic Link"
-VERSION_str = str(VERSION[:3]).strip('()').replace(',','.').replace(' ','')
+VERSION_str = str(VERSION[:3]).strip('()').replace(',', '.').replace(' ', '')
 VERSION_INFO = """
 Version: %s
 Modification date: 03.08.2011
 
 Hints:
 - 0.5.6.2   settings.py in example project modified. Now it should work correct with Django 1.4
-- 0.5.6.1   Timezone bug changes
+- 0.5.6.1   Time zone bug changes
 - 0.5.6     Example Project runs with Django 1.4
 - 0.5.5     dynamicLink.CKISNT() function added.
-- 0.5.4.1   Canges in setup.py - READM will now alsow be installed. Now if a package
+- 0.5.4.1   Changes in setup.py - READM will now also be installed. Now if a package
             is installed than help(dynamicLink) outputs the README.
 - 0.5.4     Bugfix: Installation failed on Windows in spite of "/" on the end
             of recursive-include in MANIFEST. 
-            Now canged from "recursive-include folder/ *" to "recursive-include folder *"
+            Now changed from "recursive-include folder/ *" to "recursive-include folder *"
 - 0.5.3     New stable release with updated readme.
 - 0.5.2.2   structure of repository changed - src folder removed so readme is
-            on the toplevel
+            on the top level
 - 0.5.2.1   In templates sentences changed.
-- 0.5.2     stable - general django dependences in setup removed
+- 0.5.2     stable - general Django dependences in setup removed
 - 0.5.1     new stable
 - 0.5.0.2   some text in templates changed
 - 0.5.0.1   correct readme and example settings.py
 - 0.4.9.4   install_requires in setup.py modified
 - 0.4.9.3   old data removed
 - 0.4.9.2   dl_settings removed
-- 0.4.9.1   Readme updatet
-- 0.4.9     Testet with Django 1.2 u. 1.3
+- 0.4.9.1   Readme updated
+- 0.4.9     Tested with Django 1.2 u. 1.3
 - 0.4.8.4   Some small changes
 - 0.4.8.3   Some small changes
 - 0.4.8     Runs now under Django 1.3
-- 0.4.7   - Preesettings can now be overwrite in the presettings.py in the project
+- 0.4.7   - Presettings can now be overwrite in the presettings.py in the project
             folder, or directly in the global settings.py, or in a file
             called dl_settings.py in the same directory as manage.py.
             - django-dynamic-link now runs with python below version 2.6
             2. Readme updated.
             3. Example project added.
 - 0.4.3 -   ImportError in admin.py solved.
-- 0.4.2 -   setup.py createtd. Now listed in pypi.
+- 0.4.2 -   setup.py created. Now listed in pypi.
 - 0.4.1 -   Remove small bug with links created with the action menu.
 
 TODO:

dynamicLink/views.py

 __author__ = "Andreas Fritz - sources.e-blue.eu"
 __copyright__ = "Copyright (c) " + "28.08.2010" + " Andreas Fritz"
 __licence__ = """New BSD Licence"""
-__doc__ = """Dynamic donload links with timeout and maximum rate of ckicks.
-The content will served by a stream. Path of the file on the system is covered
-through the dynamicly generated pathname in the url.py """
 
 import os
 import presettings
         if key == obj.link_key:
             return obj
 
+
 def active(key):
     active_objects = Download.objects.filter(active=True)
     # check active objects
         if key == obj.link_key:
             return obj
 
-def error(request, text=_(u'Sorry, your request is mot available')):
+
+def error(request, text=_(u'Sorry, your request is not available')):
     """returns the error page"""
     extra_context = {'message': text}
     template = 'dynamicLink/not_avallible.html'
-    return render_to_response(template, extra_context, context_instance=RequestContext(request))
+    return render_to_response(
+                              template, extra_context,
+                              context_instance=RequestContext(request)
+                              )
+
 
 def site(request, offset):
     """process site requests"""
-    offset = offset.split('-') # turn offset to keylist
-    obj = {'actives':[], 'expired':[], 'notexist':[]}
+    offset = offset.split('-')  # turn offset to keylist
+    obj = {'actives': [], 'expired': [], 'notexist': []}
+
     # Test if keys are valid
     for key in offset:
         if active(key):
             obj['expired'].append(expired(key))
         else:
             obj['notexist'].append(key)
+
     template = 'dynamicLink/provide.html'
-    extra_context = {'basepath': presettings.DYNAMIC_LINK_URL_BASE_COMPONENT, 'downloads':obj}
-    return render_to_response(template, extra_context, context_instance=RequestContext(request))
+    extra_context = {
+                     'basepath': presettings.DYNAMIC_LINK_URL_BASE_COMPONENT,
+                     'downloads': obj
+                     }
+    return render_to_response(
+                              template,
+                              extra_context,
+                              context_instance=RequestContext(request)
+                              )
+
 
 def fetch(request, offset):
     """process link requests. make desissions for every single download link"""
     else:
         return error(request, presettings.TEXT_REQUEST_DOES_NOT_EXIST)
 
+
 @cache_control(private=True)
 def provide(request, key):
     """
-    Return a download without the rael path to the served file. The content will
-    served by a stream.
+    Return a download without the rael path to the served file.
+    The content will served by a stream.
 
-    The file will read in byte code to a socket wich will be used in the response
-    object. Headers in the response will set for the specific served content
-    referable to its type.
+    The file will read in byte code to a socket wich will be
+    used in the response object. Headers in the response will
+    set for the specific served content referable to its type.
     """
     # Read database
-    # This code runs only with python >= 2.6
-#    stored_file_obj = Download.objects.get(link_key=key)
-#    try:
-#        filepath = stored_file_obj.get_path() # model method to validate and deliver path
-#    except IsExpiredError as e: # works only with python 2.6 or later (for a solution of older versions see below!)
-#        return error(request, e.value)
+
+#     # This code runs only with python >= 2.6
+#     stored_file_obj = Download.objects.get(link_key=key)
+#     try:
+#         # we use a model method to validate and
+#         # deliver the path
+#         filepath = stored_file_obj.get_path()
+#     except IsExpiredError as e:
+#         return error(request, e.value)
 
     # alternate code that also run in older python before 2.6
     stored_file_obj = Download.objects.get(link_key=key)
     try:
-        filepath = stored_file_obj.get_path() # model method to validate and deliver path
-    except IsExpiredError: # works with pyhton before 2.6
+        # we use a model method to validate and
+        # deliver the path
+        filepath = stored_file_obj.get_path()
+    except IsExpiredError:
         return error(request)
-    
+
     # make file path suitable for different installations
     delimiter = presettings.DYNAMIC_LINK_MEDIA.strip('/').split('/')[-1]
-    # now we use the objects get_paht() method to be sure the object instance keep up to date.
-    file_path = os.path.normpath(presettings.DYNAMIC_LINK_MEDIA + '/' + filepath.split(delimiter)[-1])
+    # now we use the objects get_paht() method to be sure
+    # the object instance keep up to date.
+    file_path = os.path.normpath(
+        presettings.DYNAMIC_LINK_MEDIA + '/' + filepath.split(delimiter)[-1]
+                                )
 
     # read file as binary
     try:
-        fsocket = open(file_path, 'rb') # garbage collector will deal with not closed fsocket
+        fsocket = open(file_path, 'rb')  # garbage collector will deal with
+        # not closed fsocket
     except IOError:
         stored_file_obj.active = False
-        stored_file_obj.save() # only raise the following once
-        return HttpResponseNotFound(unicode(_(u'File not found!'))) # admin will get informed by mail
+        stored_file_obj.save()  # only raise the following once
+        return HttpResponseNotFound(unicode(_(u'File not found!')))  # admin
+        # will get informed by mail
 
-#    # read file as binary
-#    try:
-#        f = open(file_path, 'rb')
-#    except IOError:
-#        stored_file_obj.active = False
-#        stored_file_obj.save() # only raise the following once
-#        return HttpResponseNotFound(unicode(_(u'File not found!'))) # admin will get informed by mail
-#    fsocket = f.read()
-#    f.close()
+#     # read file as binary
+#     try:
+#         f = open(file_path, 'rb')
+#     except IOError:
+#         stored_file_obj.active = False
+#         stored_file_obj.save()  # only raise the following once
+#         return HttpResponseNotFound(unicode(_(u'File not found!')))  # admin
+#         # will get informed by mail
+#     fsocket = f.read()
+#     f.close()
 
     # get file parameters
     file_name = os.path.basename(file_path)
 
     # specify mimetype and encoding
     auto_mimetype, auto_encoding = mimetypes.guess_type(file_path)
-    if not auto_mimetype: # for unknown types use stream
+    if not auto_mimetype:  # for unknown types use stream
         auto_mimetype = 'application/octet-stream'
 
     # response object
-    response = HttpResponse(fsocket, mimetype=auto_mimetype) # object instance with mimetype and file
+    response = HttpResponse(fsocket, mimetype=auto_mimetype)  # object instance
+    # with mimetype and file
+
     # set headers in the response object
-    # a list of headers: http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
-    # encode('utf-8') assuming you're running on a server with UTF-8 as the filesystem encoding.
-    response['Content-Disposition'] = 'attachment; filename=%s' % file_name.encode('utf-8') # add correct filename
+    # a list of headers:
+    # http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
+    # encode('utf-8') assuming you're running on a server with UTF-8 as
+    # the file system encoding.
+    response['Content-Disposition'] = 'attachment; filename=%s' \
+            % file_name.encode('utf-8')  # add correct filename
+
     if auto_encoding and auto_encoding is not 'gzip':
         # set encoding but exclude gzip from encoding headers
-        # GZip uses zlib, but on its own zlib produces content that's improperly
-        # encoded for a browser seeing 'gzip' as the content encoding.
+        # GZip uses zlib, but on its own zlib produces content that's
+        # improperly encoded for a browser seeing 'gzip' as the content
+        # encoding.
         response['Content-Encoding'] = auto_encoding
-    response['Content-Length'] = file_size # set response file size for the browsers progress bar
-    
+    # set response file size for the browsers progress bar
+    response['Content-Length'] = file_size
+
     return response
 from setuptools import setup, find_packages
 from dynamicLink import version
 import os
-#import sys
+# import sys
 import shutil
 
 
     # set requierment only if django not avallible.
     REQUIRES.append('django')
 
-#if sys.version_info < (2, 4):
+# if sys.version_info < (2, 4):
 #    REQUIRES.append('python >= 2.4')
 
 
         long_description=long_description,
         author='Andreas Fritz',
         author_email='djangp-dynamic-link@bitzeit.eu',
-        url='http://www.sources.e-blue.eu/de/pages/django/',
+        url='http://www.sources.e-blue.eu/en/pages/django/',
         download_url='https://bitbucket.org/catapela/django-dynamic-link/downloads',
         license='BSD',
-        packages=find_packages(exclude=['example',]),
+        packages=find_packages(exclude=['example', ]),
         include_package_data=True,
         keywords="django file streaming dynamic links serve",
         classifiers=[
-              'Development Status :: 4 - Beta',
+              'Development Status :: 5 - Production/Stable',
               'Framework :: Django',
               'License :: OSI Approved :: BSD License',
               'Operating System :: OS Independent',
               'Intended Audience :: Developers',
               'Topic :: Internet',
               ],
-        install_requires = REQUIRES,
+        install_requires=REQUIRES,
         zip_safe=False,
         )