def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('list'))
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.last()

    if (request.GET.get('mybtn')):
        pass

    # Render list page with the documents and the form
    return render_to_response('myapp/list.html', {
        'documents': documents,
        'form': form
    },
                              context_instance=RequestContext(request))
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile = request.FILES['docfile'])
            newdoc.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('list'))
    else:
        form = DocumentForm() # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.last()

    if(request.GET.get('mybtn')):
        pass
        
    # Render list page with the documents and the form
    return render_to_response(
        'myapp/list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )
Exemple #3
0
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            filename = request.FILES['docfile']
            if zipfile_is_valid(filename):
                fields = extract_xml(filename)
                newdoc = Document(docfile = filename, **fields)
                newdoc.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('myapp.views.list'))
    else:
        form = DocumentForm() # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response(
        'list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        files = request.FILES.getlist('docfile')
        user = request.user.username
        if form.is_valid():
            for f in files:
                filename = f.name
                try:
                    doc = Document.objects.get(filename=filename)
                    doc.filename = filename
                    doc.uploadedby = user
                    doc.lastuploadtime = timezone.now().strftime(
                        "%Y-%m-%d %H:%M:%S")
                    doc.docfile = f
                except Document.DoesNotExist:
                    doc = Document(docfile=f,
                                   filename=filename,
                                   uploadedby=user,
                                   lastuploadtime=timezone.now().strftime(
                                       "%Y-%m-%d %H:%M:%S"))
                doc.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('list'))
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render(request, 'list.html', {'documents': documents, 'form': form})
Exemple #5
0
def liss(request):
    # Handle file upload
	    
    MEDIA_FILE = os.path.join(BASE_DIR, 'media/%s.enc' % os.urandom(10).encode('hex'))
   
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            encrypt_file(request.FILES['docfile'], MEDIA_FILE, '8W;>i^H0qi|J&$coR5MFpR*Vn')
            decrypt_file( MEDIA_FILE,  os.path.join(BASE_DIR, 'media/file.jpg' ), b'my private key')
            newdoc.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('liss'))
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    """ 
   return render_to_response(
        'list.html',
        {'documents': documents, 'form': form },
        context_instance=RequestContext(request)
    )
    """
    return render(request, 
        'myapp/list.html', 
        {'documents': documents, 'form': form }
    )
Exemple #6
0
def list(request):
    # Handle file upload
    if request.method == 'POST':
        if request.POST.get("form1") != "":
            form = DocumentForm(request.POST, request.FILES)
            if form.is_valid():
                newdoc = Document(docfile=request.FILES['docfile'])
                newdoc.save()

                # Redirect to the document list after POST
                return HttpResponseRedirect(reverse('list'))

        elif request.POST.get("form2") != "":
            mail = request.POST.get("mail")
            dropdown = request.POST.get("ident")
            #plik = {{ document.docfile.url }}
            # run(lokalizacja pliku, lokalizacja modelu, nazwa modelu)
            #send (mail,link)
            #return HttpResponseRedirect("/myapp/"+dropdown)

    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render(request, 'list.html', {'documents': documents, 'form': form})
def index(request):
	form = DocumentForm()
	if request.method == 'GET':
		user=User.objects.get(username=str(request.user))
		thisupro = UserProfile.objects(user_id=user)[:1]
		context={"UserProfile":thisupro[0],'form': form}
		return render(request, 'myapp/account-setting.html', context)
	elif request.method == 'POST':
		form = DocumentForm()
		user=User.objects.get(username=str(request.user))
		thisupro = UserProfile.objects(user_id=user)[:1]
		fromType = request.POST['formType']
		if	fromType == "frmImage" :
			err_message=""
			
			try:
				form = DocumentForm(request.POST, request.FILES)
				if form.is_valid():
					handle_uploaded_image(request.user,request.FILES['image'],request)
					
			except Exception as e:
				print(e)
				err_message = e
			context={"UserProfile":thisupro[0],'form': form}
			return render(request, 'myapp/account-setting.html', context)
		elif fromType == "frmProfile" :
			err_message=""
			success=""
			try:
				txtJob = request.POST['txtJob']
				txtCompany = request.POST['txtCompany']
				txtWorking = request.POST['txtWorking']
				txtEducation = request.POST['txtEducation']
				txtSkill = request.POST['txtSkill']
				txaAbout = request.POST['txaAbout']
				user=User.objects.get(username=str(request.user))
				thisupro = UserProfile.objects(user_id=user)[:1]
				if len(thisupro)>0:
					supro=thisupro[0]
					supro.job_title = txtJob
					supro.company = txtCompany
					supro.work_field = txtWorking
					supro.edu = txtEducation
					supro.skill = txtSkill
					supro.about = txaAbout
					supro.save()
					success="success"
			except Exception as e:
				print(e)
				err_message = e
				success=e
			context={"UserProfile":thisupro[0],'form': form}
			return render(request, 'myapp/account-setting.html', context)
Exemple #8
0
def upload(request):
    """
    View for rendering upload page of the application.
    This view performs the following operations:
        1. Create a form consisting of an input field for a user to upload a file.
        2. Get the OAuth token for the user from authentication (if it doesn't
           exist).
        3. Get the list of files in current users' CDrive.
        4. Render the form and CDrive files.
    Arguments:
        request: The request object.
    Returns an HttpResponse object.
    """
    form = DocumentForm()
    if CLIENT_TOKEN_KEY not in request.session:
        if 'code' in request.GET:
            code = request.GET.get('code')
            data = {
                "grant_type": "authorization_code",
                "code": code,
                "redirect_uri": REDIRECT_URI,
                "client_id": APP_ID,
                "client_secret": APP_SECRET,
            }
            response = requests.post(url=TOKEN_URL, data=data)
            request.session[CLIENT_TOKEN_KEY] = response.json()['access_token']
            request.session.set_expiry(response.json()['expires_in'])
        else:
            return HttpResponseRedirect(AUTH_URL)
    return render(request, 'upload.html', {
        'form': form,
        'c_drive_ui_url': CDRIVE_UI_URL
    })
Exemple #9
0
def show(request):
    # Handle file upload   
    myfile = "/home/zyy/Documents/kdd-master/myweb/doc-django-master/media/documents/test_data.txt"
    form = DocumentForm() # A empty, unbound form
    
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile = request.FILES['docfile'])
            newdoc.save()
          #  if os.path.isfile(myfile):
            #plot(request)
        return HttpResponseRedirect(reverse('show'))
    
    data = process_document(myfile)
    text = " | ".join([", ".join(row) for row in data])
    return render(request, 'show.html', {'text': text, 'form': form, 'graphic': ""})
Exemple #10
0
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('list'))
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render(request, 'list.html', {'documents': documents, 'form': form})
Exemple #11
0
def liss(request):
    # Handle file upload

    # MEDIA_FILE = os.path.join(BASE_DIR, 'media/documents/%s.jpg' % os.urandom(10).encode('hex'))

    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            # handle_uploaded_file(request.FILES['docfile'], MEDIA_FILE)
            current_user = request.user
            newdoc = Document(docfile=request.FILES['docfile'],
                              uploader=current_user.id)
            newdoc.save()
            # os.remove(MEDIA_FILE)
            # a.save()
            # encrypt_file(request.FILES['docfile'], MEDIA_FILE, '8W;>i^H0qi|J&$coR5MFpR*Vn')
            # uploaderObj =
            # with open(MEDIA_FILE, 'rw') as f:
            #     mile = File(f)
            #     current_user = request.user
            #     newdoc = Document(docfile=mile, uploader=current_user.id)
            #     newdoc.save()
            #     f.close()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('liss'))
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    """
   return render_to_response(
        'list.html',
        {'documents': documents, 'form': form },
        context_instance=RequestContext(request)
    )
    """
    return render(request, 'myapp/list.html', {
        'documents': documents,
        'form': form
    })
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile = request.FILES['docfile'])
            newdoc.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('list'))
    else:
        form = DocumentForm() # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()


    # Render list page with the documents and the form
    return render(request, 'list.html', {'documents': documents, 'form': form})
Exemple #13
0
def upload(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        x = request.FILES['document'].name
        z = request.FILES['document']
        if z.name.endswith('.xlsx'):
            if isSQLite3(x) is False:
                if form.is_valid():
                    form.save()
                return redirect(reverse('myapp:files'))
        else:
            form = DocumentForm()
        return render(request, 'myapp/upload.html', {'form': form})
    else:
        form = DocumentForm()
    return render(request, 'myapp/upload.html', {'form': form})
Exemple #14
0
def fileUpload(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            docId = createPicsule(request)
          #  newdoc.save()
            for (dir, _, files) in os.walk("myproject/media/documents"):
                for f in files:
                    path = os.path.join(dir, f)
                    print path
            # Redirect to the document list after POST
            return HttpResponse(json.dumps({'id': docId}), content_type="application/json")
    else:
        form = DocumentForm() # A empty, unbound form
    # Render list page with the documents and the form
    return render_to_response(
            'myapp/fileUpload.html',
        {'form': form},
        context_instance=RequestContext(request)
    )
Exemple #15
0
def show(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()

            return HttpResponseRedirect(reverse('show'))
    else:
        form = DocumentForm()  # A empty, unbound form

    data = process_document(Document.objects.last())
    text = " | ".join([", ".join(row) for row in data])

    plot(request)

    return render(request, 'show.html', {
        'text': text,
        'form': form,
        'graphic': ""
    })
Exemple #16
0
def index(request):
	if request.method == 'POST':
		form = DocumentForm(request.POST, request.FILES)
		# Redirect to the document list after POST
		if form.is_valid():
			handle_uploaded_file(request.user,request.FILES['docfile'])
		return HttpResponseRedirect("")
	else:
		form = DocumentForm() # A empty, unbound form
		# Load documents for the list page
		documents = Documents.objects.all()
		user=User.objects.get(username=str(request.user))
		up = UserProfile.objects.get(user_id=user.id)
		user_image = up.images
		print(user_image)
			# Render list page with the documents and the form
	return render_to_response(
							'myapp/documents.html',
							{'documents': documents, 
							'form': form,
							'user_image':user_image,
							},
							context_instance=RequestContext(request)
							)
Exemple #17
0
def upload(request):
    """
    View for rendering upload page of the application.
    This view performs the following operations:
        1. Create a form consisting of an input field for a user to upload a file.
        2. Get the OAuth token for the user from authentication (if it doesn't
           exist).
        3. Get the list of files in current users' CDrive.
        4. Render the form and CDrive files.
    Arguments:
        request: The request object.
    Returns an HttpResponse object.
    """
    form = DocumentForm()
    current_url = request.get_full_path()
    if CLIENT_TOKEN_KEY not in request.session:
        if current_url.endswith("/list/"):
            return HttpResponseRedirect(AUTH_URL)
        else:
            code = request.GET.get('code')
            data = {
                "grant_type": "authorization_code",
                "code": code,
                "redirect_uri": REDIRECT_URI,
                "client_id": APP_ID,
                "client_secret": APP_SECRET,
            }
            response = requests.post(url=TOKEN_URL, data=data)
            request.session[CLIENT_TOKEN_KEY] = response.json()['access_token']
            request.session.set_expiry(response.json()['expires_in'])
    token = request.session.get(CLIENT_TOKEN_KEY)
    cdrive_files = []
    if not token is None:
        post_url = CDRIVE_URL + "/list/"
        header = {"Authorization": "Bearer " + token}
        list_response = requests.get(url=post_url, headers=header)
        if list_response.status_code == requests.codes.ok:
            for r in list_response.json():
                cdrive_files.append(r['file_name'])
    return render(
        request, 'upload.html', {
            'form': form,
            'cdrive_files': cdrive_files,
            'c_drive_ui_url': CDRIVE_UI_URL
        })
Exemple #18
0
def list(request):
    # Handle file upload
    if request.method == 'POST':
        myFile = request.FILES.get("docfile", None)  # 获取上传的文件,如果没有文件,则默认为None
        if not myFile:
            return HttpResponse("no files for upload!")

        sub_path = get_random_str()
        root = os.path.join('upload', sub_path)
        unzip_path = os.path.join('myapp/templates', sub_path)
        os.mkdir(root)
        os.mkdir(unzip_path)
        # shutil.copytree('revealjs', unzip_path)
        destination = open(os.path.join(root, myFile.name),
                           'wb+')  # 打开特定的文件进行二进制的写操作
        for chunk in myFile.chunks():  # 分块写入文件
            destination.write(chunk)
        destination.close()
        result = handle(os.path.join(root, myFile.name), unzip_path)
        if result:
            print('===============', sub_path)
            return HttpResponseRedirect('/' + sub_path + '/index.html')
        # return HttpResponse("upload over!")
        # form = DocumentForm(request.POST, request.FILES)
        # if form.is_valid():
        #     newdoc = Document(docfile=request.FILES['docfile'])
        #     newdoc.save()
        #     print(request.FILES['docfile'])
        #
        #     # Redirect to the document list after POST
        #     return HttpResponseRedirect(reverse('list'))
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render(request, 'list.html', {'documents': '', 'form': form})
Exemple #19
0
def index(request):
    # Handle file upload

    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()

            #Process and create a new file
            try:
                id = Document.objects.all()[0].id
                filepath = Document.objects.get(id=id).docfile.file.name
                filename = basename(Document.objects.get(id=id).docfile.name)
                Airtel_AV_Dashboard("Test").process(filepath, filename)

                name = ""
                for l in filename:
                    if l == ".":
                        break
                    else:
                        name += l

                with open(f"myapp/Final Output/{name} modified.xlsx",
                          "rb") as stored_file:
                    #Store the new file in the database
                    new_doc = New_Document(docfile=File(
                        stored_file, name=f"{name} modified.xlsx"))
                    new_doc.save()

                #for each_file in Document.objects.all():
                #each_file.delete()

            except Exception as e:
                print(f"Exception {e}")
                #for each_file in Document.objects.all():
                #each_file.delete()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('index'))
    else:

        form = DocumentForm()  # A empty, unbound form
        #if len(New_Document.objects.all()) > 0:
        #previous_document = New_Document.objects.all()[0]
        #previous_document.delete()

    # Load documents for the list page
    query_set = New_Document.objects.all()
    documents = []
    cnt = len(query_set) - 1
    for i in query_set:
        documents.append(query_set[cnt])
        cnt -= 1
    documents = documents

    # Render file_processing_indexpython manage.py runserver
    #  page with the documents and the form
    return render(request, 'file_processing_index.html', {
        'documents': documents,
        'name': "Download File",
        'form': form
    })
Exemple #20
0
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile = request.FILES['docfile'])
            newdoc.save()
            
	    filename = 'media/' + newdoc.docfile.name
	    extension = filename.rsplit('.')[-1]
#############is vaild?#####################
	    if(imghdr.what(filename)=='rgb' or imghdr.what(filename)=='gif' or imghdr.what(filename)=='pbm' or imghdr.what(filename)=='pgm' or imghdr.what(filename)=='ppm' or imghdr.what(filename)=='tiff' or imghdr.what(filename)=='rast' or imghdr.what(filename)=='xbm' or imghdr.what(filename)=='jpeg' or imghdr.what(filename)=='bmp' or imghdr.what(filename)=='png' or imghdr.what(filename)=='jpg'):

	        #exception handle. jpg is a part of jpeg format
	        if (imghdr.what(filename)=='jpeg' and extension=='jpg'):
		    extSyntax = 1
	        elif imghdr.what(filename) == extension:
		    extSyntax = 1
	        else:
		    extSyntax = 2
	    else:
		extSyntax = 0


##############################test#########
      	    exVar = newdoc.docfile.name
            exx = check_output(['myapp/embed.py','media/'+exVar])
	    tmp_str = exx.rsplit('\n')[3]
	    if(imghdr.what(filename) == 'gif' or imghdr.what(filename) == 'jpeg' or imghdr.what(filename) == 'jpeg' or imghdr.what(filename) == 'png'):
	        if(tmp_str == 'no files found'):
		    embSyntax = 1
	        else:
		    embSyntax = 2
		    tmp_str = exx.rsplit('\n')[4] + exx.rsplit('\n')[5]
	    else:
		embSyntax = 0
###########################################
	  


            # Json to the document list after POST
	    data = {
		    'original' : request.FILES['docfile'].name,
		    'filename' : newdoc.docfile.name.rsplit('/')[2],
		    'extension_result' : extSyntax,
		    'embedded_result' : embSyntax,
		    'embedded_message' : tmp_str,
		    'current' : extension,
		    'expected' : imghdr.what(filename)
		   }
	    return JsonResponse(data)

    else:
        form = DocumentForm() # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response(
        'list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )