示例#1
0
def new(r):
    if r.POST:
        novo = File()
        file = r.FILES['file']
        novo.content = file
        novo.name = file.name
        novo.title = r.POST['title'] or file.name
        novo.save()

        return HttpResponseRedirect(reverse('upload-index'))
    else:
        return render_to_response('main/templates/new.html', context_instance=RequestContext(r))
    def create_file(self, pdf):

        common_utils = CommonUtils()
        internal_name = common_utils.create_token() + '.pdf'

        fs = FileSystemStorage(location=settings.BASE_POOL_PDF)
        filename = fs.save(internal_name, pdf)

        file_url = fs.url(filename)
        file_db = File()
        file_db.user_name = pdf.name
        file_db.internal_name = internal_name
        file_db.date = datetime.datetime.now()
        file_db.status = file_db.STARTED
        file_db.save()

        p = Process(target=self.pdf_process, args=(file_db.id, ))
        p.start()
def crowd_upload_files(request):

    # Handle file delete
    if request.is_ajax():
        file = File.objects.get(id=request.POST.get('file_id'))
        file.delete()
        data = {'res': 'file deleted'}
        # return if it was successful to the client
        return render_to_json_response(data)

    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            filename = request.FILES['docfile'].name
            docfile = request.FILES['docfile']
            new_file = File(filename=filename,
                            uploader=request.user,
                            file=docfile)
            new_file.save()

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

    # redirect to homepage if they're not logged in
    if (not request.user.is_authenticated()) or UserType.objects.get(
            user_id=request.user.id).type != 'director':
        return redirect('/')
    else:
        user_files = File.objects.filter(uploader=request.user)
        form = DocumentForm()
        fullname = request.user.first_name + ' ' + request.user.last_name  # get user's fullname
        template = loader.get_template('main/upload_files.html')
        context = {
            'fullname': fullname,
            'form': form,
            'user_files': user_files
        }
        return HttpResponse(template.render(context, request))
示例#4
0
def add_file(request):

    if request.method == "POST":

        username = request.POST["username"]
        user = User.objects.get(username=username)

        repo = request.POST["repo"]
        repo = Repository.objects.get(name=repo, user_id=user.id)

        path = request.POST["path"]
        filename = request.POST["filename"]
        url = request.POST["url"]

        if path[len(path)-1] == "/" and path[len(path)-2] == "/":
            path = path[0:len(path)-1]

        d = Directory.objects.get(repo_id=repo.id, path=path)
        f = File(repo_id=repo.id, filename=filename, directory_id=d.id, url=url)
        f.save()

        return JsonResponse({"message": "success"})
示例#5
0
def upload_file(request):
    authenticated_user = get_authenticated_user(request)
    cloud = Cloud.objects.get(owner=authenticated_user)

    # If request method == POST
    if request.method == 'POST':
        form = FileUploadForm(request.POST, request.FILES)

        # If form valid
        if form.is_valid():
            image = form.cleaned_data['image']
            compress = form.cleaned_data['compress']

            file = File(cloud=cloud, file=image)
            file.save()

            # If user want to compress the image
            if compress is True:
                compress_image(file.file.path)

            # calculate file size
            filesize = file.file.size / 1000
            if filesize < 100:
                filesize = 0.1

            elif filesize < 200:
                filesize = 0.2

            elif filesize < 300:
                filesize = 0.3

            elif filesize < 400:
                filesize = 0.4

            elif filesize < 500:
                filesize = 0.5

            elif filesize < 600:
                filesize = 0.6

            elif filesize < 700:
                filesize = 0.7

            elif filesize < 800:
                filesize = 0.8

            elif filesize < 900:
                filesize = 0.9

            else:
                filesize = round(filesize / 100) / 10

            # Calculate cloud's used space
            cloud.used_space = float(cloud.used_space)
            cloud.used_space = round((cloud.used_space + filesize) * 10) / 10
            cloud.used_percent = round(
                float(cloud.used_space) * 1000 / float(cloud.space)) / 10
            cloud.save()

            # Redirect user to "cloud" page
            return HttpResponseRedirect('/cloud/')

    # If request method == GET
    else:
        form = FileUploadForm()  # Give the form to user

    # Check cloud's available space
    available_space = float(cloud.space) - float(cloud.used_space)
    if available_space >= 10.0:
        available_space = True

    context = {
        'authenticated_user': authenticated_user,
        'new_notifications': get_new_notifications(authenticated_user),
        'form': form,
        'cloud': cloud,
        'available_space': available_space,
    }

    # Show "upload file" page template to user
    return render(request, 'cloud/upload_file.html', context)
示例#6
0
文件: views.py 项目: shashisp/cast
def submit(request):
	from main.models import File
	start_time = time.strftime('%x %X %z')
	a = datetime.datetime.now()
	file1 = request.FILES['file']
	data = csv.reader(file1)
	email = request.POST['email']
	global _file_id
	#_file_count+=1
	#print _file_id
	
	detail = File(csvfile=file1, email=email, pid=_file_id)
	
	detail.save()
	
	
	
	account_id = []
	for row in data:
		#print row
		account_id.append(row)
	#print account_id
	x = []
	for i in account_id:
		for k in i:
			print k
			x.append(k)
	
	
	current_acnt_id = []
	for i in x:
		current_acnt_id.append(i.split('_'))
	k = []	
	for j in current_acnt_id:
		k.append(j[1])
	
	print k

	           #list of current account ids as strings
	intlist = []
	for i in k:
		j = int(i)
		intlist.append(j)
		#print j
	#print intlist      # account ids typecasted in to integers

		
	
 
	id_list = []
	for i in x:
		data = requests.get('https://graph.facebook.com/'+i+'/customaudiences?fields=account_id&access_token=CAACcXbmWPQMBAHxPC0pKxsN5jZBzlR9UU1Vj8wMpZBkwwg1om63w4rlCh5oxMbkchL5KTwmWMOQtnSig1pKwoG6V7wuAbQ2mDoiarKglnN9a0CWdebQesJBVCrUO1WmyMmzMk6ZBixPLRzgNDhR4sd8JNrnoU5FsWfDKnls6anNJFjviDVj')
		jsondata = data.json()['data']
		print jsondata
		
		for j in jsondata:
			if j['account_id'] in intlist:
				id_list.append(j['id']) #getting list of ID's
	
	failed_request = 0
	Succeeded_request = 0
	mailresponse = []
	sucess_ids = []
	failed_ids = []
	for i in intlist:
		for j in id_list:
				payload = {'access_token': 'CAACcXbmWPQMBAHxPC0pKxsN5jZBzlR9UU1Vj8wMpZBkwwg1om63w4rlCh5oxMbkchL5KTwmWMOQtnSig1pKwoG6V7wuAbQ2mDoiarKglnN9a0CWdebQesJBVCrUO1WmyMmzMk6ZBixPLRzgNDhR4sd8JNrnoU5FsWfDKnls6anNJFjviDVj' ,'adaccounts': [i]} 
				r = requests.post('https://graph.facebook.com/'+j+'/adaccounts', data=payload)
				#counting the response
				if r.json()==1:
					sucess_ids.append(j)
					Succeeded_request+=1
				else:
					failed_request+=1
					failed_ids.append(j)
				

	x = str(Succeeded_request)
	y = str(failed_request)

	attachment = File.objects.get(pid=_file_id)
	_file_id+=1
	attachfile = attachment.csvfile
	last_time = time.strftime('%x %X %z')
	b = datetime.datetime.now()
	Duration = (b-a)
	email_body = """Submitted  at:"""+start_time+"""
Finished at: """+last_time+"""
Duration : """+str(Duration)+"""
Succeeded : """+x+"""
Failed : """+y
   	"""
   		creating log files of 	
	sucess_ids_str = ''.join(sucess_ids)
	failed_ids_str = ''.join(failed_ids)
	log =open("sucess_logs.txt", "a")
	log.write(sucess_ids_str)
	log.close()
	"""

	mail = EmailMessage('Audience Sharing | File: '+attachfile.name.split('/')[4]+'| '+x+' Succeeded, '+y+' Failed', email_body, to=[email])
	mail.attach(attachfile.name.split('/')[4], attachfile.read(), "text/csv")
	#mail.attach('sucess_ids.txt', 'sucess_ids.txt', 'text')
	mail.send()
	_file_id+=1
	

	return HttpResponseRedirect('/')