コード例 #1
0
ファイル: track.py プロジェクト: AnneGilles/c3sar
def track_add(request):

    viewer_username = authenticated_userid(request)
#    if hasattr(request, user):
#        viewer_username = request.user.username
    if viewer_username == "":  # pragma: no cover
        viewer_username = "******"

    form = Form(request, TrackSchema)

    if DEBUG:  # pragma: no cover
        if 'form.submitted' in request.POST:
            if 'track_name' in form.data:
                print "track_name : " + form.data['track_name']
            if 'track_album' in form.data:
                print "track_album: " + form.data['track_album']
            if 'track_url' in form.data:
                print "track_url  : " + form.data['track_url']
            if 'track_upload' in form.data:
                print "track_upload : " + form.data['track_upload']
                print "track_upload.filename : "
                + form.data['track_upload'].filename
                print "track_upload.file : "
                + form.data['track_upload'].file

    if 'form.submitted' in request.POST and not form.validate():
        # form didn't validate
        request.session.flash('form does not validate!')

    if 'form.submitted' in request.POST and form.validate():
        request.session.flash('form validated!')

        # some defaults
        file_path = ''           # where the file is stored (incl. name)
        output_file_size = None  # the size of the file

        if DEBUG:  # pragma: no cover
            print "---- form.data: ----"
            pp.pprint(form.data)
            print "---- request.POST['track_file']: ----"
            if 'track_upload' in request.POST:
                pp.pprint(request.POST['track_upload'])
                pp.pprint(request.POST['track_upload'].filename)
                pp.pprint(request.POST['track_upload'].file)
#request.POST['track_upload']    FieldStorage(u'track_upload', u'blahblah.mp3')
#request.POST['track_upload'].filename                          u'blahblah.mp3'
#request.POST['track_upload'].file    <open file '<fdopen>', mode 'w+b' at ...>
            else:
                print "no 'track_upload' in request.POST"

        # check if the form contained a file and if yes....
        if 'track_upload' in form.data and form.data['track_upload'] != '':

            # https://docs.pylonsproject.org/projects/
            #           pyramid_cookbook/dev/files.html#basic-file-uploads
            #
            # ``filename`` contains the name of the file in string format.
            #
            #WARNING: this example does not deal with the fact that IE sends an
            # absolute file *path* as the filename.  This example is naive; it
            # trusts user input.

            file_name = sanitize_filename(
                request.POST['track_upload'].filename)

            # ``input_file`` contains the actual file data which needs to be
            # stored somewhere.

            input_file = request.POST['track_upload'].file

            # Using the filename like this without cleaning it is very
            # insecure so please keep that in mind when writing your own
            # file handling. TODO !!!

            if DEBUG:  # pragma: no cover
                print "=== current working dir: " + os.path.abspath('.')
                print "=== upload target dir: " + os.path.abspath('tracks')

            # prepare to save the file
            the_cwd = os.path.abspath('.')
            file_dir = os.path.join(the_cwd, 'tracks')

            # create a directory for tracks on the filesystem
            if not os.path.exists(file_dir):
                os.makedirs(file_dir)  # pragma: no cover

            file_path = os.path.join(file_dir, file_name)

            try:
                output_file = open(file_path, 'wb')

                # Finally write the data to the output file
                input_file.seek(0)
                while True:
                    data = input_file.read(8192)
                    if not data:
                        break
                    output_file.write(data)

                # determining filesize
                output_file_size = os.path.getsize(file_path)

                output_file.close()

                request.session.flash('file was saved')
                # return Response('OK')
            except IOError, ioerr:  # pragma: no cover
                print "==== got an error ===="
                print ioerr
                print "something failed."

        dbsession = DBSession()

#        if file_path.startswith('c3sar/'):
#            file_path = file_path.replace('c3sar/', '')

        track = Track(
            name=unicode(form.data['track_name']),
            album=unicode(form.data['track_album']),
            url=unicode(form.data['track_url']),
            filepath=unicode(file_path),
            bytesize=output_file_size,
            )
        track.registrar_id = viewer_username

        dbsession.add(track)
        dbsession.flush()

         # ToDo: send mail...

        redirect_url = route_url('track_view', request, track_id=track.id)
        return HTTPFound(location=redirect_url)