Exemple #1
0
def get_insight_list(request):
    if request.method != 'GET':
        response = HttpResponseNotAllowed(['GET'])
        response.write("Error: only GET method is allowed")
        return response

    category = request.GET.get('category')
    start_date = request.GET.get('start_date')
    end_date = request.GET.get('end_date')
    status = request.GET.get('decision')

    insights = Insight.objects.order_by("-id")

    if start_date:
        try:
            start_date = datetime.strptime(start_date, "%Y-%m-%d")
            insights = insights.filter(create_date__gte=start_date)
        except ValueError:
            return HttpResponseBadRequest

    if end_date:
        try:
            end_date = datetime.strptime(end_date, "%Y-%m-%d")
            insights = insights.filter(create_date__lte=end_date)
        except ValueError:
            return HttpResponseBadRequest

    data = {"insights": [i.short for i in insights]}

    return JsonResponse(data)
Exemple #2
0
    def _ajax_upload(self, request, *args, **kwargs):
        if request.method == "POST":
            upload = request.FILES.get('qqfile', None)
            if not upload:
                return HttpResponseBadRequest("AJAX request not valid")

            filename = upload.name
            backend = self.get_backend()

            # custom filename handler
            filename = (backend.update_filename(request, filename, *args, **kwargs)
                        or filename)
            # save the file
            backend.setup(request, filename, *args, **kwargs)
            success = backend.upload(upload, filename, False, *args, **kwargs)

            # callback
            extra_context = backend.upload_complete(request, filename, uuid=request.POST['qquuid'], *args, **kwargs)

            if success is True:
                file_uploaded.send(sender=self.__class__, backend=backend, request=request, extra_context=extra_context)

            # let Ajax Upload know whether we saved it or not
            ret_json = {'success': success, 'filename': filename}
            if extra_context is not None:
                ret_json.update(extra_context)

            # although "application/json" is the correct content type, IE throws a fit
            return HttpResponse(json.dumps(ret_json, cls=DjangoJSONEncoder), content_type='text/html; charset=utf-8')
        else:
            response = HttpResponseNotAllowed(['POST'])
            response.write("ERROR: Only POST allowed")
            return response
Exemple #3
0
    def _ajax_upload(self, request, *args, **kwargs):
        if request.method == "POST":
            upload = request.FILES.get("qqfile", None)
            if not upload:
                return HttpResponseBadRequest("AJAX request not valid")

            filename = upload.name
            backend = self.get_backend()

            # custom filename handler
            filename = backend.update_filename(request, filename, *args, **kwargs) or filename
            # save the file
            backend.setup(request, filename, *args, **kwargs)
            success = backend.upload(upload, filename, False, *args, **kwargs)

            # callback
            extra_context = backend.upload_complete(request, filename, uuid=request.POST["qquuid"], *args, **kwargs)

            if success is True:
                file_uploaded.send(sender=self.__class__, backend=backend, request=request, extra_context=extra_context)

            # let Ajax Upload know whether we saved it or not
            ret_json = {"success": success, "filename": filename}
            if extra_context is not None:
                ret_json.update(extra_context)

            # although "application/json" is the correct content type, IE throws a fit
            return HttpResponse(json.dumps(ret_json, cls=DjangoJSONEncoder), content_type="text/html; charset=utf-8")
        else:
            response = HttpResponseNotAllowed(["POST"])
            response.write("ERROR: Only POST allowed")
            return response
    def _ajax_upload(self, request, *args, **kwargs):
        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:
                    if 'qqfile' in request.GET:
                        filename = request.GET['qqfile']
                    elif 'qqfilename' in request.GET:
                        filename = request.GET['qqfilename']
                    else:
                        filename = request.POST['qqfilename']
                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, observe
                    # 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]
                else:
                    raise Http404("Bad Upload")
                filename = upload.name

            backend = self.get_backend()

            # custom filename handler
            filename = (backend.update_filename(request, filename, *args, **kwargs)
                        or filename)
            # save the file
            backend.setup(filename, *args, **kwargs)
            success = backend.upload(upload, filename, is_raw, *args, **kwargs)

            if success:
                file_uploaded.send(sender=self.__class__, backend=backend, request=request)

            # callback
            extra_context = backend.upload_complete(request, filename, *args, **kwargs)

            # let Ajax Upload know whether we saved it or not
            ret_json = {'success': success, 'filename': filename}
            if extra_context is not None:
                ret_json.update(extra_context)

            # although "application/json" is the correct content type, IE throws a fit
            return HttpResponse(json.dumps(ret_json, cls=DjangoJSONEncoder), content_type='text/html; charset=utf-8')
        else:
            response = HttpResponseNotAllowed(['POST'])
            response.write("ERROR: Only POST allowed")
            return response
Exemple #5
0
    def _ajax_upload(self, request, *args, **kwargs):
        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:
                    if 'qqfile' in request.GET:
                        filename = request.GET['qqfile']
                    else:
                        filename = request.REQUEST['qqfilename']
                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, observe
                    # 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]
                else:
                    raise Http404("Bad Upload")
                filename = upload.name

            backend = self.get_backend()

            # custom filename handler
            filename = (backend.update_filename(request, filename, *args, **kwargs)
                        or filename)
            # save the file
            backend.setup(filename, *args, **kwargs)
            success = backend.upload(upload, filename, is_raw, *args, **kwargs)

            if success:
                file_uploaded.send(sender=self.__class__, backend=backend, request=request)

            # callback
            extra_context = backend.upload_complete(request, filename, *args, **kwargs)

            # let Ajax Upload know whether we saved it or not
            ret_json = {'success': success, 'filename': filename}
            if extra_context is not None:
                ret_json.update(extra_context)

            # although "application/json" is the correct content type, IE throws a fit
            return HttpResponse(json.dumps(ret_json, cls=DjangoJSONEncoder), content_type='text/html; charset=utf-8')
        else:
            response = HttpResponseNotAllowed(['POST'])
            response.write("ERROR: Only POST allowed")
            return response
Exemple #6
0
def get_patent_json(request):
    if request.method != 'GET':
        response = HttpResponseNotAllowed(['GET'])
        response.write("Error: only GET method is allowed")
        return response

    patent = Patent.objects.all()
    response_text = serializers.serialize('json', patent)
    return HttpResponse(response_text, content_type='application/json')
Exemple #7
0
def get_insight(request, insight_id):
    if request.method != 'GET':
        response = HttpResponseNotAllowed(['GET'])
        response.write("Error: only GET method is allowed")
        return response

    insight = get_object_or_404(Insight, id=insight_id)

    data = {"patent": insight.long}

    return JsonResponse(data)
Exemple #8
0
def get_patent_model(request, patent_id):
    if request.method != 'GET':
        response = HttpResponseNotAllowed(['GET'])
        response.write("Error: only GET method is allowed")
        return response
    try:
        patent = Patent.objects.filter(id=patent_id)
        response_text = serializers.serialize('json', patent)
        return HttpResponse(response_text, content_type='application/json')
    except:
        raise Http404
Exemple #9
0
    def _ajax_upload(self, request, *args, **kwargs):
        if request.method == "POST":
            upload = request.FILES.get('qqfile', None)
            if not upload:
                return HttpResponseBadRequest("AJAX request not valid")

            # get chunks
            chunk_index = int(request.POST.get('qqpartindex'))
            total_chunks = int(request.POST.get('qqtotalparts'))


            filename = upload.name

            file_id = request.POST['qquuid']

            backend = self.get_backend()

            # custom filename handler
            filename = (backend.update_filename(request, filename, *args, **kwargs)
                        or filename)

            backend.setup(filename, *args, **kwargs)
            success = backend.upload_chunk(upload, *args, **kwargs)

            # callback - edited
            extra_context = None
            if total_chunks == chunk_index +1:
                extra_context = backend.upload_complete(request, filename, file_id, *args, **kwargs)
                # file_uploaded.send(sender=self.__class__, backend=backend, request=request)

            # let Ajax Upload know whether we saved it or not
            if settings.DEBUG:
                ret_json = {'success': success, 'filename': filename}
            else:
                ret_json = {'success': success}
            
            if extra_context is not None:
                if settings.DEBUG:
                    ret_json.update(extra_context)

            # although "application/json" is the correct content type, IE throws a fit
            return HttpResponse(json.dumps(ret_json, cls=DjangoJSONEncoder), content_type='text/html; charset=utf-8')
        else:
            response = HttpResponseNotAllowed(['POST'])
            response.write("ERROR: Only POST allowed")
            return response
Exemple #10
0
def search_insight(request):
    if request.method != 'GET':
        response = HttpResponseNotAllowed(['GET'])
        response.write("Error: only GET method is allowed")
        return response

    keyword = request.GET.get('keyword')

    if keyword and keyword != '':
        result = Insight.search(keyword)

        data = {"insights": [i.short for i in result]}

        return JsonResponse(data)

    response = HttpResponse()
    response.write("No search_patent keyword provided")
    return response
Exemple #11
0
def get_patent_list(request):
    if request.method != 'GET':
        response = HttpResponseNotAllowed(['GET'])
        response.write("Error: only GET method is allowed")
        return response

    category = request.GET.get('category')
    start_date = request.GET.get('start_date')
    end_date = request.GET.get('end_date')
    decision = request.GET.get('status')

    patents = Patent.get_recent_list()

    if category:
        if category.isdigit():
            category = int(category)
            patents = patents.filter(category_code=category)

    if decision:
        if decision.isdigit():
            decision = int(decision)
            patents = patents.filter(decision=decision)

    if start_date:
        try:
            start_date = datetime.strptime(start_date, "%Y-%m-%d")
            patents = patents.filter(latest_date__gte=start_date)
        except ValueError:
            return HttpResponseBadRequest

    if end_date:
        try:
            end_date = datetime.strptime(end_date, "%Y-%m-%d")
            patents = patents.filter(latest_date__lte=end_date)
        except ValueError:
            return HttpResponseBadRequest

    data = {"patents": [p.short for p in patents]}
    return JsonResponse(data)
Exemple #12
0
def ajax_upload(request):
    if request.method == 'POST':
        for field_name in request.FILES:
            uploaded_file = request.FILES[field_name]

            datedir = time.strftime('%Y/%m/%d/', time.localtime(time.time()))
            dest_dir = conf.TEMP_DIR + datedir

            if not os.path.exists(str(dest_dir)):
                os.makedirs(str(dest_dir))

            salt = str(time.time()) + uploaded_file.name
            if isinstance(salt, unicode):
                salt = salt.encode('utf8')
            filename = hashlib.md5(salt).hexdigest()
            fn_ext = uploaded_file.name.split('.')[-1]

            # save to temp dir
            dest_path = dest_dir + filename + '.' + fn_ext
            dest = open(str(dest_path), 'wb+')
            for chunk in uploaded_file.chunks():
                dest.write(chunk)
            dest.close()

            # copy to media root
            media_path = time.strftime('uploads/media/%Y/%m/%d/', time.localtime(time.time())) + filename + '.' + fn_ext
            if not os.path.exists(settings.MEDIA_ROOT + time.strftime('uploads/media/%Y/%m/%d/', time.localtime(time.time()))):
                os.makedirs(settings.MEDIA_ROOT + time.strftime('uploads/media/%Y/%m/%d/', time.localtime(time.time())))

            import shutil
            shutil.copyfile(dest_path, settings.MEDIA_ROOT + media_path)

        ret_json = {'success': True, 'filename': media_path}        
        return HttpResponse(json.dumps(ret_json), mimetype="text/plain")
    else:
        response = HttpResponseNotAllowed(['POST'])
        response.write("ERROR: Only POST allowed")
        return response
Exemple #13
0
def send_email(request):
    if request.method != 'GET':
        response = HttpResponseNotAllowed(['GET'])
        response.write("Error: only GET method is allowed")

    email = request.GET.get("email")
    response = HttpResponse()
    if email:

        email_body = """
        The URL for the document is:
        http://%s%s""" % (
            request.get_host(),
            static('20160114-CGPDTM-DECISION-TAKEDA-833-KOLNP-2010.pdf'))

        send_mail(subject="TwoFourInsight Download",
                  message=email_body,
                  from_email="*****@*****.**",
                  recipient_list=[email])
        response.write("Send Succeed")
    else:
        response.write("Email Address is not given")

    return response
Exemple #14
0
    def _ajax_upload(self, request, *args, **kwargs):
        if request.method == "POST":
            filename = False
            headerValues = headers.initGlobals(request)
            if request.is_ajax() and False:
                # 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.POST['qqfilename']
                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, observe
                    # 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]
                else:
                    raise Http404("Bad Upload")

                if u'qqfilename' in request.POST:
                    filename = request.POST[u'qqfilename']
                else:
                    filesReq = request.FILES.getlist('qqfile')

                    if filesReq:
                        filesReq = filesReq[0]

                        filename = filesReq.name

            if not filename:
                return HttpResponse('Not filename found')

            backend = self.get_backend()

            # custom filename handler
            if u'qqpartindex' not in request.POST or request.POST[
                    u'qqpartindex'] == '0':
                kwargs['first_part'] = True
            else:
                kwargs['first_part'] = False

            filename_origin = filename

            project_id = headerValues['CURRENT_PROJECT'].id if headerValues[
                'CURRENT_PROJECT'] and headerValues[
                    'CURRENT_PROJECT'].id else None
            if project_id:
                backend.UPLOAD_DIR = 'projects/' + str(project_id)

            filename = (backend.update_filename(request, filename, *args, **
                                                kwargs) or filename)

            # save the file

            backend.setup(filename, *args, **kwargs)

            success = backend.upload(upload, filename, is_raw, *args, **kwargs)

            # callback
            extra_context = backend.upload_complete(request, filename, *args,
                                                    **kwargs)

            # let Ajax Upload know whether we saved it or not
            ret_json = {'success': success, 'filename': filename}
            if extra_context is not None:
                ret_json.update(extra_context)

            if u'qqpartindex' in request.POST and int(
                    request.POST[u'qqpartindex']) == int(
                        request.POST[u'qqtotalparts']) - 1:

                fileNow = PM_Files(projectId=headerValues['CURRENT_PROJECT'],
                                   authorId=request.user,
                                   name=filename_origin)
                try:
                    sId = int(request.POST.get('section_id', 0))
                except ValueError:
                    sId = 0

                version_of = int(request.POST.get('version_of', 0))

                if sId:
                    try:
                        fileNow.category = PM_File_Category.objects.get(pk=sId)
                    except PM_File_Category.DoesNotExist:
                        pass

                fileNow.file.name = os.path.join(ret_json['path'])
                fileNow.save()

                if version_of:
                    try:
                        fileOld = PM_Files.objects.get(pk=int(version_of))
                        fileOld.addNewVersion(fileNow)
                    except PM_Files.DoesNotExist:
                        pass

                ret_json.update({
                    'id':
                    fileNow.id,
                    'name':
                    fileNow.name,
                    'src':
                    fileNow.src,
                    'is_picture':
                    fileNow.isPicture,
                    'type':
                    fileNow.type,
                    'date_create':
                    fileNow.date_create,
                    'size':
                    fileNow.size,
                    'thumbnail':
                    protected(thumbnail(str(fileNow), '167x167'))
                    if fileNow.isPicture else ''
                })
                # although "application/json" is the correct content type, IE throws a fit
            return HttpResponse(json.dumps(ret_json, cls=DjangoJSONEncoder),
                                content_type='text/html; charset=utf-8')

        else:
            response = HttpResponseNotAllowed(['POST'])
            response.write("ERROR: Only POST allowed")
            return response
Exemple #15
0
    def _ajax_upload(self, request):
        if request.method == "POST":
            # determine which model and field this upload relates to
            try:
                model = request.POST['model']
                field = request.POST['field']
            except KeyError:
                return HttpResponseBadRequest("AJAX request not valid")
            else:
                # is the field one of the fields allowed?
                if field not in ('logo', 'square_logo', 'thumbnail'):
                    return HttpResponseBadRequest("AJAX request not valid")

            if request.is_ajax():
                # /!\ try this with Chrome / this is HTML5
                # the file is stored raw in the request
                is_raw = True
                upload = request
                try:
                    filename = request.POST['file']
                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, observe
                    # 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]
                    filename = upload.name
                else:
                    raise Http404("Bad Upload")

            # we have a filename, now determine where to put it
            # first, we need to figure out what model this refers to
            #logger.debug(model + '/' + field)
            try:
                _model = getattr(models, model)
                upload_to = _model._meta.get_field(field).upload_to
            except Exception as e:
                logger.error(e)
                return HttpResponseBadRequest("Bad Request")

            # do we need to resize the image?
            width = request.POST['width'] if request.POST.has_key(
                'width') else None
            height = request.POST['height'] if request.POST.has_key(
                'height') else None
            if width and height:
                self.storage.set_size(width, height)

            # save the file
            self.storage.setup(filename, upload_to)
            success = self.storage.upload(upload, is_raw)
            ret_json = {'success': success, 'filename': self.storage.filename}
            return HttpResponse(json.dumps(ret_json, cls=DjangoJSONEncoder),
                                content_type='application/json; charset=utf-8')
        else:
            response = HttpResponseNotAllowed(['POST'])
            response.write("Only POST allowed")
            return response
Exemple #16
0
    def _ajax_upload(self, request):
        if request.method == "POST":
            # determine which model and field this upload relates to
            try:
                model = request.POST['model']
                self.model = model
                field = request.POST['field']
            except KeyError:
                return HttpResponseBadRequest("AJAX request not valid")
            else:
                # is the field one of the fields allowed?
                if field not in ('picture',):
                    return HttpResponseBadRequest("AJAX request not valid")

            if request.is_ajax():
                # /!\ try this with Chrome / this is HTML5
                # the file is stored raw in the request
                is_raw = True
                upload = request
                try:
                    filename = request.POST['file']
                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, observe
                    # 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]
                    filename = upload.name
                else:
                    raise Http404("Bad Upload")

            # we have a filename, now determine where to put it
            # first, we need to figure out what model this refers to
            #logger.debug(model + '/' + field)
            try:
                _model = getattr(models, model)
                upload_to = _model._meta.get_field(field).upload_to
            except Exception as e:
                logger.error(e)
                return HttpResponseBadRequest("Bad Request")

            # do we need to resize the image?
            width = request.POST['width'] if request.POST.has_key('width') else None
            height = request.POST['height'] if request.POST.has_key('height') else None
            if width and height:
                self.storage.set_size(width, height)

            # save the file
            self.storage.setup(filename, upload_to)
            success = self.storage.upload(upload, is_raw)
            ret_json = {'success': success, 'filename': self.storage.filename}
            return HttpResponse(json.dumps(ret_json, cls=DjangoJSONEncoder), content_type=self.content_type)
        else:
            response = HttpResponseNotAllowed(['POST'])
            response.write("Only POST allowed")
            return response