def handle_attachment(message, content, related=False): # r = '' # if related: # r = '(r)' filename, encoding = decode_header(content.get_filename())[0] if encoding: filename = filename.decode(encoding, errors='replace') #if not related: # print "saving attachment [%s] of type %s from message %d %s" % (filename, content.get_content_type(), message.id, r) a = Attachment() a.filename = filename # TODO need to parse weird strings from this if not a.filename: a.filename = str(uuid.uuid4()) a.content_type = content.get_content_type() a.stored_location = os.path.join(files_dir, str(message.id), get_valid_filename(a.filename)) # probably want to fix this too a.mime_related = related # load the file file_content = content.get_payload(decode=1) a.file_md5 = hashlib.md5(file_content).hexdigest() # again, probably a better way to do this than all in memory # actually write it do disk - should wrap this in a try except too if not os.path.exists(os.path.join(files_dir, str(message.id))): os.makedirs(os.path.join(files_dir, str(message.id))) with open(a.stored_location, 'wb') as fp: fp.write(file_content) a.message = message a.save()
def form_builder(request, form, model, holiday_id, item_id, html, field): data = {'holiday_id': holiday_id} inst = None init_attachments = None if item_id: inst = model.objects.get(pk=item_id) data['title'] = inst.name data['item_id'] = item_id if inst.files.count() > 0: init_attachments = {"attachments": inst.files.all()} else: data['title'] = 'Add %s' % (field) if request.method == 'POST': form = form(request.POST, instance=inst) if form.is_valid(): inst = form.save(inst) inst.save() if 'file' in request.FILES: fileitem = request.FILES['file'] newFile = Attachment(attachment=fileitem, user=request.user) newFile.save() inst.files.add(newFile) inst.save() holiday = Holiday.objects.get(pk=holiday_id) getattr(holiday, field).add(inst) holiday.save() messages.success(request, 'Saved successfully!') return HttpResponseRedirect('/holiday/' + str(holiday_id)) data['form'] = form else: data['form'] = form(instance=inst, initial=init_attachments) return render_to_response(html, data, RequestContext(request))
def add(request): if request.method == 'POST': form = AddViolation(request.POST) if form.is_valid(): msg=_("Thank you for submitting a new report. To finalize your submission please confirm using your validation key.\nYour verification key is %s/%s%s\nPlease note that reports are moderated, it might take some time before your report appears online. Thank you for your patience.") actid=sendverifymail('activate?key=',form.cleaned_data['email'], msg) operator, created = Operator.objects.get_or_create(name=form.cleaned_data['operator']) v=Violation( country = form.cleaned_data['country'], operator_ref = operator, contract = form.cleaned_data['contract'], resource = form.cleaned_data['resource'], resource_name = form.cleaned_data['resource_name'], type = form.cleaned_data['type'], media = form.cleaned_data['media'], temporary = form.cleaned_data['temporary'], contractual = form.cleaned_data['contractual'], contract_excerpt = sanitizeHtml(form.cleaned_data['contract_excerpt']), loophole = form.cleaned_data['loophole'], activationid = actid ) v.save() #c=Confirmation(key='', email=form.cleaned_data['email'], violation=v) #c.save() c = Comment( comment=form.cleaned_data['comment'], submitter_email=form.cleaned_data['email'], submitter_name=form.cleaned_data['nick'], consent=form.cleaned_data['consent'], timestamp=datetime.now(), violation=v, ) c.save() for f in request.FILES.getlist('attachments[]'): a=Attachment(comment=c, name=f.name, type=f.content_type) m = hashlib.sha256() for chunk in f.chunks(): m.update(chunk) sname=m.hexdigest() a.storage.save(sname,f) a.save() messages.add_message(request, messages.INFO, _('Thank you for submitting this report, you will receive a verification email immediately, if not check your spam folder.')) return HttpResponseRedirect('/') # Redirect after POST else: form = AddViolation() v_list = Violation.objects.filter(activationid='',featuredcase__isnull=False).order_by('id').reverse()[:3] return render_to_response( 'index.html', { 'form': form, 'violations': v_list }, context_instance=RequestContext(request))
def add(request): if request.method == 'POST': form = AddViolation(request.POST) if form.is_valid(): msg=_("Thank you for submitting a new report. To finalize your submission please confirm using your validation key.\nYour verification key is %s/%s%s\nPlease note that reports are moderated, it might take some time before your report appears online. Thank you for your patience.") actid=sendverifymail('activate?key=',form.cleaned_data['email'], msg) operator, created = Operator.objects.get_or_create(name=form.cleaned_data['operator']) v=Violation( country = form.cleaned_data['country'], operator_ref = operator, contract = form.cleaned_data['contract'], resource = form.cleaned_data['resource'], resource_name = form.cleaned_data['resource_name'], type = form.cleaned_data['type'], media = form.cleaned_data['media'], temporary = form.cleaned_data['temporary'], contractual = form.cleaned_data['contractual'], contract_excerpt = sanitizeHtml(form.cleaned_data['contract_excerpt']), loophole = form.cleaned_data['loophole'], activationid = actid ) v.save() #c=Confirmation(key='', email=form.cleaned_data['email'], violation=v) #c.save() c = Comment( comment=form.cleaned_data['comment'], submitter_email=form.cleaned_data['email'], submitter_name=form.cleaned_data['nick'], consent=form.cleaned_data['consent'], timestamp=datetime.now(), violation=v, ) c.save() for f in request.FILES.getlist('attachments[]'): a=Attachment(comment=c, name=f.name, type=f.content_type) m = hashlib.sha256() for chunk in f.chunks(): m.update(chunk) sname=m.hexdigest() a.storage.save(sname,f) a.save() messages.add_message(request, messages.INFO, _('Thank you for submitting this report, you will receive a verification email immediately, if not check your spam folder.')) return HttpResponseRedirect('/') # Redirect after POST else: form = AddViolation() v_list = Violation.objects.filter(activationid='',featuredcase__isnull=False).order_by('id').reverse()[:3] return render_to_response( 'index.html', { 'form': form, 'violations': v_list }, context_instance=RequestContext(request))
def fetch_menu(): # get provider, provider->get_fresh_menus menu_files = download_menu_files() for menu_file in menu_files: with open(menu_file, 'r') as mf: fs = Attachment(menufile=File(mf)) fs.save() load_menu_from_file(menu_file, fs) # TODO verbose output return True
class EventifyAttachmentCreationTest(TestCase): attachment = None def setUp(self): self.attachment = Attachment(file="eventify_model.pdf") self.attachment.save() def test_attachment_url_creation(self): """ Ensure we can retrieve list of venues. """ # check if URL actually exists attach_url = self.attachment.attachment_url request = requests.get(attach_url) self.assertEqual(request.status_code, status.HTTP_200_OK)
def send_private_message(sender, receiver, message, attachments = ''): if isinstance(sender, int): sender = User.objects.get(id = sender) if isinstance(receiver, int): receiver = User.objects.get(id = receiver) pm = PrivateMessage(sender = sender, receiver = receiver, body_text = message) pm.save() if attachments: for s in attachments.split("|"): url, file_name = s.split("*") attachment = Attachment(url = url, file_name = file_name) attachment.save() pm.attachments.add(attachment) return pm # def send_private_message_and_notify(sender, receiver, message, attachments = []): # pm = send_private_message(sender, receiver, message) # if pm.sender != pm.receiver: # notification.send_notification(pm.receiver, 'pm', private_message = pm) # return pm
def attachment_formset_handler(request, object): if request.method == "POST" and request.POST.has_key("attachments-TOTAL_FORMS"): attachment_formset = AttachmentFormSet(request.POST, prefix = "attachments" ) if attachment_formset.is_valid(): for form in attachment_formset: if form.cleaned_data.has_key("id") and form.cleaned_data["id"]: if not form.cleaned_data["file"] or form.cleaned_data["DELETE"] == True: form.cleaned_data["id"].delete() else: form.save() elif form.cleaned_data.has_key("file") and form.cleaned_data["file"]: if not object.id: object.save() attachment = Attachment(file = form.cleaned_data["file"], content_type = ContentType.objects.get_for_model(object), object_id = object.id, ) attachment.save() else: attachment_formset = AttachmentFormSet(queryset = object.attachments.all(), prefix = "attachments" ) return attachment_formset
def ajax_upload(request, object_id=None, record=None): try: object = None if request.method == "POST": if request.is_ajax(): # the file is stored raw in the request upload = request is_raw = True # AJAX Upload will pass the filename in the querystring if it # is the "advanced" ajax upload try: filename = request.GET['qqfile'] content_type = "application/octet-stream" except KeyError: return HttpResponseBadRequest("AJAX request not valid") # not an ajax upload, so it was the "basic" iframe version with # submission via form else: is_raw = False if len(request.FILES) == 1: # FILES is a dictionary in Django but Ajax Upload gives the uploaded file an # ID based on a random number, so it cannot be guessed here in the code. # Rather than editing Ajax Upload to pass the ID in the querystring, # observer that each upload is a separate request, # so FILES should only have one entry. # Thus, we can just grab the first (and only) value in the # dict. upload = request.FILES.values()[0] content_type = upload.content_type else: raise Http404("Bad Upload") filename = upload.name random.seed() filehash = str(random.getrandbits(128)) savefile = join( getattr(settings, 'MEDIA_ROOT'), 'attachments', filehash) # save the file success = save_upload(upload, savefile, is_raw) attachment = Attachment(filename=filename, content_type=content_type, uploaded_by=request.user.profile, attached_file=filehash) if record: attachment.attached_record = record about = record.about.all() if about.count(): attachment.attached_object = about[0] object = attachment.attached_object else: object = Object.objects.get(id=object_id) attachment.attached_object = object attachment.save() if object: object.set_last_updated() # TODO: smart markup and return as string, and object id, different # classnames,id or attribute for update records and objects if success: ret_json = {'success': success, 'object_id': object.id if object else None, 'update_id': record.id if record else None} else: ret_json = {'success': False, 'object_id': None, 'update_id': None} return HttpResponse(json.dumps(ret_json)) except: pass
def attachments(request, path): """ On delete: delete the file at the path. On post: post a new file at the path, unless the On delete with path, delete the file. On post with path, replace the file. On post without path, create a new file. On get with path, download the file. On get without path, return a list of files in the thread. TODO: On head with path, return info about the file. """ if request.method == 'DELETE' or request.POST.get('method') == 'delete': for path in get_files(request, path): attachment = Attachment.objects.get(path=path) for reciever, response in attachment_manipulate.send(sender=attachment, request=request, action='delete'): if isinstance(response, HttpResponse): return response attachment.delete() return HttpResponse(json.dumps(True), content_type="application/json") elif request.POST.get('method') == 'hide': for path in get_files(request, path): attachment = Attachment.objects.get(path=path) for reciever, response in attachment_manipulate.send(sender=attachment, request=request, action='hide'): if isinstance(response, HttpResponse): return response attachment.hidden = True attachment.save() return HttpResponse(json.dumps(True), content_type="application/json") elif request.POST.get('method') == 'show': for path in get_files(request, path): attachment = Attachment.objects.get(path=path) for reciever, response in attachment_manipulate.send(sender=attachment, request=request, action='show'): if isinstance(response, HttpResponse): return response attachment.hidden = False attachment.save() return HttpResponse(json.dumps(True), content_type="application/json") elif request.POST.get('method') == 'zip': attachments = [] for path in get_files(request, path): attachment = Attachment.objects.get(path=path) for reciever, response in attachment_view.send(sender=attachment, request=request): if isinstance(response, HttpResponse): return response attachments.append(attachment) zip = AttachmentZip.create(attachments) response = HttpResponse(json.dumps(zip.info()), content_type="application/json", status=202) response['Location'] = zip.url return response elif request.method == 'POST': file = request.FILES['file'] path = posixpath.join(path, file._name) try: attachment = Attachment.objects.get(path=path) except: attachment = Attachment(path=path) attachment.file = file attachment.mimetype = file.content_type attachment.author = request.user for reciever, response in attachment_manipulate.send(sender=attachment, request=request, action='create'): if isinstance(response, HttpResponse): return response attachment.save() return HttpResponse(json.dumps(attachment.info()), content_type="application/json") elif path: attachment = get_object_or_404(Attachment, path=path) for reciever, response in attachment_view.send(sender=attachment, request=request): if isinstance(response, HttpResponse): return response if not attachment.file.storage.exists(attachment.file.path): raise Http404 response = HttpResponse(FileWrapper(attachment.file), content_type=attachment.mimetype) response['Content-Length'] = attachment.file.storage.size(attachment.file.path) response['Content-Disposition'] = "attachment; filename=%s" % attachment.file.name return response