Example #1
0
def log(*args):    
    if Config.__name__ != 'Development':
        return
    r = get_route()
    if r and '/static' in r.rule:
        return
    # logging only on staging / development env
    if console:
        console.log(*args)
Example #2
0
def debug(error=None):
    if hasattr(error, 'traceback'):
        msg = error.traceback
        if not msg:
            # Bottle raised exception
            msg = error.body
    else:
        msg = error
    if console:
        header = console.get_header()
        if header:
            k,v = header
            response.headers[k] = v
    if error:    
        if request.is_xhr and console:
            console.log(msg)
            return { 'error': True }
        else:
            return '<pre>%s</pre>' %  html_escape(msg)
def log_api_exception_to_browser_console(sender, exception, **extra):
    """Log an API exception to the browser's console."""
    if sender.debug and sender.config.get('API_LOG_EXCEPTIONS_TO_BROWSER_CONSOLE'):
        try:
            import chromelogger

            type_, value_, traceback_ = sys.exc_info()
            tbs = traceback.extract_tb(traceback_)
            exc_only = traceback.format_exception_only(type_, value_)

            group_func = chromelogger.group_collapsed
            chromelogger.group_collapsed("%cAPI Server Error:", 'color: red;', str(exc_only[-1]))
            chromelogger.log('Traceback (most recent call last):')
            for i, tb in enumerate(tbs):
                if i == len(tbs) - 1:
                    group_func = chromelogger.group  # Expand the last stack frame
                group_func('%cFile "%s", line %i, in %s', 'font-weight: normal;', tb[0], tb[1], tb[2])
                chromelogger.log(tb[3])
                chromelogger.group_end()
            chromelogger.warn(''.join(exc_only))
            chromelogger.group_end()
        except Exception:
            pass  # Failures here should not prevent the API error response
Example #4
0
def hello():
    console.log('Hello console!')
    console.get_header()
    return "Hello World!"
Example #5
0
def import_personal_files(request):
    available_storage = get_list_or_404(filter_by_access(request.user, Storage, write=True).order_by('title'))
    available_collections = get_list_or_404(filter_by_access(request.user, Collection))
    writable_collection_ids = list(filter_by_access(request.user, Collection, write=True).values_list('id', flat=True))

    storage_choices = choices = [make_storage_select_choice(s, request.user) for s in available_storage]

    # if DEFAULT_PERSONAL_COLLECTION and RESTRICT_TO_DEFAULTS:
    #     available_collections = DEFAULT_PERSONAL_COLLECTION
    #
    # if DEFAULT_PERSONAL_STORAGE and RESTRICT_TO_DEFAULTS:
    #     available_storage = DEFAULT_PERSONAL_STORAGE

    class UploadFileForm(forms.Form):
        collection = forms.ChoiceField(choices=((c.id,
                                                 '%s%s' % ('*' if c.id in writable_collection_ids else '',
                                                           c.title)) for c in sorted(available_collections,
                                                                                     key=lambda c: c.title)))
        storage = forms.ChoiceField(choices=storage_choices)
        file = forms.FileField()
        create_records = forms.BooleanField(required=False)
        replace_files = forms.BooleanField(required=False, label='Replace files of same type')
        multiple_files = forms.BooleanField(required=False,
                                           label='Allow multiple files of same type')
        personal_records = forms.BooleanField(required=False)

        def clean(self):
            cleaned_data = self.cleaned_data
            if any(self.errors):
                return cleaned_data
            # personal = cleaned_data['personal_records']
            # if not personal and not int(cleaned_data['collection']) in writable_collection_ids:
            #     self._errors['collection'] = ErrorList(["Can only add personal records to selected collection"])
            #     del cleaned_data['collection']
            return cleaned_data
    console.log(request.method)
    if request.method == 'POST':
        # get the form and check that it's valid
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
        # get settings from form data

            create_records = True
            replace_files = True
            multiple_files = True
            personal_records = True

            collection = get_object_or_404(
                filter_by_access(request.user,
                                 Collection.objects.filter(
                                     id=form.cleaned_data['collection']), write=None))
            storage = get_object_or_404(
                filter_by_access(request.user, Storage.objects.filter(id=form.cleaned_data['storage'].split(',')[0]),
                                 write=True))
            file = request.FILES['file']
            console.log(file)
            record = None

            limit = storage.get_upload_limit(request.user)
            if limit > 0 and file.size > limit * 1024:
                result = "The uploaded file is too large (%d>%d)." % (file.size, limit * 1024)
            else:

                mimetype = mimetypes.guess_type(file.name)[0] or file.content_type

                owner = request.user
                #if personal_records else None
                id = os.path.splitext(file.name)[0]

                # find record by identifier
                titlefield = standardfield('title')
                idfield = standardfield('identifier')

                # Match identifiers that are either full file name (with extension) or just base name match
                records = find_record_by_identifier((id, file.name,),
                                                    collection,
                                                    owner=owner,
                                                    ignore_suffix=multiple_files)
                result = "File skipped."

                if len(records) == 1:
                    # Matching record found
                    record = records[0]
                    media = record.media_set.filter(storage=storage, mimetype=mimetype)
                    media_same_id = media.filter(name=id)
                    if len(media) == 0 or (len(media_same_id) == 0 and multiple_files):
                        # No media yet
                        media = Media.objects.create(record=record,
                                                     name=id,
                                                     storage=storage,
                                                     mimetype=mimetype)
                        media.save_file(file.name, file)
                        result = "File added (Identifier '%s')." % id
                    elif len(media_same_id) > 0 and multiple_files:
                        # Replace existing media with same name and mimetype
                        media = media_same_id[0]
                        media.delete_file()
                        media.save_file(file.name, file)
                        result = "File replaced (Identifier '%s')." % id
                    elif replace_files:
                        # Replace existing media with same mimetype
                        media = media[0]
                        media.delete_file()
                        media.save_file(file.name, file)
                        result = "File replaced (Identifier '%s')." % id
                    else:
                        result = "File skipped, media files already attached."
                elif len(records) == 0:
                    # No matching record found
                    if create_records:
                        # Create a record
                        record = Record.objects.create(name=id, owner=owner)
                        CollectionItem.objects.create(collection=collection, record=record)
                        FieldValue.objects.create(record=record, field=idfield, value=id, order=0)
                        FieldValue.objects.create(record=record, field=titlefield, value=id, order=1)
                        media = Media.objects.create(record=record,
                                                     name=id,
                                                     storage=storage,
                                                     mimetype=mimetype)
                        media.save_file(file.name, file)
                        result = "File added to new record (Identifier '%s')." % id
                    else:
                        result = "File skipped, no matching record found (Identifier '%s')." % id
                else:
                    result = "File skipped, multiple matching records found (Identifier '%s')." % id
                    # Multiple matching records found
                    pass

            if request.POST.get('swfupload') == 'true':
                html = render_to_string('storage_import_file_response.html',
                                        {'result': result,
                                         'record': record, },
                                        context_instance=RequestContext(request)
                )
                return HttpResponse(content=simplejson.dumps(dict(status='ok', html=html)),
                                    mimetype='application/json')

            request.user.message_set.create(message=result)
            next = request.GET.get('next', request.get_full_path())
            return HttpResponseRedirect(next)

        else:
            # invalid form submission
            if request.POST.get('swfupload') == 'true':
                html = render_to_string('storage_import_file_response.html',
                                        {'result': form.errors},
                                        context_instance=RequestContext(request)
                )
                console.log(html)
                return HttpResponse(content=simplejson.dumps(dict(status='ok', html=html)),
                                    mimetype='application/json')

    else:
        form = UploadFileForm()
        console.log(form)

    return render_to_response('import_personal_files.html',
                              {'upload_form': form,
                              },
                              context_instance=RequestContext(request))
Example #6
0
 def get_context_data(self, **kwargs):
     context = super(ConfigurationListView, self).get_context_data(**kwargs)
     console.log("context")
     # context['now'] = timezone.now()
     return context