예제 #1
0
파일: views.py 프로젝트: sizzlelab/Arki
def index(request):
    """
    Renders the index page of Fourdnest
    """
    messageform = MessageForm()
    if request.method == 'POST': # If the form has been submitted...
        form = MessageForm(request.POST, request.FILES) # A form bound to the POST data
        if form.is_valid(): # File was posted with form
            e = Egg(caption=form.cleaned_data.get('message'))
            e.user = request.user if request.user.is_authenticated() else None
            e.save()
            return HttpResponseRedirect(reverse('fourdnest_index'))
    latest_objects = Egg.objects.all()
    latest_objects = latest_objects.order_by('-id')[:30]

    for obj in latest_objects:
        if obj.content:
            _, obj.fileext = os.path.splitext(obj.content.originalfilename)
    return _render_to_response(request, 'fourdnest_base.html', {
        'latest_objects': latest_objects,
        #'latest_object_form': latest_object_form,
        'messageform': messageform,
        'cf': CommentForm(),
    })
예제 #2
0
파일: views.py 프로젝트: sizzlelab/Arki
def simple_upload(request):
    """
    Handles uploaded files
    """
    try:
        if request.method == 'POST': # If the form has been submitted...
            user =  request.user if request.user.is_authenticated() else None
            form = UploadForm(request.POST, request.FILES) # A form bound to the POST data
            if form.is_valid(): # File was posted with form
                c = None
                kwargs = {}
                kwargs['author'] = user.username.title() if user else 'Anonymous'
                # Create a new Egg
                e = Egg(**kwargs)
                print kwargs
                for filefield, tmpname in handle_uploaded_file(request):
                    print "HANDLING FILE:", filefield, tmpname
                    c = Content(**kwargs)
                    originalname = str(request.FILES["file"])
                    # c.user = request.user # Only authenticated users can use this view
                    c.set_file(originalname, tmpname) # Save uploaded file to filesystem
                    c.get_type_instance() # Create thumbnail if it is supported
                    c.save()
                    e.content = c
                    e.uid = c.uid
                    break # We save only the first file
                if c:
                    c.user = user
                    c.save()
                e.user = user
                print "USER", user
                if user:
                    response_status = 200 # Created
                else:
                    response_status = 401 # Unauthorized
                e.save()
                # We can handle tags after egg has id (it is saved)
                response = HttpResponse(status=response_status)
                #response.status_code = 201
                # FIXME: use reverse()
                #return HttpResponseRedirect(reverse('egg api', args=[e.uid]))
                response['Location'] = '/fourdnest/api/v1/egg/%s/' % e.uid
                return response
            else:
                response = HttpResponse(status=204)
                return response
        else:
            raise Http404
    except Exception, err:
        print err
        raise
        return HttpResponse("Server error", status=500)
예제 #3
0
파일: views.py 프로젝트: sizzlelab/Arki
def api_upload(request):
    """
    Renders the upload form page.
    """
    try:
        if request.method == 'POST': # If the form has been submitted...
            #for header in request.META.keys():
            #    if header.startswith('HTTP'):
            #        print header, request.META[header]
            #print request.raw_post_data[:1000]
            #if request.user.is_authenticated() is False:
            #    return HttpResponse(status=401)
            form = UploadForm(request.POST, request.FILES) # A form bound to the POST data
            #validate_authorization(request)
            if form.is_valid(): # File was posted with form
                c = None
                data = dict(request.POST)
                jsondata = request.POST.get('data')
                if jsondata is None: # Temporary fix for ambiguous parameter name data / metadata
                    jsondata = request.POST.get('metadata')
                if jsondata:
                    try: # data is a json string containing the same keys as multipart form
                        data = json.loads(jsondata)
                    except: # if it was not valid json, use normal post data
                        data = dict(request.POST)
                        #raise
                SUPPORTED_FIELDS = ['title', 'caption', 'author']
                kwargs = {}
                for field in SUPPORTED_FIELDS:
                    kwargs[field] = data.get(field, '')
                try:
                    kwargs['point'] = Point(float(data.get('lon')), float(data.get('lat')))
                except:
                    kwargs['point'] = None
                    #raise
                    pass
                # Create a new Egg
                e = Egg(**kwargs)
                print kwargs
                response_status = 201 # Created

                tags = data.get('tags')
                if tags:
                    tags = [x.lower() for x in tags]
                    tag_str = ','.join(tags)
                else:
                    tags = []
                    tag_str = ''
                user = c = None
                file_md5_sums = []
                for filefield, tmpname in handle_uploaded_file(request):
                    print "HANDLING FILE:", filefield, tmpname
                    c = Content(**kwargs)
                    c.keywords = tag_str
                    originalname = str(request.FILES["file"])
                    # c.user = request.user # Only authenticated users can use this view
                    c.set_file(originalname, tmpname) # Save uploaded file to filesystem
                    digest_maker = hashlib.md5()
                    with open(c.file.path, 'rb') as f:
                        buf = f.read(4096)
                        while buf:
                            digest_maker.update(buf)
                            buf = f.read(4096)
                    file_md5_sums.append(digest_maker.hexdigest())
                    #print digest_maker.hexdigest()
                    c.get_type_instance() # Create thumbnail if it is supported
                    c.save()
                    # Copy coordinates from content (parsed while saving it if they existed)
                    e.content = c
                    if e.point is None and c.point:
                        e.point = c.point
                    e.uid = c.uid
                    break # We save only the first file
                # Handle authorization after files are handled
                user =  validate_4dnest_authorization(request, file_md5_sums)
                if c:
                    c.user = user
                    c.save()
                e.user = user
                print "USER", user
                if user:
                    response_status = 201 # Created
                else:
                    response_status = 401 # Unauthorized
                e.save()
                # We can handle tags after egg has id (it is saved)
                #print "LOOPING TAGS"
                for tagname in tags:
                    try:
                        tag = Tag.objects.get(name=tagname)
                        #print "Tag old:",
                    except Tag.DoesNotExist:
                        tag = Tag(name=tagname)
                        tag.save()
                        #print "Tag new:",
                    #print tagname, tag
                    e.tags.add(tag)
                response = HttpResponse(status=response_status)
                #response.status_code = 201
                # FIXME: use reverse()
                #return HttpResponseRedirect(reverse('egg api', args=[e.uid]))
                response['Location'] = '/fourdnest/api/v1/egg/%s/' % e.uid
                return response
            else:
                response = HttpResponse(status=204)
                return response
        else:
            raise Http404
    except Exception, err:
        print err
        raise
        return HttpResponse("Server error", status=500)