Making zip file with custom content per user

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
2
down vote

favorite












What I tried to do:



  1. In my main project folder I have directory downloadable_app with these files/folders inside:

    • index.html

    • js/app.f54b97d7097bcf4226c0.js


  2. I need to allow users to download this downloadable_app folder as zip archive

  3. In app.f54b97d7097bcf4226c0.js file I have axios.defaults.headers.common['Authorization'] = 'Bearer <BEARER_TOKEN>'

  4. I need to replace <BEARER_TOKEN> by request.user token

This is how I did this:



settings.py:



PROJECT_PATH = os.path.abspath(os.path.dirname(__name__))
DOWNLOADABLE_APP_ROOT = os.path.join(PROJECT_PATH, 'downloadable_app')


views.py:



import datetime
import binascii
import os
from datetime import timedelta
import shutil
...

from oauth2_provider.models import Application, AccessToken


class DownloadAppView(LoginRequiredMixin, View):
def dispatch(self, request, *args, **kwargs):
if not self.request.user.plan:
raise Http404
self.token = self._get_or_create_user_token()
return super(DownloadAppView, self).dispatch(
request, *args, **kwargs)

def _add_token_to_downloadable_app(self, token):
with open(os.path.join(settings.DOWNLOADABLE_APP_ROOT, 'js/app.f54b97d7097bcf4226c0.js'), 'r') as file:
filedata = file.read()

filedata = filedata.replace('<BEARER_TOKEN>', token)

with open(os.path.join(settings.DOWNLOADABLE_APP_ROOT, 'js/app.f54b97d7097bcf4226c0.js'), 'w') as file:
file.write(filedata)

def _reset_token_in_downloadable_app(self, token):
with open(os.path.join(settings.DOWNLOADABLE_APP_ROOT, 'js/app.f54b97d7097bcf4226c0.js'), 'r') as file:
filedata = file.read()

filedata = filedata.replace(token, '<BEARER_TOKEN>')

with open(os.path.join(settings.DOWNLOADABLE_APP_ROOT, 'js/app.f54b97d7097bcf4226c0.js'), 'w') as file:
file.write(filedata)

def _get_or_create_user_token(self):
app, created = Application.objects.get_or_create(
client_type=Application.CLIENT_CONFIDENTIAL,
authorization_grant_type=Application.GRANT_CLIENT_CREDENTIALS,
redirect_uris='https://www.example.com/',
name='downloadable_app',
user=User.objects.filter(is_superuser=True, is_staff=True).first()
)
access_token, created = AccessToken.objects.get_or_create(
user=self.request.user,
scope='read write',
application=app,
defaults='expires': timezone.now() + timedelta(days=1000), 'token': binascii.hexlify(os.urandom(20)).decode()
)
return access_token.token

def get(self, request):
self._add_token_to_downloadable_app(self.token)

# create_zip_archive
shutil.make_archive('downloadable_app_archives/my_app_'.format(request.user.pk), 'zip', settings.DOWNLOADABLE_APP_ROOT)
response = HttpResponse(
open(os.path.join(
settings.PROJECT_PATH, 'downloadable_app_archives/my_app_.zip'.format(request.user.pk)), 'rb').read(), content_type='application/zip')
self._reset_token_in_downloadable_app(self.token)
return response


management.commands.delete_zip_archives.py:



class Command(BaseCommand):
help = 'Delete downloadable app zip archives'

def handle(self, *args, **options):
shutil.rmtree(os.path.join(settings.PROJECT_PATH, 'downloadable_app_archives'))


Can you please take a look and let me know how can I improve this?







share|improve this question

























    up vote
    2
    down vote

    favorite












    What I tried to do:



    1. In my main project folder I have directory downloadable_app with these files/folders inside:

      • index.html

      • js/app.f54b97d7097bcf4226c0.js


    2. I need to allow users to download this downloadable_app folder as zip archive

    3. In app.f54b97d7097bcf4226c0.js file I have axios.defaults.headers.common['Authorization'] = 'Bearer <BEARER_TOKEN>'

    4. I need to replace <BEARER_TOKEN> by request.user token

    This is how I did this:



    settings.py:



    PROJECT_PATH = os.path.abspath(os.path.dirname(__name__))
    DOWNLOADABLE_APP_ROOT = os.path.join(PROJECT_PATH, 'downloadable_app')


    views.py:



    import datetime
    import binascii
    import os
    from datetime import timedelta
    import shutil
    ...

    from oauth2_provider.models import Application, AccessToken


    class DownloadAppView(LoginRequiredMixin, View):
    def dispatch(self, request, *args, **kwargs):
    if not self.request.user.plan:
    raise Http404
    self.token = self._get_or_create_user_token()
    return super(DownloadAppView, self).dispatch(
    request, *args, **kwargs)

    def _add_token_to_downloadable_app(self, token):
    with open(os.path.join(settings.DOWNLOADABLE_APP_ROOT, 'js/app.f54b97d7097bcf4226c0.js'), 'r') as file:
    filedata = file.read()

    filedata = filedata.replace('<BEARER_TOKEN>', token)

    with open(os.path.join(settings.DOWNLOADABLE_APP_ROOT, 'js/app.f54b97d7097bcf4226c0.js'), 'w') as file:
    file.write(filedata)

    def _reset_token_in_downloadable_app(self, token):
    with open(os.path.join(settings.DOWNLOADABLE_APP_ROOT, 'js/app.f54b97d7097bcf4226c0.js'), 'r') as file:
    filedata = file.read()

    filedata = filedata.replace(token, '<BEARER_TOKEN>')

    with open(os.path.join(settings.DOWNLOADABLE_APP_ROOT, 'js/app.f54b97d7097bcf4226c0.js'), 'w') as file:
    file.write(filedata)

    def _get_or_create_user_token(self):
    app, created = Application.objects.get_or_create(
    client_type=Application.CLIENT_CONFIDENTIAL,
    authorization_grant_type=Application.GRANT_CLIENT_CREDENTIALS,
    redirect_uris='https://www.example.com/',
    name='downloadable_app',
    user=User.objects.filter(is_superuser=True, is_staff=True).first()
    )
    access_token, created = AccessToken.objects.get_or_create(
    user=self.request.user,
    scope='read write',
    application=app,
    defaults='expires': timezone.now() + timedelta(days=1000), 'token': binascii.hexlify(os.urandom(20)).decode()
    )
    return access_token.token

    def get(self, request):
    self._add_token_to_downloadable_app(self.token)

    # create_zip_archive
    shutil.make_archive('downloadable_app_archives/my_app_'.format(request.user.pk), 'zip', settings.DOWNLOADABLE_APP_ROOT)
    response = HttpResponse(
    open(os.path.join(
    settings.PROJECT_PATH, 'downloadable_app_archives/my_app_.zip'.format(request.user.pk)), 'rb').read(), content_type='application/zip')
    self._reset_token_in_downloadable_app(self.token)
    return response


    management.commands.delete_zip_archives.py:



    class Command(BaseCommand):
    help = 'Delete downloadable app zip archives'

    def handle(self, *args, **options):
    shutil.rmtree(os.path.join(settings.PROJECT_PATH, 'downloadable_app_archives'))


    Can you please take a look and let me know how can I improve this?







    share|improve this question





















      up vote
      2
      down vote

      favorite









      up vote
      2
      down vote

      favorite











      What I tried to do:



      1. In my main project folder I have directory downloadable_app with these files/folders inside:

        • index.html

        • js/app.f54b97d7097bcf4226c0.js


      2. I need to allow users to download this downloadable_app folder as zip archive

      3. In app.f54b97d7097bcf4226c0.js file I have axios.defaults.headers.common['Authorization'] = 'Bearer <BEARER_TOKEN>'

      4. I need to replace <BEARER_TOKEN> by request.user token

      This is how I did this:



      settings.py:



      PROJECT_PATH = os.path.abspath(os.path.dirname(__name__))
      DOWNLOADABLE_APP_ROOT = os.path.join(PROJECT_PATH, 'downloadable_app')


      views.py:



      import datetime
      import binascii
      import os
      from datetime import timedelta
      import shutil
      ...

      from oauth2_provider.models import Application, AccessToken


      class DownloadAppView(LoginRequiredMixin, View):
      def dispatch(self, request, *args, **kwargs):
      if not self.request.user.plan:
      raise Http404
      self.token = self._get_or_create_user_token()
      return super(DownloadAppView, self).dispatch(
      request, *args, **kwargs)

      def _add_token_to_downloadable_app(self, token):
      with open(os.path.join(settings.DOWNLOADABLE_APP_ROOT, 'js/app.f54b97d7097bcf4226c0.js'), 'r') as file:
      filedata = file.read()

      filedata = filedata.replace('<BEARER_TOKEN>', token)

      with open(os.path.join(settings.DOWNLOADABLE_APP_ROOT, 'js/app.f54b97d7097bcf4226c0.js'), 'w') as file:
      file.write(filedata)

      def _reset_token_in_downloadable_app(self, token):
      with open(os.path.join(settings.DOWNLOADABLE_APP_ROOT, 'js/app.f54b97d7097bcf4226c0.js'), 'r') as file:
      filedata = file.read()

      filedata = filedata.replace(token, '<BEARER_TOKEN>')

      with open(os.path.join(settings.DOWNLOADABLE_APP_ROOT, 'js/app.f54b97d7097bcf4226c0.js'), 'w') as file:
      file.write(filedata)

      def _get_or_create_user_token(self):
      app, created = Application.objects.get_or_create(
      client_type=Application.CLIENT_CONFIDENTIAL,
      authorization_grant_type=Application.GRANT_CLIENT_CREDENTIALS,
      redirect_uris='https://www.example.com/',
      name='downloadable_app',
      user=User.objects.filter(is_superuser=True, is_staff=True).first()
      )
      access_token, created = AccessToken.objects.get_or_create(
      user=self.request.user,
      scope='read write',
      application=app,
      defaults='expires': timezone.now() + timedelta(days=1000), 'token': binascii.hexlify(os.urandom(20)).decode()
      )
      return access_token.token

      def get(self, request):
      self._add_token_to_downloadable_app(self.token)

      # create_zip_archive
      shutil.make_archive('downloadable_app_archives/my_app_'.format(request.user.pk), 'zip', settings.DOWNLOADABLE_APP_ROOT)
      response = HttpResponse(
      open(os.path.join(
      settings.PROJECT_PATH, 'downloadable_app_archives/my_app_.zip'.format(request.user.pk)), 'rb').read(), content_type='application/zip')
      self._reset_token_in_downloadable_app(self.token)
      return response


      management.commands.delete_zip_archives.py:



      class Command(BaseCommand):
      help = 'Delete downloadable app zip archives'

      def handle(self, *args, **options):
      shutil.rmtree(os.path.join(settings.PROJECT_PATH, 'downloadable_app_archives'))


      Can you please take a look and let me know how can I improve this?







      share|improve this question











      What I tried to do:



      1. In my main project folder I have directory downloadable_app with these files/folders inside:

        • index.html

        • js/app.f54b97d7097bcf4226c0.js


      2. I need to allow users to download this downloadable_app folder as zip archive

      3. In app.f54b97d7097bcf4226c0.js file I have axios.defaults.headers.common['Authorization'] = 'Bearer <BEARER_TOKEN>'

      4. I need to replace <BEARER_TOKEN> by request.user token

      This is how I did this:



      settings.py:



      PROJECT_PATH = os.path.abspath(os.path.dirname(__name__))
      DOWNLOADABLE_APP_ROOT = os.path.join(PROJECT_PATH, 'downloadable_app')


      views.py:



      import datetime
      import binascii
      import os
      from datetime import timedelta
      import shutil
      ...

      from oauth2_provider.models import Application, AccessToken


      class DownloadAppView(LoginRequiredMixin, View):
      def dispatch(self, request, *args, **kwargs):
      if not self.request.user.plan:
      raise Http404
      self.token = self._get_or_create_user_token()
      return super(DownloadAppView, self).dispatch(
      request, *args, **kwargs)

      def _add_token_to_downloadable_app(self, token):
      with open(os.path.join(settings.DOWNLOADABLE_APP_ROOT, 'js/app.f54b97d7097bcf4226c0.js'), 'r') as file:
      filedata = file.read()

      filedata = filedata.replace('<BEARER_TOKEN>', token)

      with open(os.path.join(settings.DOWNLOADABLE_APP_ROOT, 'js/app.f54b97d7097bcf4226c0.js'), 'w') as file:
      file.write(filedata)

      def _reset_token_in_downloadable_app(self, token):
      with open(os.path.join(settings.DOWNLOADABLE_APP_ROOT, 'js/app.f54b97d7097bcf4226c0.js'), 'r') as file:
      filedata = file.read()

      filedata = filedata.replace(token, '<BEARER_TOKEN>')

      with open(os.path.join(settings.DOWNLOADABLE_APP_ROOT, 'js/app.f54b97d7097bcf4226c0.js'), 'w') as file:
      file.write(filedata)

      def _get_or_create_user_token(self):
      app, created = Application.objects.get_or_create(
      client_type=Application.CLIENT_CONFIDENTIAL,
      authorization_grant_type=Application.GRANT_CLIENT_CREDENTIALS,
      redirect_uris='https://www.example.com/',
      name='downloadable_app',
      user=User.objects.filter(is_superuser=True, is_staff=True).first()
      )
      access_token, created = AccessToken.objects.get_or_create(
      user=self.request.user,
      scope='read write',
      application=app,
      defaults='expires': timezone.now() + timedelta(days=1000), 'token': binascii.hexlify(os.urandom(20)).decode()
      )
      return access_token.token

      def get(self, request):
      self._add_token_to_downloadable_app(self.token)

      # create_zip_archive
      shutil.make_archive('downloadable_app_archives/my_app_'.format(request.user.pk), 'zip', settings.DOWNLOADABLE_APP_ROOT)
      response = HttpResponse(
      open(os.path.join(
      settings.PROJECT_PATH, 'downloadable_app_archives/my_app_.zip'.format(request.user.pk)), 'rb').read(), content_type='application/zip')
      self._reset_token_in_downloadable_app(self.token)
      return response


      management.commands.delete_zip_archives.py:



      class Command(BaseCommand):
      help = 'Delete downloadable app zip archives'

      def handle(self, *args, **options):
      shutil.rmtree(os.path.join(settings.PROJECT_PATH, 'downloadable_app_archives'))


      Can you please take a look and let me know how can I improve this?









      share|improve this question










      share|improve this question




      share|improve this question









      asked May 9 at 16:51









      paul

      111




      111

























          active

          oldest

          votes











          Your Answer




          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          );
          );
          , "mathjax-editing");

          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: false,
          noModals: false,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );








           

          draft saved


          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f194027%2fmaking-zip-file-with-custom-content-per-user%23new-answer', 'question_page');

          );

          Post as a guest



































          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes










           

          draft saved


          draft discarded


























           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f194027%2fmaking-zip-file-with-custom-content-per-user%23new-answer', 'question_page');

          );

          Post as a guest













































































          Popular posts from this blog

          Chat program with C++ and SFML

          Function to Return a JSON Like Objects Using VBA Collections and Arrays

          Will my employers contract hold up in court?