def edit_person(slug): try: p = Person.objects.get(site=g.site.domain, slug=slug) except Person.DoesNotExist: abort(404) if not g.site.domain == g.user: abort(403) if request.method == "POST": reqfile = request.files.get('file') if reqfile: f = File() f.site = g.site.domain f.name = reqfile.filename f.content_type = reqfile.mimetype f.slug, f.content_length = save_file( reqfile, request.config["UPLOAD_FOLDER"]) f.save() p.name = request.form.get("name") p.title = request.form.get("title") p.phone = request.form.get("phone") p.email = request.form.get("email") p.twitter = request.form.get("twitter") p.description = request.form.get("description") if reqfile: p.image_slug = f.slug p.save() return redirect(url_for(".show_person", slug=p.slug)) return render_template("edit_person.html", person=p)
def edit_post(year, month, day, slug): try: p = Post.objects.get(site=g.site.domain, year=year, month=month, day=day, slug=slug) except Post.DoesNotExist: abort(404) if not g.site.domain == g.user: abort(403) if request.method == "POST": reqfile = request.files.get('file') if reqfile: f = File() f.site = g.site.domain f.name = reqfile.filename f.content_type = reqfile.mimetype f.slug, f.content_length = save_file( reqfile, current_app.config["UPLOAD_FOLDER"]) f.save() p.name = request.form.get("name") p.text = request.form.get("text") if reqfile: p.image_slug = f.slug p.save() return redirect( url_for("post", year=p.year, month=p.month, day=p.day, slug=p.slug)) return render_template("edit_post.html", post=p)
def edit_post(year, month, day, slug): try: p = Post.objects.get(site=g.site.domain, year=year, month=month, day=day, slug=slug) except Post.DoesNotExist: abort(404) if not g.site.domain == g.user: abort(403) if request.method == "POST": reqfile = request.files.get("file") if reqfile: f = File() f.site = g.site.domain f.name = reqfile.filename f.content_type = reqfile.mimetype f.slug, f.content_length = save_file(reqfile, current_app.config["UPLOAD_FOLDER"]) f.save() p.name = request.form.get("name") p.text = request.form.get("text") if reqfile: p.image_slug = f.slug p.save() return redirect(url_for("post", year=p.year, month=p.month, day=p.day, slug=p.slug)) return render_template("edit_post.html", post=p)
def RegisterFile(Service=None, FileName=None, ProvisionedSpace="10G"): if Service is None: raise StorageError('RegisterFile(): Service can not be None') if FileName is None: raise StorageError('RegisterFile(): FileName can not be None') vfilespace = StringSizeToBytes(ProvisionedSpace) if Service.freespace - vfilespace > 0: NewFile = File() NewFile.vfilename = FileName NewFile.ufid = GetUniqueFileID(FileName) NewFile.pfilesize = 0 NewFile.vfilesize = vfilespace NewFile.service = Service NewFile.pfilename = GetPhysicalFileName(Service.localpath, FileName) NewFile.status = 'O' NewFile.save() SFreeSpace = CalculateFreeSpace(Service) Service.freespace = SFreeSpace Service.save() return NewFile else: raise StorageError('RegisterFile(): No have left space')
def handle_new_file(user, uploaded, bulletin_id, encryption_key=None, rand=Random.new()): if encryption_key == '': encryption_key = None r, c, ep, iv, encryption_key = create_encryption_params(encryption_key, rand) file = File( author=user, bulletin=Bulletin.objects.get(pk=bulletin_id), name=uploaded.name, content=uploaded, rand=r, check=c, encryption_params=ep, date_created=datetime.now(), date_modified=datetime.now(), ) if encryption_key is not None: with tempfile.NamedTemporaryFile() as temp: cipher = AES.new(encryption_key, AES.MODE_CFB, iv) for chunk in uploaded.chunks(): encrypted_chunk = cipher.encrypt(chunk) temp.write(encrypted_chunk) temp.seek(0) file.content = DFile(temp) file.save() give_file_access(user, user, file, encryption_key) else: file.save()
def upload(request, uri): if request.POST: _uri = request.POST.get("uri") _md5_hash = request.POST.get("hash") _name = request.POST.get("name") _description = request.POST.get("description") _time = datetime.datetime.now() _directory = request.POST.get("directory") if _directory != "": _rank = 2 # 判断文件夹是否存在,若存在,则其中文件数加一,否则创建新的文件夹 try: d = Directory.objects.get(uri=uri + "/" + _directory) except Directory.DoesNotExist: d = None if d: d.file_num += 1 d.save() else: d = Directory(uri=uri + "/" + _directory, file_num=1, time=_time, name=_directory) d.save() else: _rank = 1 pd = PrimaryDirectory.objects.get(uri=uri) pd.file_num += 1 pd.save() file = File(uri=_uri, md5_hash=_md5_hash, name=_name, description=_description, time=_time, url=getDownloadUrl(_uri), download_num=0, rank=_rank) file.save() return HttpResponse("ok") return render_to_response("upload.html", {"uri": uri}, context_instance=RequestContext(request))
def upload_flash(request): """ Helper function that processes the file upload. Used by flash player. :Return: HttpResponse of 0 or 1 """ try: if (request.method == 'POST' and 'file_upload' in request.FILES and 'slug' in request.GET): upload = File() upload.file_upload = request.FILES['file_upload'] upload.submission = Submission.objects.get( slug=request.GET['slug']) upload.save() return HttpResponse(1) else: return HttpResponse(0) except StopUpload: raise except: return HttpResponse(0)
def upload(request, name): if request.method == 'POST': if request.FILES is None: return HttpResponseBadRequest('No file[] found') file = request.FILES[u'files[]'] wrapped_file = UploadedFile(file) filename = wrapped_file.name file_size = wrapped_file.file.size entry = File() entry.filename = unicode(filename) entry.username = unicode(name) entry.size = file_size entry.slug = generate_slug(8) entry.data = file entry.save() uploaded = [{ 'name': filename, 'size': filesizeformat(file_size), 'slug': entry.slug, 'date': entry.created.date().isoformat() }] return HttpResponse(json.dumps({'files': uploaded})) else: raise Http404
def edit_person(slug): try: p = Person.objects.get(site=g.site.domain, slug=slug) except Person.DoesNotExist: abort(404) if not g.site.domain == g.user: abort(403) if request.method == "POST": reqfile = request.files.get('file') if reqfile: f = File() f.site = g.site.domain f.name = reqfile.filename f.content_type = reqfile.mimetype f.slug, f.content_length = save_file(reqfile, request.config["UPLOAD_FOLDER"]) f.save() p.name = request.form.get("name") p.title = request.form.get("title") p.phone = request.form.get("phone") p.email = request.form.get("email") p.twitter = request.form.get("twitter") p.description = request.form.get("description") if reqfile: p.image_slug = f.slug p.save() return redirect(url_for(".show_person", slug=p.slug)) return render_template("edit_person.html", person=p)
def test_model_file(self): """Test File Model""" folder = Folder(name='test') folder.save() obj = File(name='test', folder=folder) obj.save() self.assertEquals(folder, obj.folder) self.assertNotEquals(obj.id, None) obj.delete()
def parse_pep8(run, git_path, output): """Parse the pep8 output, store the results""" errfiles_set = set() errortype_set = set() lineno_set = set() # Add all files in the project to the db allfiles = set() os.path.walk(git_path, add_file_to_set, allfiles) for filename in allfiles: filename = filename.replace(git_path + '/', '', 1) runfile = File(filename=filename, run=run) runfile.save() # Generate a set of error types, error files, and lines for line in output.readlines(): filename, lineno, errnum, errtext = string.split(line, ':', 3) lineno = int(lineno) filename = filename.replace(git_path + '/', '', 1) # Create sets to remove duplicates errfiles_set.add(filename) # Add new err types to the db if (errnum, errtext) not in errortype_set: errortype_set.add((errnum, errtext)) if not Error.objects.filter(error_type=errnum): err = Error(error_type=errnum, short_descr=errtext) err.save() # Create a set of line numbers for each file for ln in range(max(1, lineno - 3), lineno + 4): lineno_set.add((filename, ln)) # Add err instances to the db runfile = File.objects.get(run=run, filename=filename) errtype = Error.objects.get(error_type=errnum) runerr = RunError(error=errtype, file=runfile, line_number=lineno, error_descr=errtext) runerr.save() # Add lines to the db for filename in errfiles_set: runfile = File.objects.get(run=run, filename=filename) f = open(git_path + '/' + filename, 'r') lineno = 1 for line in f: if (filename, lineno) in lineno_set: linetext = Line(file=runfile, line_number=lineno, text=line) linetext.save() lineno = lineno + 1 f.close()
def post(self): for name in request.files: file = request.files.get(name) filename = path.basename(file.filename) ext = path.splitext(filename)[1] mimetype = file.mimetype user_id = g.current_user.id attachment = File( name=filename, ext=ext, mimetype=mimetype, user_id=user_id) attachment.save() file.save(path.join(Setting.UPLOAD_FOLDER, attachment.save_name)) return {'success': True}, 201
def save_file(mime, base64): ''' Calculate hash of the file, look up in the database, save if it's a new one and return its hash. The hash can the be used as URL. ''' hash_ = file_keeper_hash(mime, base64) objects = File.objects.filter(hash=hash_) if not objects: file_ = File(hash=hash_, mime=mime, base64=base64) file_.save() return hash_
def post_object(request): if request.method == "POST": upload = request.FILES['file'] parent = request.POST.get('parent') if 'parent' in request.POST.keys() else None f = File(name=upload.name, file=upload, owner=request.user, parent=parent, bytes=request.POST.get('size'), mime=request.POST.get('type')) f.save() return JsonResponse(f.get_client_inode(), safe=False) return JsonResponse({'message':'Invalid file..'}, status=400, safe=False)
def files(): if request.method == "POST" and g.site.domain == g.user: reqfile = request.files["file"] f = File() f.site = g.site.domain f.name = reqfile.filename f.slug = secure_filename(f.name) f.content_type = reqfile.mimetype f.slug, f.content_length = save_file(reqfile, app.config["UPLOAD_FOLDER"]) f.save() files = File.objects(site=g.site.domain) return render_template("files.html", files=files)
def files(): if request.method == "POST" and g.site.domain == g.user: reqfile = request.files['file'] f = File() f.site = g.site.domain f.name = reqfile.filename f.slug = secure_filename(f.name) f.content_type = reqfile.mimetype f.slug, f.content_length = save_file(reqfile, app.config["UPLOAD_FOLDER"]) f.save() files = File.objects(site=g.site.domain) return render_template('files.html', files=files)
def fileRead(request): if request.method == 'POST': myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) ob = File(path="/home/divum/Desktop/django/myproject" + uploaded_file_url) ob.save() dic = {} dic['status'] = 200 dic['message'] = "File Stored" dic['url'] = "/home/divum/Desktop/django/myproject" + uploaded_file_url return JsonResponse(dic, status=200)
def create_file(name, folder_id): root = MEDIA_ROOT folder = Folder.objects.get(id=folder_id) # Open a file f = open(folder.path + "/" + name, "w") # Close opend file f.close() file = File() file.name = name file.folder = folder file.active = True file.save() return file.id
def upload_html(request, submission): """ Helper function that processes the file upload. Used by the 'no flash' version. :Return: Void """ if request.FILES: for file in request.FILES: upload = File() upload.submission = submission upload.file_upload = request.FILES[file] upload.save() return
def upload_file(name, folder_id, f): root = MEDIA_ROOT folder = Folder.objects.get(id=folder_id) # create a file with open(folder.path + "/" + name, 'w') as destination: for chunk in f.chunks(): destination.write(chunk) file = File() file.name = name file.folder = folder file.active = True file.save() return file.id
def add_file(request,prop_id, event_id, note_id): if request.method == 'POST': form = FileUploadForm(request.POST, request.FILES) note = Note.objects.get(pk=note_id) if form.is_valid(): newdoc = File(docfile=request.FILES['docfile'] ) newdoc.note = note newdoc.save() return HttpResponse("added file") else: form = FileUploadForm() documents = File.objects.all() context={'form':form, 'documents': documents,'event_id':event_id, 'prop_id':prop_id,"note_id":note_id} return HttpResponseBadRequest(render (request,'main/note.html',context))
def upload(request): if request.POST: userid = request.POST.get('userid') # Queries all non-expired sessions sessions = Session.objects.filter(expire_date__gte=datetime.now()) # Checks if session is active for session in sessions: data = session.get_decoded() found_userid=data.get('_auth_user_id') # Prceeds when user id is validated if found_userid!=None and long(userid)==found_userid: user = User.objects.filter(id=userid)[0] faculty=None faculty=Faculty.objects.filter(id=request.POST.get('fid'))[0] transaction = Transaction.objects.get(id=request.POST.get('transaction')) document = Dokument() document.faculty= faculty document.transaction= transaction document.save() #Generates a random alphanum string for filename template while True: fnameTemplate='' fnameTemplate = ''.join(random.choice(string.ascii_lowercase)) fnameTemplate += ''.join(random.choice(string.ascii_lowercase + string.digits) for x in range(4)) + '_' if len(File.objects.filter(filename__startswith = fnameTemplate))==0: break #Processes uploaded files, page by page for key in request.FILES: files = request.FILES[key] filename = fnameTemplate + key.split('_')[1] + '.bmp' with open('DCSArchivingSystem/testapp/media/files/' + filename, 'wb+') as destination: for chunk in files.chunks(): destination.write(chunk) file = File() file.filename = filename file.file = 'files/' + filename file.save() document.files.add(file) Log.create(user, "Uploaded file", file, document).save() Log.create(user, "Created Document", None, document).save() return HttpResponseRedirect("/dashboard/") else: return render_to_response('upload.html', context_instance=RequestContext(request))
def compile_java(file_id): #first traslate traslate_java(file_id) file = File.objects.get(id=file_id) folder = file.folder user = folder.user galatea_code = GALATEA + "galatea.jar " code = "javac -cp "+ galatea_code + folder.path + "/*.java" #print code value = subprocess.check_output([code], shell=True) #print value #get all the file in this folder for root, dirs, files in os.walk(folder.path): root_folder = Folder.objects.get(path=root, name = os.path.basename(root)) for dir in dirs: folders = Folder.objects.filter(father=root_folder.id) esta = False for folder in folders: if folder.name == dir: esta = True if not esta: folder = Folder() folder.name = dir folder.path = root_folder.path + "/" + dir folder.user = user folder.father = root_folder.id folder.active = True folder.save() #print dirs for file in files: files_folder = File.objects.filter(folder = root_folder.id) esta = False for f in files_folder: if f.name == file: esta = True if not esta: if (os.path.splitext(file)[1] != ".class"): f = File() f.name = file f.folder = root_folder f.active = True f.save() return value
def new_post(): if not g.site.domain == g.user: abort(403) p = Post() if request.method == "POST": reqfile = request.files.get('file') if reqfile: f = File() f.site = g.site.domain f.name = reqfile.filename f.content_type = reqfile.mimetype f.slug, f.content_length = save_file(reqfile, blog.config["UPLOAD_FOLDER"]) f.save() import datetime p.site = g.site.domain p.name = request.form.get("name") p.created = datetime.datetime.utcnow() p.year = p.created.year p.month = p.created.month p.day = p.created.day slugs = [ __j.slug for __j in Post.objects.filter(site=g.site.domain, year=p.year, month=p.month, day=p.day, slug=p.slug) ] counter = 1 slug = slugify(p.name) __slug = slug while __slug in slugs: counter += 1 __slug = "%s_%d" % (slug, counter) p.slug = __slug p.text = request.form.get("text") if reqfile: p.image_slug = f.slug p.save() return redirect( url_for("post", year=p.year, month=p.month, day=p.day, slug=p.slug)) return render_template("edit_post.html", post=p)
def add_file(file_name, description=None): """Adds a file name to the catalog""" file_name = file_name.strip() try: date_created = datetime.datetime.fromtimestamp(os.path.getctime(file_name)).strftime('%Y-%m-%d %H:%M:%S') current_file = File(file_name=file_name, description=description, date_created=date_created) current_file.save() print "'%s' added!" % file_name except IntegrityError: current_file = File.get(File.file_name == file_name) return current_file
def upload(request, json=False): if request.method == 'GET': form = UploadForm() if request.method == 'POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): data = request.FILES['file'] size = form.cleaned_data['file'].size expire_date = form.cleaned_data['expire_date'] or one_week_later() message = form.cleaned_data['message'] receiver = form.cleaned_data['receiver'] if form.cleaned_data['filename_overwrite']: name = form.cleaned_data['filename_overwrite'] else: name = form.cleaned_data['file'].name file = File(name=name, owner=request.user, expire_date=expire_date, message=message, size=size) md5 = handle_uploaded_file(name, file.secret, data) file.md5 = md5 file.save() if receiver: downloader = Downloader(email=receiver, file=file) downloader.save() url = 'http://%s/files/download/%s/%s' % \ (Site.objects.get_current().domain, file.id, file.secret) from_ = request.user.email mailit([receiver], from_, message, url) if json: response = {'status': 'ok', 'fileid': file.id} return HttpResponse(simplejson.dumps(response)) else: return HttpResponseRedirect('/files/list/') if json: response = {'status': 'error', 'message': 'form not valid'} return HttpResponse(simplejson.dumps(response)) else: return render_to_response('files/upload.html', {'form': form, }, context_instance=RequestContext(request))
def add(self, request, *args, **kwargs): form = SubmitFileForm(request.POST or None, request.FILES or None) if form.is_valid(): docfile = request.FILES['docfile'] docfile_ext = docfile.name.split(".")[-1] if docfile_ext == "pdf" or docfile_ext == "txt": field_starts_at = request.POST['starts_at'] or 0 field_ends_at = request.POST['ends_at'] or 0 file = File( title = request.POST['title'], docfile = request.FILES['docfile'], is_summarized = request.POST.get('is_summarized', False), starts_at = field_starts_at, ends_at = field_ends_at, user = request.user ) # cleaned data title = form.cleaned_data["title"] docfile = form.cleaned_data["docfile"] is_summarized = form.cleaned_data["is_summarized"] starts_at = form.cleaned_data["starts_at"] ends_at = form.cleaned_data["ends_at"] if (int(field_starts_at) <= int(field_ends_at)): if file.save(): if docfile_ext == "pdf": messages.success(request, "O arquivo " + docfile.name + " foi convertido para txt e adicionado com sucesso!") else: messages.success(request, "O arquivo " + docfile.name + " foi adicionado com sucesso!") else: messages.error(request, "O arquivo " + docfile.name + " está protegido." " Verifique as permissões de acesso ao conteúdo do arquivo.") else: messages.error(request, "Range de conversão inválido. " "Verfique se as páginas inseridas estão corretas.") return redirect('/') else: messages.error(request, "Formato do arquivo ." + docfile_ext + u" inválido! Apenas .pdf e .txt são permitidos.") files = File.objects.filter(user=request.user).all() template = "converter/index.html" context = { "title": "Conversor", "form": form, "files": files } return render(request, template, context)
def new_person(): if not g.site.domain == g.user: abort(403) p = Person() if request.method == "POST": reqfile = request.files.get('file') if reqfile: f = File() f.site = g.site.domain f.name = reqfile.filename f.content_type = reqfile.mimetype f.slug, f.content_length = save_file( reqfile, current_app.config["UPLOAD_FOLDER"]) f.save() p.site = g.site.domain p.name = request.form.get("name") p.title = request.form.get("title") p.phone = request.form.get("phone") p.email = request.form.get("email") p.twitter = request.form.get("twitter") p.description = request.form.get("description") slugs = [__p.slug for __p in Person.objects.filter(site=g.site.domain)] slug = slugify(p.name) counter = 1 __slug = slug while __slug in slugs: counter += 1 __slug = "%s_%d" % (slug, counter) p.slug = __slug if reqfile: p.image_slug = f.slug p.save() pl = Personnel.objects.get(site=g.site.domain) pl.people.append(p.slug) pl.save() return redirect(url_for(".show_personnel")) return render_template("edit_person.html", person=p)
def new_person(): if not g.site.domain == g.user: abort(403) p = Person() if request.method == "POST": reqfile = request.files.get('file') if reqfile: f = File() f.site = g.site.domain f.name = reqfile.filename f.content_type = reqfile.mimetype f.slug, f.content_length = save_file(reqfile, current_app.config["UPLOAD_FOLDER"]) f.save() p.site = g.site.domain p.name = request.form.get("name") p.title = request.form.get("title") p.phone = request.form.get("phone") p.email = request.form.get("email") p.twitter = request.form.get("twitter") p.description = request.form.get("description") slugs = [ __p.slug for __p in Person.objects.filter(site=g.site.domain) ] slug = slugify(p.name) counter = 1 __slug = slug while __slug in slugs: counter += 1 __slug = "%s_%d" % (slug, counter) p.slug = __slug if reqfile: p.image_slug = f.slug p.save() pl = Personnel.objects.get(site=g.site.domain) pl.people.append(p.slug) pl.save() return redirect(url_for(".show_personnel")) return render_template("edit_person.html", person=p)
def TakeOwnership(Service=None, FileName=None): if Service is None: raise StorageError('TakeOwnership(): Service can not be None') if FileName is None: raise StorageError('TakeOwnership(): FileName can not be None') if FileExist(Service.localpath,FileName,True): NewFile = File() NewFile.vfilename = FileName NewFile.pfilename = FileName NewFile.ufid = GetUniqueFileID(FileName) NewFile.service = Service NewFile.status = 'O' NewFile.vfilesize = 0 NewFile.pfilesize = 0 NewFile.save() CloseFile(NewFile.ufid) return NewFile else: raise StorageError('TakeOwnership(): File not exit [%s%s]' % (Service.localpath+FileName))
def new_post(): if not g.site.domain == g.user: abort(403) p = Post() if request.method == "POST": reqfile = request.files.get("file") if reqfile: f = File() f.site = g.site.domain f.name = reqfile.filename f.content_type = reqfile.mimetype f.slug, f.content_length = save_file(reqfile, blog.config["UPLOAD_FOLDER"]) f.save() import datetime p.site = g.site.domain p.name = request.form.get("name") p.created = datetime.datetime.utcnow() p.year = p.created.year p.month = p.created.month p.day = p.created.day slugs = [ __j.slug for __j in Post.objects.filter(site=g.site.domain, year=p.year, month=p.month, day=p.day, slug=p.slug) ] counter = 1 slug = slugify(p.name) __slug = slug while __slug in slugs: counter += 1 __slug = "%s_%d" % (slug, counter) p.slug = __slug p.text = request.form.get("text") if reqfile: p.image_slug = f.slug p.save() return redirect(url_for("post", year=p.year, month=p.month, day=p.day, slug=p.slug)) return render_template("edit_post.html", post=p)
def upload(request, name): if request.method == 'POST': if request.FILES is None: return HttpResponseBadRequest('No file[] found') file = request.FILES[u'files[]'] wrapped_file = UploadedFile(file) filename = wrapped_file.name file_size = wrapped_file.file.size entry = File() entry.filename = unicode(filename) entry.username = unicode(name) entry.size = file_size entry.slug = generate_slug(8) entry.data = file entry.save() uploaded = [{'name': filename, 'size': filesizeformat(file_size), 'slug': entry.slug, 'date': entry.created.date().isoformat()}] return HttpResponse(json.dumps({'files': uploaded})) else: raise Http404
def upload_flash(request): """ Helper function that processes the file upload. Used by flash player. :Return: HttpResponse of 0 or 1 """ try: if (request.method == 'POST' and 'file_upload' in request.FILES and 'slug' in request.GET): upload = File() upload.file_upload = request.FILES['file_upload'] upload.submission = Submission.objects.get(slug=request.GET['slug']) upload.save() return HttpResponse(1) else: return HttpResponse(0) except StopUpload: raise except: return HttpResponse(0)
def api_upload(request): reader = yield from request.multipart() field = yield from reader.next() filename = field.filename size = 0 path = 'E:/upload/' id = next_id() if not os.path.exists(path): os.mkdir(path) with open(os.path.join(path, filename), 'wb') as f: while True: chunk = yield from field.read_chunk() # 8192 bytes by default. if not chunk: break size += len(chunk) f.write(chunk) file = File(id=id, filename=filename, filepath=filename, filesize=size) affected = yield from file.save() return {'affected': affected}
def csvUpload(request): global messages messages = [] try: template = 'fileupload.html' form = SimpleFileForm() if request.method == 'POST': if 'file' in request.FILES: # # Final counters # numberWeeks = 0 numberTeamMembers = 0 numberActuals = 0 # # Preprossesing file # csvfile = request.FILES['file'] fileName = csvfile.name fileSize = csvfile.size rawData = csvfile.read() csvfile.seek(0) csvData = csv.reader(csvfile) fileDate = datetime.datetime.now() # # create file record # try: f = File(name=fileName, uploadDate=fileDate, data=rawData, status="This message means an internal error...") f.save() messages.append('Loaded file: "%s" [%d] on %s '% (fileName, fileSize, fileDate)) except: messages.append('Error while saving csv file') raise # # parse csv data # teamHead = [] teamData = {} teamMemberHead = [] for row in csvData: if not teamData: if not teamHead: # # Working on Team and Metric Header # teamHead = row # # Testing team data # if len(teamHead)<2: messages.append('Team Header row 1 has less than expected data') if teamHead[teamName] != "Team Name": messages.append('Expected Team Name Header not found') if teamHead[metricName] != "Metric Name": messages.append('Expected Metric Name Header not found') else: # # Working on Team and Metric names # # # testing team data # if len(row)<2: messages.append('Error, Team Data has less than expected data') raise # # Get Team and Metric objects # try: team, created = Team.objects.get_or_create(name=row[0]) #team.save() except: messages.append('Error with team information') raise try: metric, created = Metric.objects.get_or_create(team=team, name=row[1]) #metric.save() except: messages.append('Error with metric information') raise teamData['team'] = team teamData['metric'] = metric else: # # Working on member an metrics data # if not teamMemberHead: # # Testing second Header # teamMemberHead = row if len(teamMemberHead)<dateStart+1: messages.append('Team Member row 3 has less than expected data') if teamMemberHead[oDeskName] != "oDesk ID": messages.append('Expected oDesk ID Header not found') if teamMemberHead[memberName] != "Member Name": messages.append('Expected Member Name Header not found') # # Processing dates from header # try: metricDates = map(datetime_from_str, teamMemberHead[dateStart:]) numberWeeks = len(metricDates) except: messages.append('Some dates could not be parsed or are not sundays') raise else: # # Processing each memeber data # numberTeamMembers += 1 try: teamMember, created = TeamMember.objects.get_or_create(team=team, oId = row[oDeskName], defaults={'name': row[memberName]}) except: messages.append('Erro while getting Team member.') raise # # Processing members metrics # try: for metricDate, metricValue in zip(metricDates, row[dateStart:]): metdef ={'fileLoaded':f} if not metricValue: metdef['value'] = 0 metdef['status'] = False else: metdef['value'] = int(metricValue) MetricData.objects.get_or_create(member=teamMember, metric=metric, metricDate=metricDate, defaults=metdef) numberActuals +=1 except: messages.append('Erro while inserting Metric.') raise # # Saving final file status # messages.append("team='%s' metric='%s' processed %d actuals. %d members by %d weeks."% (team.name, metric.name, numberActuals, numberTeamMembers, numberWeeks)) f.status = "\n".join(messages) f.save() else: messages.append('No file attached') return render_to_response(template, RequestContext(request, { 'form': form, 'processMessages': messages, })) else: # # Display the form # return render_to_response(template, RequestContext(request, { 'form': form, 'processMessages': messages, })) except: # # Here we hold every problem genenrated on parsing # try: if f: f.status = "\n".join(messages) f.save() except: # # Let's display them...... # pass return render_to_response(template, RequestContext(request, { 'form': form, 'processMessages': messages, }))
def store(request): """ This view recieves a chunck of a file and saves it. When all the chunks are uploaded, they are joined together to make a complete file. This is gonna be pretty sketch for a while """ guid = File.sanitize_filename(request.POST['resumableIdentifier']) if not guid: return HttpResponseNotFound("Invalid file identifier") dir_path = os.path.join(settings.TMP_ROOT, str(request.user.pk) + "-" + guid) try: os.makedirs(dir_path) except OSError as e: # directory exists, dude! pass # each file will be named 1.part, 2.part etc. and stored inside the dir_path file_path = os.path.join(dir_path, str(int(request.POST['resumableChunkNumber'])) + '.part') file = request.FILES['file'] # dont let that chunk be too big if file.size > (settings.CHUNK_SIZE*2): shutil.rmtree(dir_path) return HttpResponseNotFound("Too many chunks") with open(file_path, 'wb') as dest: for chunk in file.chunks(): dest.write(chunk) total_number_of_chunks = int(request.POST['resumableTotalChunks']) total_number_of_uploaded_chunks = len(os.listdir(dir_path)) if total_number_of_chunks != total_number_of_uploaded_chunks: return HttpResponse("OK") total_size = 0 for i in range(1, total_number_of_chunks + 1): chunk_path = os.path.join(dir_path, str(i) + '.part') total_size += os.path.getsize(chunk_path) if total_size > settings.MAX_UPLOAD_SIZE: shutil.rmtree(dir_path) return HttpResponseNotFound("File too big") if total_size != int(request.POST['resumableTotalSize']): # All files present and accounted for, # just slow as balls when it comes to getting written return HttpResponse("OK") try: f = File( name=request.POST['resumableFilename'], type=FileType.UNKNOWN, status=FileStatus.UPLOADED, uploaded_by=request.user, tmp_path=dir_path, ) f.save() except DatabaseError as e: # that file was already taken care of, dude return HttpResponse("OK") process_uploaded_file.delay(total_number_of_chunks, f) return HttpResponse("COMPLETE")
def create(self, file): file = File() file.save(file, file.name) return file
def multiuploader(request): """ Main Multiuploader module. Parses data from jQuery plugin and makes database changes. """ if request.method == 'POST': log.info('received POST to main multiuploader view') if request.FILES == None: return HttpResponseBadRequest('Must have files attached!') #getting file data for farther manipulations file = request.FILES[u'files[]'] wrapped_file = UploadedFile(file) filename = wrapped_file.name file_size = wrapped_file.file.size log.info ('Got file: "%s"' % filename) #writing file manually into model #because we don't need form of any type. image = File() image.filename= filename image.image=file image.key_data = image.key_generate image.save() log.info('File saving done') #settings imports try: file_delete_url = settings.MULTI_FILE_DELETE_URL+'/' # file_url = settings.MULTI_IMAGE_URL+'/'+image.key_data+'/' except AttributeError: file_delete_url = 'multi_delete/' # file_url = 'multi_image/'+image.key_data+'/' file_url = image.image.url; #generating json response array result = [] context = {"name":filename, "size":file_size, "url":file_url, "file_id": image.id, "delete_url":file_delete_url+str(image.pk)+'/', "delete_type":"POST", } #getting thumbnail url using sorl-thumbnail print image.is_image if image.is_image: im = get_thumbnail(image, "80x80", quality=50) context['thumbnail_url'] = im.url result.append(context) response_data = simplejson.dumps(result) #checking for json data type #big thanks to Guy Shapiro if "application/json" in request.META['HTTP_ACCEPT_ENCODING']: mimetype = 'application/json' else: mimetype = 'text/plain' return HttpResponse(response_data, mimetype=mimetype) else: #GET return HttpResponse('Only POST accepted')
class DocumentsViewsTest(TestCase): username = "******" password = "******" def setUp(self): self.group, created = Group.objects.get_or_create(name='test') self.user, created = DjangoUser.objects.get_or_create(username=self.username) self.user.set_password(self.password) self.user.save() perspective, created = Perspective.objects.get_or_create( name='default') perspective.set_default_user() perspective.save() ModuleSetting.set('default_perspective', perspective.id) self.folder = Folder(name='test') self.folder.set_default_user() self.folder.save() self.document = Document(title='test_document', folder=self.folder) self.document.set_default_user() self.document.save() self.file = File(name='test_file', folder=self.folder) self.file.set_default_user() self.file.save() self.link = WebLink(title='test', folder=self.folder, url='test') self.link.set_default_user() self.link.save() ###################################### # Testing views when user is logged in ###################################### def test_index_login(self): "Test index page with login at /documents/" response = self.client.post('/accounts/login', {'username': self.username, 'password': self.password}) self.assertRedirects(response, '/') response = self.client.get(reverse('document_index')) self.assertEquals(response.status_code, 200) def test_index_documents_login(self): "Test index page with login at /documents/documents/" response = self.client.post('/accounts/login', {'username': self.username, 'password': self.password}) self.assertRedirects(response, '/') response = self.client.get(reverse('index_documents')) self.assertEquals(response.status_code, 200) def test_index_files_login(self): "Test index page with login at /documents/files/" response = self.client.post('/accounts/login', {'username': self.username, 'password': self.password}) self.assertRedirects(response, '/') response = self.client.get(reverse('index_files')) self.assertEquals(response.status_code, 200) def test_index_weblinks_login(self): "Test index page with login at /documents/weblinks/" response = self.client.post('/accounts/login', {'username': self.username, 'password': self.password}) self.assertRedirects(response, '/') response = self.client.get(reverse('index_weblinks')) self.assertEquals(response.status_code, 200) # Folders def test_folder_add(self): "Test index page with login at /documents/folder/add/" response = self.client.post('/accounts/login', {'username': self.username, 'password': self.password}) self.assertRedirects(response, '/') response = self.client.get(reverse('documents_folder_add')) self.assertEquals(response.status_code, 200) # form self.assertEqual(Folder.objects.count(), 1) post_data = {'name': 'test'} response = self.client.post(reverse('documents_folder_add'), post_data) self.assertEquals(response.status_code, 302) # redirect somewhere self.assertEquals(Folder.objects.count(), 2) def test_folder_view_login(self): "Test index page with login at /documents/folder/view/<folder_id>" response = self.client.post('/accounts/login', {'username': self.username, 'password': self.password}) self.assertRedirects(response, '/') response = self.client.get( reverse('documents_folder_view', args=[self.folder.id])) self.assertEquals(response.status_code, 200) def test_folder_edit_login(self): "Test index page with login at /documents/folder/edit/<folder_id>" response = self.client.post('/accounts/login', {'username': self.username, 'password': self.password}) self.assertRedirects(response, '/') response = self.client.get( reverse('documents_folder_edit', args=[self.folder.id])) self.assertEquals(response.status_code, 200) def test_folder_delete_login(self): "Test index page with login at /documents/folder/delete/<folder_id>" response = self.client.post('/accounts/login', {'username': self.username, 'password': self.password}) self.assertRedirects(response, '/') response = self.client.get( reverse('documents_folder_delete', args=[self.folder.id])) self.assertEquals(response.status_code, 200) # Documents def test_document_add(self): "Test index page with login at /documents/add" response = self.client.post('/accounts/login', {'username': self.username, 'password': self.password}) self.assertRedirects(response, '/') response = self.client.get(reverse('documents_document_add')) self.assertEquals(response.status_code, 200) # form self.assertEqual(Document.objects.count(), 1) response = self.client.get(reverse('documents_document_add')) post_data = {'title': 'test', 'folder': self.folder, } response = self.client.post( reverse('documents_document_add'), post_data) #self.assertEqual(Document.objects.count(), 2) def test_document_add_typed(self): "Test index page with login at /documents/add/folder/<folder_id>" response = self.client.post('/accounts/login', {'username': self.username, 'password': self.password}) self.assertRedirects(response, '/') response = self.client.get( reverse('documents_document_add_typed', args=[self.folder.id])) self.assertEquals(response.status_code, 200) def test_document_view_login(self): "Test index page with login at /documents/view/<document_id>" response = self.client.post('/accounts/login', {'username': self.username, 'password': self.password}) self.assertRedirects(response, '/') response = self.client.get( reverse('documents_document_view', args=[self.document.id])) self.assertEquals(response.status_code, 200) def test_document_edit_login(self): "Test index page with login at /documents/edit/<document_id>" response = self.client.post('/accounts/login', {'username': self.username, 'password': self.password}) self.assertRedirects(response, '/') response = self.client.get( reverse('documents_document_edit', args=[self.document.id])) self.assertEquals(response.status_code, 200) def test_document_delete_login(self): "Test index page with login at /documents/delete/<document_id>" response = self.client.post('/accounts/login', {'username': self.username, 'password': self.password}) self.assertRedirects(response, '/') response = self.client.get( reverse('documents_document_delete', args=[self.document.id])) self.assertEquals(response.status_code, 200) # Files def test_file_view_login(self): "Test index page with login at /file/view/<file_id>" response = self.client.post('/accounts/login', {'username': self.username, 'password': self.password}) self.assertRedirects(response, '/') response = self.client.get( reverse('documents_file_view', args=[self.file.id])) self.assertEquals(response.status_code, 200) def test_file_edit_login(self): "Test index page with login at /file/edit/<file_id>" response = self.client.post('/accounts/login', {'username': self.username, 'password': self.password}) self.assertRedirects(response, '/') response = self.client.get( reverse('documents_file_edit', args=[self.file.id])) self.assertEquals(response.status_code, 200) def test_file_delete_login(self): "Test index page with login at /file/view/<file_id>" response = self.client.post('/accounts/login', {'username': self.username, 'password': self.password}) self.assertRedirects(response, '/') response = self.client.get( reverse('documents_file_delete', args=[self.file.id])) self.assertEquals(response.status_code, 200) # Web Links def test_weblink_add_typed(self): "Test index page with login at /documents/weblink/add/<folder_id>" response = self.client.post('/accounts/login', {'username': self.username, 'password': self.password}) self.assertRedirects(response, '/') response = self.client.get( reverse('documents_weblink_add_typed', args=[self.folder.id])) self.assertEquals(response.status_code, 200) def test_weblink_add(self): "Test index page with login at /documents/weblink/add/" response = self.client.post('/accounts/login', {'username': self.username, 'password': self.password}) self.assertRedirects(response, '/') response = self.client.get(reverse('documents_weblink_add')) self.assertEquals(response.status_code, 200) # form self.assertEqual(WebLink.objects.count(), 1) response = self.client.get(reverse('documents_weblink_add')) post_data = {'title': 'test', 'folder': self.folder, 'url': 'test', } response = self.client.post( reverse('documents_weblink_add'), post_data) # self.assertEqual(WebLink.objects.count(), 2) def test_weblink_view_login(self): "Test index page with login at /documents/view/<weblink_id>" response = self.client.post('/accounts/login', {'username': self.username, 'password': self.password}) self.assertRedirects(response, '/') response = self.client.get( reverse('documents_weblink_view', args=[self.link.id])) self.assertEquals(response.status_code, 200) def test_weblink_edit_login(self): "Test index page with login at /documents/edit/<weblink_id>" response = self.client.post('/accounts/login', {'username': self.username, 'password': self.password}) self.assertRedirects(response, '/') response = self.client.get( reverse('documents_weblink_edit', args=[self.link.id])) self.assertEquals(response.status_code, 200) def test_weblink_delete_login(self): "Test index page with login at /documents/delete/<weblink_id>" response = self.client.post('/accounts/login', {'username': self.username, 'password': self.password}) self.assertRedirects(response, '/') response = self.client.get( reverse('documents_weblink_delete', args=[self.link.id])) self.assertEquals(response.status_code, 200) ###################################### # Testing views when user is not logged in ###################################### def test_index(self): "Test index page at /documents/" response = self.client.get('/documents/') # Redirects as unauthenticated self.assertRedirects(response, reverse('user_login')) def test_index_documents_out(self): "Testing /documents/documents/" response = self.client.get(reverse('index_documents')) self.assertRedirects(response, reverse('user_login')) def test_index_files_out(self): "Testing /documents/files/" response = self.client.get(reverse('index_files')) self.assertRedirects(response, reverse('user_login')) def test_index_weblinks_out(self): "Testing /documents/weblinks/" response = self.client.get(reverse('index_weblinks')) self.assertRedirects(response, reverse('user_login')) # Folders def test_folder_add_out(self): "Testing /documents/folder/add/" response = self.client.get(reverse('documents_folder_add')) self.assertRedirects(response, reverse('user_login')) def test_folder_view_out(self): "Testing /documents/folder/view/<folder_id>" response = self.client.get( reverse('documents_folder_view', args=[self.folder.id])) self.assertRedirects(response, reverse('user_login')) def test_folder_edit_out(self): "Testing /documents/folder/edit/<folder_id>" response = self.client.get( reverse('documents_folder_edit', args=[self.folder.id])) self.assertRedirects(response, reverse('user_login')) def test_folder_delete_out(self): "Testing /documents/folder/delete/<folder_id>" response = self.client.get( reverse('documents_folder_delete', args=[self.folder.id])) self.assertRedirects(response, reverse('user_login')) # Documents def test_document_add_out(self): "Testing /documents/add" response = self.client.get(reverse('documents_document_add')) self.assertRedirects(response, reverse('user_login')) def test_document_add_typed_out(self): "Testing /documents/add/folder/<folder_id>" response = self.client.get( reverse('documents_document_add_typed', args=[self.folder.id])) self.assertRedirects(response, reverse('user_login')) def test_document_view_out(self): "Testing /documents/view/<document_id>" response = self.client.get( reverse('documents_document_view', args=[self.document.id])) self.assertRedirects(response, reverse('user_login')) def test_document_edit_out(self): "Testing /documents/edit/<document_id>" response = self.client.get( reverse('documents_document_edit', args=[self.document.id])) self.assertRedirects(response, reverse('user_login')) def test_document_delete_out(self): "Testing /documents/delete/<document_id>" response = self.client.get( reverse('documents_document_delete', args=[self.document.id])) self.assertRedirects(response, reverse('user_login')) # Files def test_file_view_out(self): "Testing /file/view/<file_id>" response = self.client.get( reverse('documents_file_view', args=[self.file.id])) self.assertRedirects(response, reverse('user_login')) def test_file_edit_out(self): "Testing /file/edit/<file_id>" response = self.client.get( reverse('documents_file_edit', args=[self.file.id])) self.assertRedirects(response, reverse('user_login')) def test_file_delete_out(self): "Testing /file/view/<file_id>" response = self.client.get( reverse('documents_file_delete', args=[self.file.id])) self.assertRedirects(response, reverse('user_login')) # Web Links def test_weblink_add_typed_out(self): "Testing /documents/weblink/add/<folder_id>" response = self.client.get( reverse('documents_weblink_add_typed', args=[self.folder.id])) self.assertRedirects(response, reverse('user_login')) def test_weblink_add_out(self): "Testing /documents/weblink/add/" response = self.client.get(reverse('documents_weblink_add')) self.assertRedirects(response, reverse('user_login')) def test_weblink_view_out(self): "Testing /documents/view/<weblink_id>" response = self.client.get( reverse('documents_weblink_view', args=[self.link.id])) self.assertRedirects(response, reverse('user_login')) def test_weblink_edit_out(self): "Testing /documents/edit/<weblink_id>" response = self.client.get( reverse('documents_weblink_edit', args=[self.link.id])) self.assertRedirects(response, reverse('user_login')) def test_weblink_delete_out(self): "Testing /documents/delete/<weblink_id>" response = self.client.get( reverse('documents_weblink_delete', args=[self.link.id])) self.assertRedirects(response, reverse('user_login'))
def Upload(request): if request.method != "POST": raise Http404 if not request.FILES: if "cliptext" not in request.POST: raise Http404 token = utils.gentoken() while os.path.isdir("/var/www/synchy.org/main/synchy-django/media/%s" % token): token = utils.gentoken() os.mkdir("/var/www/synchy.org/main/synchy-django/media/%s" % token) os.mkdir("/var/www/synchy.org/main/synchy-django/media/%s/files" % token) if not request.FILES: if 'cliptext' in request.POST: group = Group() group.token = token group.multi = False group.save() file = File() file.group = group file.name = "clipboard.txt" file.mime = "text/plain" file.save() data = request.POST['cliptext'] handle = open("/var/www/synchy.org/main/synchy-django/media/%s/files/%s" % (token, file.name), 'w+') handle.write(data) handle.close() else: os.rmdir("/var/www/synchy.org/main/synchy-django/media/%s/files" % token) os.rmdir("/var/www/synchy.org/main/synchy-django/media/%s" % token) return Http404 else: if len(request.FILES) != 1: os.rmdir("/var/www/synchy.org/main/synchy-django/media/%s/files" % token) os.rmdir("/var/www/synchy.org/main/synchy-django/media/%s" % token) raise Http404 else: if 'file' in request.FILES: group = Group() group.token = token group.multi = False group.save() file = File() file.group = group file.name = request.FILES['file'].name file.mime = request.FILES['file'].content_type file.save() data = request.FILES['file'].read() handle = open("/var/www/synchy.org/main/synchy-django/media/%s/files/%s" % (token, file.name), 'w+') handle.write(data) handle.close() elif 'zip' in request.FILES: group = Group() group.token = token group.multi = True group.save() if request.FILES['zip'].content_type != "application/octet-stream": os.rmdir("/var/www/synchy.org/main/synchy-django/media/%s/files" % token) os.rmdir("/var/www/synchy.org/main/synchy-django/media/%s" % token) raise Http404 data = request.FILES['zip'].read() handle = open("/var/www/synchy.org/main/synchy-django/media/%s/%s%s%s%s" % (token, "files-", token[:2], token[-2:], ".zip"), 'w+') handle.write(data) handle.close() os.system('cd "%s/var/www/synchy.org/main/synchy-django/media/%s/files/"; sudo jar -xf %s/var/www/synchy.org/main/synchy-django/media/%s/files-%s%s.zip' % (os.getcwd(), token, os.getcwd(), token, token[:2], token[-2:])) zfile = Zip() zfile.group = group zfile.name = "%s%s%s%s" % ("files-", token[:2], token[-2:], ".zip") zfile.save() mime = magic.Magic(mime=True) for name in os.listdir("/var/www/synchy.org/main/synchy-django/media/%s/files/" % token): file = File() file.group = group file.name = name file.mime = mime.from_file("/var/www/synchy.org/main/synchy-django/media/%s/files/%s" % (token, name)) file.save() else: os.rmdir("/var/www/synchy.org/main/synchy-django/media/%s/files" % token) os.rmdir("/var/www/synchy.org/main/synchy-django/media/%s" % token) raise Http404 return HttpResponse(token)
def copy_folder(request, folder_id): if not request.user.is_authenticated(): return HttpResponseRedirect(reverse('existing_user'), { 'logged_in': False, 'form': forms.LoginForm(), }) if request.method == 'POST': form = forms.FolderForm(request.POST) filterargs = {'author': request.user, 'name': request.POST['name']} if Folder.objects.filter(**filterargs): return render(request, 'secure_witness/copy_folder.html', { 'folder_taken': True, 'folder': Folder.objects.get(pk = folder_id), 'folder_id': folder_id, 'user': request.user, 'form': form, 'logged_in': request.user.is_authenticated(), }) if form.is_valid(): original_folder = Folder.objects.get(pk = folder_id) folder = Folder( author = original_folder.author, name = request.POST['name'], date_created = original_folder.date_created, date_modified = original_folder.date_modified, location = request.POST['location'], description = request.POST['description'] ) folder.save() for original_bulletin in Bulletin.objects.filter(folder = original_folder): bulletin = Bulletin( author = original_bulletin.author, name = original_bulletin.name, folder = folder, date_created = original_bulletin.date_created, date_modified = original_bulletin.date_modified, location = original_bulletin.location, description = original_bulletin.description ) bulletin.save() for original_file in File.objects.filter(bulletin = original_bulletin): newFile = File( author = original_file.author, bulletin = bulletin, content = original_file.content, name = original_file.name, rand = original_file.rand, check = original_file.check, encryption_params = original_file.encryption_params, date_created = original_file.date_created, date_modified = original_file.date_modified ) newFile.save() return HttpResponseRedirect(reverse('home'), { 'logged_in': request.user.is_authenticated(), 'form': forms.LoginForm(), }) else: f = get_object_or_404(Folder, pk = folder_id) form = forms.FolderForm(instance = f) return render(request, 'secure_witness/copy_folder.html', { 'folder_id': folder_id, 'form': form, 'folder': Folder.objects.get(pk = folder_id), 'logged_in': request.user.is_authenticated(), })
def copy_bulletin(request, bulletin_id): if not request.user.is_authenticated(): return HttpResponseRedirect(reverse('existing_user'), { 'logged_in': request.user.is_authenticated(), 'form': forms.LoginForm(), }) if request.method == 'POST': form = forms.BulletinForm(request.POST) original_bulletin = Bulletin.objects.get(pk = bulletin_id) f = original_bulletin.folder filterargs = {'author': request.user, 'name': request.POST['name'], 'folder': f} if Bulletin.objects.filter(**filterargs): return render(request, 'secure_witness/copy_bulletin.html', { 'bulletin_taken': True, 'bulletin_id': bulletin_id, 'bulletin': original_bulletin, 'user': request.user, 'form': form, 'folder': f, 'folder_id': f.pk, 'logged_in': request.user.is_authenticated(), }) if form.is_valid(): bulletin = Bulletin( author = original_bulletin.author, name = request.POST['name'], folder = original_bulletin.folder, date_created = datetime.now(), date_modified = datetime.now(), location = request.POST['location'], description = request.POST['description'] ) bulletin.save() for original_file in File.objects.filter(bulletin = original_bulletin): newFile = File( author = original_file.author, bulletin = bulletin, content = original_file.content, # name = original_file.name, name = 'test', rand = original_file.rand, check = original_file.check, encryption_params = original_file.encryption_params, date_created = datetime.now(), date_modified = datetime.now(), ) newFile.save() return HttpResponseRedirect(reverse('get_folder', kwargs={'folder_id': bulletin.folder.pk}), { 'folder_id': bulletin.folder.pk, 'folder': bulletin.folder, 'logged_in': request.user.is_authenticated(), }) else: b = get_object_or_404(Bulletin, pk = bulletin_id) f = b.folder form = forms.BulletinForm(instance = b) return render(request, 'secure_witness/copy_bulletin.html', { 'bulletin_id': bulletin_id, 'form': form, 'bulletin': Bulletin.objects.get(pk = bulletin_id), 'logged_in': request.user.is_authenticated(), 'folder': f, 'folder_id': f.pk, })
def upload_file(request, folder_id): #import pdb; pdb.set_trace() if request.method=='POST': handle_uploaded_file(request.FILES['file'], request.FILES['file'].name) f = File(file_name = request.FILES['file'].name, file_path = request.FILES['file'].name, parent_folder = folder_id, created_on = '2011-1-1 12:00', created_by = 1, last_updated_on = '2011-1-1 12:00', last_updated_by = 1) f.save()
def convert(request): if request.method=='POST': exfile = str(request.FILES['excelfile'].name) f = File() f.excel = request.FILES['excelfile'] f.save() sheet = pyexcel.get_sheet(file_name=f.excel.name) h=0 while h<3: i=4 if h==0: x=0 else: x=(h*80) while i<124: if h == 0: st=Student2() if h == 1: st=Student3() if h == 2: st=Student4() st.name = sheet[i,x+3] print st.name st.sap_id = sheet[i,x+2] st.s1_name = sheet[1,x+4] st.s1_t_c = sheet[i,x+7] st.s1_t_g = sheet[i,x+9] st.s1_p_c = sheet[i,x+12] st.s1_p_g = sheet[i,x+13] st.s1_l = 4 st.s1_t = 1 st.s2_name = sheet[1,x+15] st.s2_t_c = sheet[i,x+18] st.s2_t_g = sheet[i,x+20] st.s2_p_c = sheet[i,x+23] st.s2_p_g = sheet[i,x+24] st.s2_l = 3 st.s2_p = 1 st.s3_name = sheet[1,x+26] st.s3_t_c = sheet[i,x+29] st.s3_t_g = sheet[i,x+31] st.s3_p_c = sheet[i,x+34] st.s3_p_g = sheet[i,x+35] st.s3_l = 3 st.s3_p = 1 st.s4_name = sheet[1,x+37] st.s4_t_c = sheet[i,x+40] st.s4_t_g = sheet[i,x+42] st.s4_p_c = sheet[i,x+47] st.s4_p_g = sheet[i,x+49] st.s4_l = 5 st.s4_p = 2 st.s5_name = sheet[1,x+51] st.s5_t_c = sheet[i,x+54] st.s5_t_g = sheet[i,x+56] st.s5_p_c = sheet[i,x+61] st.s5_p_g = sheet[i,x+63] st.s5_l = 4 st.s5_p = 2 st.s6_name = sheet[1,x+65] st.s6_t_c = sheet[i,x+68] st.s6_t_g = sheet[i,x+70] st.s6_l = 2 st.s7_name = sheet[1,x+72] st.s7_t_c = sheet[i,x+73] st.s7_t_g = sheet[i,x+74] st.s7_p = 4 st.totalc = 27 st.totalg = sheet[i,x+78] st.gpa = sheet[i,x+79] st.save() i+=1 h+=1 f.delete() return render(request,"convert.html")
def upload(request): if request.method == 'POST': # 上传到本地目录 try: path = request.POST.get('path') proxy = request.POST.get('proxy') proxy_host = request.POST.getlist('proxy_host') # 上传到本地 f = request.FILES['file'] df = handle_uploaded_file(f) files = {'file': (f.name, open(df, 'rb'))} params = {'action': 'upload'} # 通过proxy处理文件 proxy_obj = Proxy.objects.get(id=proxy) tnow = datetime.datetime.now() # 调用proxy接口,上传文件 api = API('{0}/v1.0/upload'.format(proxy_obj.url), proxy_obj.username, CRYPTOR.decrypt(proxy_obj.password)) result, code = api.req_post(data=params, files=files) if code != 200: file = File(path=path, proxy=proxy_obj, create_time=tnow, status='01', result="上传文件失败") file.save() raise ServerError(result['messege']) # 上传文件成功之后,调用proxy接口,进行文件上传任务 hosts = [] if not proxy_host: hosts = Asset.objects.all().filter(proxy=proxy_obj) if not hosts: # 没有可执行主机 file = File(path=path, proxy=proxy_obj, create_time=tnow, status='01', result="没有可执行主机") file.save() raise RuntimeError("没有可执行主机") else: for host_id in proxy_host: hosts.append(Asset.objects.get(id=host_id)) host_list = [] resource = [] params = {} trigger_kwargs = {} trigger_kwargs['year'] = tnow.year trigger_kwargs['month'] = tnow.month trigger_kwargs['day'] = tnow.day trigger_kwargs['hour'] = tnow.hour trigger_kwargs['minute'] = tnow.minute+1 trigger_kwargs['second'] = tnow.second params['trigger_kwargs'] = trigger_kwargs params['task_name'] = 'ansible' task_kwargs = {} task_kwargs['module_name'] = 'copy' task_kwargs['module_args'] = 'src={0} dest={1}'.format(result.get('fp'), path) # 构建inventory 和 构建主机list for host in hosts: host_list.append(host.networking.all()[0].ip_address) tmp_d = dict() tmp_d['hostname'] = host.networking.all()[0].ip_address tmp_d['port'] = host.port tmp_d['username'] = host.username tmp_d['password'] = CRYPTOR.decrypt(host.password) # 用于前端确定选择的asset tmp_d['id'] = host.id resource.append(tmp_d) task_kwargs['host_list'] = host_list task_kwargs['resource'] = resource params['task_kwargs'] = task_kwargs # 调用proxy接口,创建任务 api = APIRequest('{0}/v1.0/job'.format(proxy_obj.url), proxy_obj.username, CRYPTOR.decrypt(proxy_obj.password)) result, code = api.req_post(json.dumps(params)) if code != 200: file = File(path=path, proxy=proxy_obj, create_time=tnow, status='01', result="上传文件失败") file.save() else: file = File(path=path, proxy=proxy_obj, task_uuid=result['job']['job_id'], create_time=tnow) file.save() except Exception, e: logger.error(traceback.format_exc()) return HttpResponseRedirect(reverse('file_upload'))