Exemple #1
0
class ViewTestCase(TestCase):
    def setUp(self):
        self.image = Image(image=SimpleUploadedFile(name='x.jpg',
                                                    content='x',
                                                    content_type='image/jpeg'),
                           title='Example')
        self.image.save()
        self.params = {'app': 'main', 'model': 'image', 'pk': self.image.pk}

    def get_page(self, url):
        """ Ensures given url returns HTTP 200. """
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        return response

    def test_get_widget_iframe(self):
        """ User requests an iframe with the widget and gets an expected result """
        self.get_page(reverse('embed9:widget', kwargs=self.params))

    def test_get_widget_loader(self):
        """ User requests a JavaScript loader of the widget and gets an expected result """
        self.get_page(reverse('embed9:loader', kwargs=self.params))

    def test_get_widget_preview(self):
        """ User requests a widget preview and gets an expected result """
        self.get_page(reverse('embed9:preview', kwargs=self.params))
Exemple #2
0
 def form_valid(self, form):
     obj = Image()
     obj.user = self.request.user
     ext = self.request.FILES['image'].name
     obj.title = form.cleaned_data['title']
     s3 = boto3.resource('s3',
                         use_ssl=False,
                         endpoint_url='http://minio:9000')
     imguuid = uuid.uuid4()
     imgurl = f'{obj.user.id}-{imguuid}.{ext}'
     s3.Object('image', imgurl).put(Body=self.request.FILES['image'])
     obj.imageurl = imgurl
     obj.save()
     thumbnail.thumbnailify.delay(obj.id, imgurl, (200, 200))
     return HttpResponseRedirect(obj.get_absolute_url())
Exemple #3
0
def update_images(request):
    """
    Rereads the images from
    :param request:
    :return:
    """
    Image.objects.all().delete()

    files = os.listdir('images')
    files = [f for f in files if f[-3:] == 'png']
    for f in files:
        image = Image()
        image.filename = 'images/%s' % f
        image.save()

    return HttpResponse("Update images (Count: %d)" % len(files))
Exemple #4
0
def update_images(request):
    """
    Rereads the images from
    :param request:
    :return:
    """
    Image.objects.all().delete()

    files = os.listdir('images')
    files = [f for f in files if f[-3:] == 'png']
    for f in files:
        image = Image()
        image.filename = 'images/%s' % f
        image.save()

    return HttpResponse("Update images (Count: %d)" % len(files))
Exemple #5
0
def image(request, id=None):
    if id == None and request.method == "POST":
        data = simplejson.loads(request.raw_post_data)
        i = Image()
        i.from_json(data)
        i.save()
        return json_response(request, i)
    elif id != None:
        i = Image.objects.get(pk=id)
        if request.method == "POST":
            data = simplejson.loads(request.raw_post_data)
            i.from_json(data)
            i.save()
        return json_response(request, i)
    else:
        images = Image.objects.all()
        if 'archive' in request.GET and request.GET['archive'].lower() in (
                "true", "t", "1"):
            images = images.filter(archive=True)
        else:
            images = images.filter(archive=False)
        limited_images = images
        if 'bbox' in request.GET:
            limited_images = []
            left, bottom, right, top = map(float,
                                           request.GET['bbox'].split(","))
            for image in images:
                ileft, ibottom, iright, itop = map(float,
                                                   image.bbox.split(","))
                inbottom = (((ibottom >= bottom) and (ibottom <= top))
                            or ((bottom >= ibottom) and (bottom <= itop)))
                intop = (((itop >= bottom) and (itop <= top))
                         or ((top > ibottom) and (top < itop)))
                inleft = (((ileft >= left) and (ileft <= right))
                          or ((left >= ileft) and (left <= iright)))
                inright = (((iright >= left) and (iright <= right))
                           or ((right >= iright) and (right <= iright)))
                intersects = ((inbottom or intop) and (inleft or inright))
                if intersects:
                    limited_images.append(image)
        data = {'images': [i.to_json() for i in limited_images]}
        return json_response(request, data)
Exemple #6
0
def upload2(request):
    """Get uploaded file from form."""
    uploaded = request.read
    fileSize = int(uploaded.im_self.META["CONTENT_LENGTH"])
    fileName = uploaded.im_self.META["HTTP_X_FILE_NAME"]
    fileContent = uploaded(fileSize)

    """Write image to disk."""
    fn, ext = os.path.splitext(fileName)
    name = (
        fn
        + timezone.now().strftime("%Y_%m_%d_%H_%M_%S_%f")
        + base64.urlsafe_b64encode(os.urandom(settings.SALT_LENGHT))
        + ext
    )
    fileHandler = open(settings.MEDIA_ROOT + "images/" + name, "wb")
    fileHandler.write(fileContent)
    fileHandler.close()

    """Create md5hash digest for image."""
    base64string = base64.b64encode(fileContent)
    mdfive = md5.new(base64string).hexdigest()

    """Write image data to db."""
    latitude = request.GET.get("lat")
    longitude = request.GET.get("lon")
    tags = request.GET.get("tags").split(" ")

    image = Image(title=name, md5hash=mdfive, pub_date=timezone.now(), lat=latitude, lon=longitude)
    image.save()

    for tagtext in tags:
        if Tag.objects.filter(name=tagtext).exists():
            t = Tag.objects.get(name=tagtext)
        else:
            t = Tag(name=tagtext)
            t.save()
        image.tags.add(t)
        image.save()

    return HttpResponse('{"success": true}')
Exemple #7
0
    def process_item(self, item, spider):
        # pass
        # self.items.append(item['url'])
        # with open('file.txt', 'a+') as f:
        #     f.write("%s\n" % item)

        carItem = item["carItem"]
        car = Car()
        print("=================" + carItem["url"])
        car.url = carItem["url"]  # get URL
        car.title = carItem["title"]  # get title
        car.price = carItem["price"]  # get price
        car.location = carItem["location"]  # get location
        car.model = carItem["model"]  # get model year
        car.mileage = carItem["mileage"]  # get mileage
        car.fuel = carItem["fuel"]  # get fuel type
        car.engine = carItem["engine"]  # get engine
        car.transmission = carItem["transmission"]  # get transmission
        car.save()

        imageItem = item["imageItem"]["url"]
        if (len(imageItem) > 1):
            for imageUrl in imageItem.split(", "):
                image = Image()
                image.url = imageUrl
                image.car_id = car
                image.save()
        else:
            image = Image()
            image.url = imageItem
            image.car_id = car
            image.save()

        keywordCar = KeywordCar()
        keywordCar.keyword_id = self.keyword
        keywordCar.car_id = car
        keywordCar.save()
        # with io.open("items.txt", "a", encoding="utf-8") as f:
        #     f.write(str(item))
        return item
Exemple #8
0
def image(request, id=None):
    if id == None and request.method == "POST":
        data = simplejson.loads(request.raw_post_data)
        i = Image()
        i.from_json(data)
        i.save()
        return json_response(request, i)
    elif id != None:
        i = Image.objects.get(pk=id)
        if request.method == "POST":
            data = simplejson.loads(request.raw_post_data)
            i.from_json(data)
            i.save()
        return json_response(request, i)
    else:
        images = Image.objects.all()
        if 'archive' in request.GET and request.GET['archive'].lower() in ("true", "t", "1"):
            images = images.filter(archive=True)
        else:
            images = images.filter(archive=False)
        limited_images = images
        if 'bbox' in request.GET:
            limited_images = []
            left, bottom, right, top = map(float, request.GET['bbox'].split(","))
            for image in images:
                ileft, ibottom, iright, itop = map(float, image.bbox.split(","))
                inbottom = (((ibottom >= bottom) and (ibottom <= top)) or ((bottom >= ibottom) and (bottom <= itop)))
                intop = (((itop >= bottom) and (itop <= top)) or ((top > ibottom) and (top < itop)))
                inleft = (((ileft >= left) and (ileft <= right)) or ((left >= ileft) and (left <= iright)))
                inright = (((iright >= left) and (iright <= right)) or ((right >= iright) and (right <= iright)))
                intersects = ((inbottom or intop) and (inleft or inright))
                if intersects: 
                    limited_images.append(image)
        data = {'images': [
            i.to_json() for i in limited_images
            ]
        }   
        return json_response(request, data)
Exemple #9
0
    def create(self, validated_data):
        # Do processing

        # user requesting
        
        # user requesting

        image = validated_data['image']
        del validated_data['image']
        ext = validated_data['extension']
        # TODO: have a shared s3 obj instead of instantiating
        s3 = boto3.resource('s3', use_ssl=False, endpoint_url='http://minio:9000/')
        # TODO: check for collisions
        imguuid = uuid.uuid4()
        imgurl = f'{validated_data["user"].id}-{imguuid}.{ext}'
        s3.Object('image', imgurl).put(Body=image.file)
        validated_data['imageurl'] = imgurl
        obj = Image(**validated_data)
        obj.save()

        # Send task
        thumbnail.thumbnailify.delay(obj.id, imgurl, (200, 200))
        return obj
Exemple #10
0
def upload_image(request):
    instance = Image(file=request.FILES['fileimg'])
    instance.save()
    return HttpResponse(str(instance.pk))
Exemple #11
0
def item(request):
    """
    * get
    itn:item_num每次取得贴子条数
    st:start_pos:开始条数
    cat:catalog :分类
    tag:拼音缩写 JY ZH PC XK XR TC todo 管理员自定义
    # todo :缓存
    #todo 用户id查询
    #todo 用户id
    ps :删除在post的基础上op=DELETE
    *post
    """
    res = ""
    op = request.POST.get("op", None)
    if request.method == "GET":
        item_num = request.GET.get('itn', 10)
        start_pos = request.GET.get("st", None)
        catalog = request.GET.get("tag", "all")  # TODO
        page = request.GET.get("pg", 1)
        # 上拉刷新
        if start_pos is None:
            select_obj = Item.objects.all()
            start_pos = Item.objects.order_by('-pk').first().id
            # 下拉刷新,前端自动返回启刷的id
        else:
            # 只搜索id值小于起始点的
            select_obj = Item.objects.filter(pk__lte=start_pos)
        # 图片请求令启一个api,减轻服务器压力
        select_obj = select_obj.order_by('-pk').values()
        paginator = Paginator(select_obj, item_num)
        try:
            content = paginator.page(page)
        except PageNotAnInteger as e:
            content = paginator.page(1)
            print(e)  # todo 改log
        except EmptyPage as e:  # 是invalid的子类要放在前面 #todo 前端要判断最后一页到了没,到了就不能在页面加载最后一页了
            content = paginator.page(paginator.num_pages)
            print(e)
        except InvalidPage as e:
            content = paginator.page(1)
            print(e)  # todo 改log

        # for per_item in content:
        #     if()
        # content=serializers.serialize("json", content, ensure_ascii=False)

        content = list(content)
        data = {
            'mag': 'ok',
            'status': 200,
            'per_page': int(paginator.per_page),
            'num_page': int(paginator.num_pages),
            'start_pos': start_pos,
            "page_now": page,
            'content': content
        }
        return JsonResponse(data)
    # end if
    ###########
    # 发帖
    elif request.method == "POST" and op is None:
        i_title = request.POST.get('ttl', False)
        i_content = request.POST.get('cnt', False)  # 内容
        i_tag = request.POST.get('tag', False)  # 标签
        i_p_id = request.POST.get('p_id', False)  # 发帖人id  #todo 身份验证
        i_id = request.POST.get('i_id', False)

        if i_title and i_tag and i_content and i_p_id:
            dict_to_add = {
                'i_title': i_title,
                'i_content': i_content,
                'i_tag': i_tag,
                'i_p_id': i_p_id
            }
            try:
                if not i_id:
                    it = Item(**dict_to_add)
                    it.save()
                    msg = 'add_success'
                else:
                    it = Item.objects.filter(pk=i_id)
                    it.update(**dict_to_add)  # 创建并写入数据库
                    msg = 'update_success'
                    # 先储存否则外码设置有问题
                    # todo 图片修改?
                if request.FILES:
                    image_list = request.FILES.getlist("img")
                    for image in image_list:
                        img = Image(file=image, item=it)
                        img.save()
                return JsonResponse({"msg": msg, 'status': 200})
            except Exception as e:
                res = str(e)
        else:
            res = "missing argument"
    elif request.method == "POST" and op == "DELETE":
        i_p_id = request.POST.get('p_id', False)  # 发帖人id  #todo 身份验证
        i_id = request.POST.get('i_id', False)  # todo 无法访问
        if not Item.objects.filter(pk=i_id).exists():
            res = "not found"
        else:
            the_item = Item.objects.filter(pk=i_id).first()
            print(the_item)
            print(i_p_id)
            print(i_id)
            print(the_item.i_p_id)

            if not i_p_id or the_item.i_p_id != i_p_id:
                res = "no access to delete"
            else:
                the_item.delete()
                return JsonResponse({"msg": 'delete_success', 'status': 200})

    return JsonResponse({"msg": 'illegal operation::' + res, "status": 400})