Esempio n. 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))
Esempio n. 2
0
 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}
Esempio n. 3
0
def image(request, id=None):
    @logged_in_or_basicauth()
    def handle_update(request, image):
        data = simplejson.loads(request.raw_post_data)
        image.from_json(data, request.user)
        image.save()
        return json_response(request, image)

    if id == None and request.method == "POST":
        i = Image()
        return handle_update(request, i)
    elif id != None:
        i = Image.objects.get(pk=id)
        if request.method == "DELETE":
            i.delete()
            return json_response(request, "")
        elif request.method == "POST":
            return handle_update(request, i)
        return json_response(request, i)
    else:
        images = Image.objects.all().select_related()
        output = request.GET.get('output', 'simple')
        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)
        if 'layer' in request.GET:
            images = images.filter(layers__id=request.GET['layer'])
        if 'bbox' in request.GET:
            left, bottom, right, top = map(float,
                                           request.GET['bbox'].split(","))
            box = Polygon.from_bbox([left, bottom, right, top])
            images = images.filter(bbox__intersects=box)
        limit = min(int(request.GET.get("limit", 1000)), 10000)
        start = int(request.GET.get("start", 0))
        end = start + limit
        images = images.order_by("-id")

        # Instantiating full image objects for thousands of images is slow;
        # instead, just use .values and make our own dict here. Adding more
        # properties here should be done with consideration.
        if output == 'simple':
            data = {
                'images': [
                    dict(x) for x in images[start:end].values(
                        "id", "width", "height", "url", "bbox")
                ]
            }
            for i in data['images']:
                i['bbox'] = list(i['bbox'].extent)

        else:
            data = {
                'images':
                [i.to_json(output=output) for i in images[start:end]]
            }
        return json_response(request, data)
Esempio n. 4
0
File: views.py Progetto: aaronr/oam
def image(request, id=None):
    @logged_in_or_basicauth()
    def handle_update(request, image):
        data = simplejson.loads(request.raw_post_data)
        image.from_json(data, request.user)
        image.save()
        return json_response(request, image)
        
    if id == None and request.method == "POST":
        i = Image()
        return handle_update(request,i)
    elif id != None:
        i = Image.objects.get(pk=id)
        if request.method == "DELETE":
            i.delete()
            return json_response(request, "")
        elif request.method == "POST":
            return handle_update(request, i)
        return json_response(request, i)
    else:
        images = Image.objects.all().select_related()
        output = request.GET.get('output', 'simple')
        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)
        if 'layer' in request.GET:
            images = images.filter(layers__id=request.GET['layer'])
        if 'bbox' in request.GET:
            left, bottom, right, top = map(float, request.GET['bbox'].split(","))
            box = Polygon.from_bbox([left, bottom, right, top])
            images = images.filter(bbox__intersects=box)
        limit = min(int(request.GET.get("limit", 1000)), 10000)
        start = int(request.GET.get("start", 0))    
        end = start + limit
        images = images.order_by("-id") 

        # Instantiating full image objects for thousands of images is slow;
        # instead, just use .values and make our own dict here. Adding more 
        # properties here should be done with consideration.
        if output == 'simple':
           data = {'images': 
            [dict(x) for x in images[start:end].values("id", "width", "height", "url", "bbox")]
           } 
           for i in data['images']:
            i['bbox'] = list(i['bbox'].extent)
        
        else:
            data = {'images': [
                i.to_json(output=output) for i in images[start:end]
                ]
            }   
        return json_response(request, data)
Esempio n. 5
0
def get_image(request):
    id = request.GET.get('id', None)
    if id is None:
        # Return all images relevant images
        images = Image.get_relevant_images()

        # Transfer images to json
        images_data = []
        for image in images:
            im_dic = {
                'path': '/image?id=%d' % image.id
            }
            images_data.append(im_dic)
        return JsonResponse({'images': images_data})
    else:
        # Return the image
        thumbnail = request.GET.get('thumbnail', '0')
        image = Image.objects.get(pk=id)
        if thumbnail == '1':
            path = '/tmp/im.png'
            resize_and_crop(image.filename, path, (200, 200))
            with open(path, 'rb') as f:
                return HttpResponse(f.read(), content_type="png")
        else:
            with open(image.filename, 'rb') as f:
                return HttpResponse(f.read(), content_type="png")
Esempio n. 6
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))
Esempio n. 7
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))
Esempio n. 8
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}')
Esempio n. 9
0
def save_picture(form_picture):
    random_hex = secrets.token_hex(8)
    _, f_ext = os.path.splitext(form_picture.filename)
    picture_fn = random_hex + f_ext
    picture_path = os.path.join(app.root_path, 'static/profile_pics',
                                picture_fn)
    output_size = (125, 125)
    i = Image.open(form_picture)
    i.thumbnail(output_size)
    i.save(picture_path)

    return picture_fn
Esempio n. 10
0
File: views.py Progetto: Razz12/jnp
def searchView(request):
	data = json.loads(request.raw_post_data)
	#print("OKI")
	ret = {}
	ret["objects"] = Image.full_text(data['search'])
	#print(ret)
	#print("HEHE")
	
	kupa = json.dumps(ret, skipkeys=True)
	#print("WYSZLO")
	#print(kupa)
	return HttpResponse(kupa, content_type="application/json")
Esempio n. 11
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())
Esempio n. 12
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)
Esempio n. 13
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
Esempio n. 14
0
def get_image(request):
    id = request.GET.get('id', None)
    if id is None:
        # Return all images relevant images
        images = Image.get_relevant_images()

        # Transfer images to json
        images_data = []
        for image in images:
            im_dic = {'path': '/image?id=%d' % image.id}
            images_data.append(im_dic)
        return JsonResponse({'images': images_data})
    else:
        # Return the image
        thumbnail = request.GET.get('thumbnail', '0')
        image = Image.objects.get(pk=id)
        if thumbnail == '1':
            path = '/tmp/im.png'
            resize_and_crop(image.filename, path, (200, 200))
            with open(path, 'rb') as f:
                return HttpResponse(f.read(), content_type="png")
        else:
            with open(image.filename, 'rb') as f:
                return HttpResponse(f.read(), content_type="png")
Esempio n. 15
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
Esempio n. 16
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)
Esempio n. 17
0
def main_app(request):
    context = {'images': Image.get_relevant_images()}
    return TemplateResponse(request, "main/index.html", context)
Esempio n. 18
0
def upload_image(request):
    instance = Image(file=request.FILES['fileimg'])
    instance.save()
    return HttpResponse(str(instance.pk))
Esempio n. 19
0
def main_app(request):
    context = {
        'images': Image.get_relevant_images()
    }
    return TemplateResponse(request, "main/index.html", context)
Esempio n. 20
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})