Exemple #1
0
def get_property(request, property_name):
    if request.method == 'PUT':
        model = simplejson.loads(request.data)
        pr_obj = ProductProperty.get_by_id(property_name)
        if not pr_obj:
            return render_json_response({
                'api_success': False,
                'api_msg': "Property %s not found." % property_name
            })
        pr_obj.title = model['title']
        pr_obj.units = model['units']
        pr_obj.put()
        return render_json_response({
            'api_success': True,
            'api_msg': 'Property %s updated' % model['id']
        })

    if request.method == 'DELETE':
        pr_obj = ProductProperty.get_by_id(property_name)
        if not pr_obj:
            return render_json_response({
                'api_success': False,
                'api_msg': "Property %s not found." % property_name
            })
        pr_obj.key.delete()
        return render_json_response({
            'api_success': True,
            'api_msg': "Property %s deleted" % property_name
        })
Exemple #2
0
def get_api_key(request, id):
    if request.method == 'GET':
        key = ApiKey.get_by_id(id)
        return render_json_response(key.to_json())

    if request.method == 'PUT':
        model = simplejson.loads(request.data)
        key = ApiKey.get_by_id(id)
        if not key:
            data = {'api_success': False, 'api_msg': 'ApiKey %s not found' % id}
            return render_json_response(data)
        key.title = model['email']
        key.is_writer = model['is_writer']
        key.put()
        data = {'api_success': True, 'api_msg': 'ApiKey %s updated' % id}
        return render_json_response(data)

    if request.method == 'DELETE':
        key = ApiKey.get_by_id(id)
        if not key:
            data = {'api_success': False, 'api_msg': 'ApiKey %s not found' % id}
            return render_json_response(data)
        key.key.delete()
        data = {'api_success': True, 'api_msg': 'ApiKey %s deleted' % id}
        return render_json_response(data)
Exemple #3
0
def create(data, is_unique_title=False):
    try:
        title = data.get("title", "")
        if not title:
            res = {"api_success": False, "api_msg": '"title" field is required', "api_function": create.__name__}
            logging.warning(res)
            return render_json_response(res)
        if is_unique_title and is_category_exist(title):
            res = {"api_success": False, "api_msg": 'Field "title" must be unique', "api_function": create.__name__}
            logging.warning(res)
            return render_json_response(res)

        available = data.get("available", False)

        parent = data.get("parent", None)
        if parent:
            parent_id = parent.get("id", None)
            if parent_id:
                parent = Category.get_by_id(parent_id)

        if parent:
            category = Category(title=title, parent_category=parent.key, available=available)
        else:
            category = Category(title=title, available=available)
        category.put()
        res = {"api_success": True, "api_msg": "Category created", "category": category.to_json()}
        logging.info(res)
        return render_json_response(res)
    except Exception, e:
        res = {"api_success": False, "api_msg": str(e), "api_function": create.__name__}
        logging.error(res)
        return render_json_response(res)
Exemple #4
0
def create(data, is_unique_title=False):
    try:
        title = data.get('title', '')
        if not title:
            res = {'api_success':False,
                 'api_msg':'"title" field is required',
                 'api_function':create.__name__}
            logging.warning(res)
            return render_json_response(res)
        if is_unique_title and is_brand_exist(title):
            res = {'api_success':False,
                 'api_msg':'Field "title" must be unique',
                 'api_function':create.__name__}
            logging.warning(res)
            return render_json_response(res)

        available = data.get('available', False)
        brand = Brand.create_new_entity(title=title,
                available=available)

        res = {'api_success': True,
                    'api_msg': 'Brand created',
                    'brand': brand.to_json()}
        logging.info(res)
        return render_json_response(res)
    except Exception,e:
        res = {'api_success': False,
               'api_msg': str(e),
               'api_function':create.__name__}
        logging.error(res)
        return render_json_response(res)
Exemple #5
0
def get_cart_item(request, item_id):
    cart = request.session.get('cart', {})

    if request.method == 'GET':
        count = cart.get(item_id, {}).get('count', 0)
        return render_json_response(cart_item_to_json(item_id, count))

    if request.method == 'PUT':
        model = simplejson.loads(request.data)
        count = model.get('count', 0)
        if not len(cart):
            cart[item_id] = {'count': count}
            request.session['cart'] = cart
            return render_json_response(cart_item_to_json(item_id, count))
        else:
            product = cart.get(item_id, {})
            product['count'] = count
            cart[item_id] = product
            request.session['cart'] = cart
            return render_json_response(cart_item_to_json(item_id, count))

    if request.method == 'DELETE':
        item = cart.get(item_id, {})
        if item:
            del cart[item_id]
        request.session['cart'] = cart
        return render_json_response({'api_success': True,
            'api_msg': 'Item %s removed from cart' % item_id})
Exemple #6
0
def admins(request):
    users = User.all().filter('is_admin =', True)
    if users.count():
        return render_json_response([user.to_json() for user in users])
    return render_json_response({
        'api_success': False,
        'api_msg': 'Admins not found.'})
Exemple #7
0
def send_to_manager(request, order_id):
    order = Order.get_by_id(order_id)
    if not order:
        return render_to_response({
            'api':{
                'success': False,
                'msg': 'Order %s not found' % order_id
            }
        }, status=404)
    managers = Manager.query()
    if not managers.count():
        return render_json_response({
            'api':{
                'success': False,
                'msg': 'Managers not found.'
            }
        }, status=404)
    subject = render_to_string('order/msg/subject.html', {'order':order})
    msg = render_to_string('order/msg/body.html', {'order': order})

    email = mail.EmailMessage()
    email.subject = subject
    email.html = msg
    email.sender = settings.DEFAULT_MAIL_FROM
    for manager in managers:
       if manager.communication.email:
           email.to = manager.communication.email
           email.send()
    return render_json_response({
        'api':{
            'success': True,
            'msg': 'Order notifications were sent'
        }
    })
Exemple #8
0
def create(data):
    product_id= data.get('product_id', '')
    product = Product.get_by_id(product_id)
    if not product:
        res = { 'api_success':False,
                'api_msg':'Product %s not found' % product_id,
                'api_function': create.__name__}
        logging.warning(res)
        return render_json_response(res)
    image64 = data.get('image_data', '')
    if not image64:
        res = {'api_success': False, 'api_msg': 'Image data not found'}
        logging.warning(res)
        return render_json_response(res)
    image64 = base64.decodestring(image64)
    im = Image.create_from_data(image64, title=product.title)
    if im.get_cached_url():
        if product.master_image is None:
            im.is_master = True
        product.images.append(im)
        product.put()
        res = {'api_success': True, 'api_msg': 'Image uploaded'}
        logging.info(res)
    else:
        res = {'api_success':False,
                 'api_msg':'Invalid image'}
        logging.warning(res)
    return render_json_response(res)
Exemple #9
0
def category_json(request, category_id):
    category = Category.get_by_id(category_id)
    if not category:
        return render_json_response({
            'api':{
                'success': False,
                'msg': 'Category %s not found' % category_id
            }
        }, status=400)

    if request.method == 'GET':
        return get_category(category)

    if request.method == 'DELETE':
        return delete_category(request, category)

    if request.method == 'PUT':
        return put_category(request, category)

    return render_json_response({
        'api':{
            'success':False,
            'msg': 'Request method %s not supported' % request.method
        }
    }, status=400)
Exemple #10
0
def r_info_delete_image(request, uid):
    if request.method == 'POST':
        img = RetailInfoImage.get_by_id(uid)
        if img:
            img.key.delete()
            return render_json_response({'api':{'success':True}})
    return render_json_response({'api':{'success':False}})
Exemple #11
0
def add_image(request, name):
    product_ = Product.get_by_id(name)
    if not product_:
        return render_json_response({'api_success':False,
                                     'api_msg':'Product %s not found' % name},
                                    status=400)
    if request.method == 'POST':
        try:
            upload_files = get_uploads(request, 'file')
            blob_info = upload_files[0]
            im = Image.create(blob_info.key(), title=product_.title)
            if not len(product_.images):
                im.is_master = True
            if im.get_cached_url():
                product_.images.append(im)
                product_.put()
                api_upload_img_url = blobstore.create_upload_url(
                                    url_for('shop/admin/product/upload_img',
                                        name=product_.key.id()))
                return render_json_response(
                    {'api_success':True,
                     'api_msg':'Image uploaded',
                     'api_upload_img_url':api_upload_img_url,
                     'img': im.to_json()})
            else:
                return render_json_response(
                            {'api_success':False,
                             'api_msg':'Invalid image'})
        except Exception, e:
            return render_json_response(
                    {'api_success':False,
                     'api_msg':str(e)}, status=400)
Exemple #12
0
def product_json(request, product_id):
    product = Product.get_by_id(product_id)
    if not product:
        return render_json_response({
            'api':{
                'success': False,
                'msg': 'Product %s not found' % product_id
            }
        }, status=400)

    if request.method == 'GET':
        return get_product(product)

    if request.method == 'DELETE':
        return delete_product(request, product)

    if request.method == 'PUT':
        return put_product(request, product)

    return render_json_response({
        'api':{
            'success':False,
            'msg': 'Request method %s not supported' % request.method
        }
    }, status=400)
Exemple #13
0
def create_category(request):
    if request.method == 'POST':
        try:
            model = simplejson.loads(request.data)
            title = model.get('title', '')
            available = model.get('available', False)
            only_end_products = model.get('only_end_products')
            parent_category = model.get('parent_category', None)
            if parent_category:
                parent_id = parent_category.get('id', None)
                if parent_id:
                    parent_category = Category.get_by_id(int(parent_id))
                    if parent_category:
                        parent_category = parent_category.key
            category = Category(
                title=title,
                available=available,
                parent_category=parent_category,
                only_end_products=only_end_products)
            category.put()
            res = {'api_success': True,
                   'api_msg': 'Category "%s" created' % category.key.id()}
            res.update(category.to_json())
            return render_json_response(res)
        except Exception, e:
            res = {'api_success': False,
                   'api_msg': str(e)}
            return render_json_response(res)
Exemple #14
0
def get_manager(request, uid):
    manager = Manager.get_by_id(uid)
    if not manager:
        data = {'api_success': False,
                'api_msg': 'Manager %s not found' % uid}
        return render_json_response(data, status=404)

    if request.method == 'GET':
        return render_json_response(manager.to_json())

    if request.method == 'DELETE':
        manager.key.delete()
        data = {'api_success': True, 'api_msg': 'Manager %s deleted' % uid}
        return render_json_response(data)

    if request.method == 'PUT':
        model = simplejson.loads(request.data)
        manager.communication = Communication.from_json(model.get('communication', {}))
        manager.telephone = Telephone.from_json(model.get('telephone', {}))
        manager.address = Address.from_json(model.get('address', {}))
        manager.name = model.get('name', '')
        manager.last_name = model.get('last_name', '')
        manager.is_display = model.get('is_display', False)
        manager.put()
        data = {'api_success': True, 'api_msg': 'Manager %s updated' % uid}
        data.update(manager.to_json())
        return render_json_response(data)
Exemple #15
0
def tasks(request):
    if request.method == "POST":
        task = Task.create_task(request.form)
        return render_json_response(task.to_dict())

    tasks = Task.read_tasks(request.user.key(),
                            params=request.args)
    data = [task.to_dict() for task in tasks]
    return render_json_response(data)
Exemple #16
0
 def inner(request, *args, **kwargs):
     if request.user.is_anonymous():
         try:
             api_key = request.args['key']
         except BadRequest:
             return render_json_response({'message': 'bad request', 'status': 'error'}, status=400)
         if validate_api_key(api_key) is False:
             return render_json_response({'message': 'invalid key', 'status': 'error'}, status=403)
     return func(request, *args, **kwargs)
Exemple #17
0
def shorturl(request, path=None):
    if path is not None and URLSHORTEN_PATTERN.search(path) is False:
        return render_json_response({'message': 'bad request', 'status': 'error'}, status=400)
    user_created = str(request.user.key())
    if request.user.is_anonymous():
        api_key_entity = validate_api_key(request.args['key'])
        user_created = api_key_entity.user_created
    shorturls = URLShorten(method=request.method, user_created=user_created, values=request.values, path=path)
    shorturls.do()
    return render_json_response(shorturls.result, status=shorturls.code)
Exemple #18
0
def new_order(request):
    client_json = simplejson.loads(request.data)
    name = client_json.get('name', '')
    telephone = client_json.get('telephone', '')
    email = client_json.get('email', '')
    if not client_json \
    or not name \
    or not telephone:
        return render_json_response({
            'api_success': False,
            'api_msg': \
            u'Заказ не сформирован, т.к. не заполнена контактная информация.'},
            status=401)
    cart = request.session.get('cart', {})
    order_items = get_cart_items(cart)
    total_price = 0.0
    for item in order_items:
        total_price += item.get('price', 0.0) * item.get('count', 0)
        pass
    if not order_items or not total_price:
        return render_json_response({
        'api_success': False,
        'api_msg': u'Корзина пуста или при передаче данных произошла ошибка.\n\
Поробуйте еще раз. %s' % order_items}, status=409)

    client = Client(
        name=name,
        telephone=telephone,
        email=email,
        address=client_json.get('address'),
        is_delivery=client_json.get('delivery', False),
        ip=request.remote_addr)
    order = Order(client=client, total_price=total_price)
    for item in order_items:
        oi = OrderItem(
            item_id=item.get('id', ''),
            item_title=item.get('title', ''),
            item_url=item.get('url', ''),
            item_img_url=item.get('img_url', ''),
            item_price=item.get('price', 0.0),
            item_count=item.get('count', 0)
            )
        order.items.append(oi)
    order.put()
    def txn():
        taskqueue.add(url=url_for('order/send_to_manager',
                            order_id=str(order.key.id())),
                            transactional=True)
    db.run_in_transaction(txn)
    request.session['cart'] = {}
    return render_json_response({
        'api_success': True,
        'api_msg': u'Заказ успешно сформирован!\n\
В ближайшее время с вами свяжется наш менеджер и уточнит детали заказа.'
        })
Exemple #19
0
def get_image(request, id, uid):
    union = Union.get_by_id(id)
    if not union:
        return render_json_response({"api": {"success": False, "msg": "Union %s not found" % id}}, status=400)
    if request.method == "DELETE":
        for image in union.images:
            if image.uid == uid:
                image.pre_delete()
                union.images.remove(image)
                union.put()
                return render_json_response({"api": {"success": True}})
Exemple #20
0
def template_feed(request):
    memcache_key = 'template_feed'
    template_feed_dict = memcache.get(memcache_key)
    if template_feed_dict is not None:
        return render_json_response({'templates': template_feed_dict}, mimetype='application/json')
    results = EventTemplate.all().order('-updated_at').fetch(20)
    template_feed_dict = [
        {'template_name': r.template_name, 'title': r.title, 'id': r.key().id(), 'description': r.description} for r in
        results]
    memcache.set(memcache_key, template_feed_dict, 3600)
    return render_json_response({'templates': template_feed_dict}, mimetype='application/json')
Exemple #21
0
def get_category(request, category_id):
    if request.method == 'GET':
        try:
            category = Category.get_by_id(category_id)
            if not category:
                data = {'api_success': False,
                        'api_msg': 'Category %s not found' % category_id}
                return render_json_response(data)
            return render_json_response(category.to_json())
        except Exception, e:
            data = {'api_success': False,
                    'api_msg': str(e)}
            return render_json_response(data)
Exemple #22
0
def get_object(request_, class_):
    key_id = request_.values.get('id')
    if key_id is None:
        return render_json_response('Failed - ID not found', status=404)
    try:
        key_id = int(key_id)
    except ValueError:
        return render_json_response('Invalid ID: %s' % key_id, status=500)
    objs = class_.get_by_id(key_id)
    if not objs:
        return render_json_response(
            "Failed - object with ID %s not found" % key_id,
            status=404)
    return render_json_response(objs.to_json())
Exemple #23
0
 def test_render_json_response_simple(self):
   """Test for render_json_response"""
   for v in self.test_values:
     response = render_json_response(v)
     self.assertEqual(response.status_code, 200)
     v2 = json.loads(response.data)
     self.assertEqual(v, v2)
Exemple #24
0
def sync_add_image(request, uid):
    logging.info("Add image for gift with key: %s" % uid)
    mem_key = 'sync/add_image/%s' % uid
    img_url = memcache.get(mem_key)
    if img_url:
        memcache.delete(mem_key)
        img = urlfetch.fetch(img_url)
        if img.status_code == 200:
            thumb = img.content
            gift = Gift.get_by_id(uid)
            if gift:
                title = gift.name.replace('"', '"')
                thumb_img = ThumbImage()
                content_type = 'image/jpeg'
                thumb_img.add_new_thumb(blob_img=thumb, thumb_size=(700, 700,),
                                        title=title, content_type=content_type)
                thumb_img.add_new_thumb(blob_img=thumb, thumb_size=(400, 400, ),
                                        title=title, content_type=content_type)
                thumb_img.add_new_thumb(blob_img=thumb, thumb_size=(200, 200, ),
                                        title=title, content_type=content_type)
                thumb_img.add_new_thumb(blob_img=thumb, thumb_size=(100, 100, ),
                                        title=title, content_type=content_type)
                if not gift.thumbs.count():
                    thumb_img.main_gift = gift
                thumb_img.gift = gift
                thumb_img.put()
    return render_json_response({'api_msg': 'Ok', 'api_success': True})
Exemple #25
0
def create_brand(request):
    if request.method == 'POST':
        model = simplejson.loads(request.data)
        brand = Brand(
            title=model['title'])
        brand.put()
        return render_json_response(brand.to_json())
Exemple #26
0
 def test_render_json_response_simple(self):
     """Test for render_json_response"""
     for v in self.test_values:
         response = render_json_response(v)
         self.assertEqual(response.status_code, 200)
         v2 = json.loads(response.data)
         self.assertEqual(v, v2)
Exemple #27
0
def products_dates_json(request):
    date1 = request.values.get("from_date")
    date2 = request.values.get('to_date')
    if date1 is None:
        ApiException('Invalid request: parameter "from_date" not found.')
    date1 = datetime.strptime(date1, '%Y-%m-%d')
    if date2 is None:
        date2 = datetime.now()
    else:
        date2 = datetime.strptime(date2, '%Y-%m-%d')
    ApiException(date2)
    is_new = request.values.get('only_new')
    if is_new is None:
        products_q = Product.query(
            Product.timestamp_edit >= date1,
            Product.timestamp_edit <= date2).fetch(keys_only=True)
    else:
        products_q = Product.query(
            Product.timestamp_add >= date1,
            Product.timestamp_add <= date2).fetch(keys_only=True)
    res = {
        'success': True,
        'result': [key.id() for key in products_q]
    }
    return render_json_response(res)
Exemple #28
0
def task_calculate_point_daily(request):
	now = datetime.now()
	date = {"year": now.year, "month": now.month, "day": now.day, "date": "%04d%02d%02d" % (now.year, now.month, now.day)}

	thermography_points = ThermographyPoints.all().filter("day_calculate_status =", 0).filter("date =", date['date']).fetch(10)
	logging.info(thermography_points)
	
	for thermography_point in thermography_points:
		thermography = _get_thermography_ponit_daily(thermography_point.site, thermography_point.url, date)
		total_points = json.loads(thermography.data) if thermography.data else {}
		points = json.loads(thermography_point.data)
		for key in points.keys():
			if total_points.has_key(key):
				total_points[key] += points[key]
			else:
				total_points[key] = points[key]

		thermography.data = json.dumps(total_points)
		thermography.max_point = max(total_points.values())
		thermography.put()

		thermography_point.day_calculate_status = 1
		thermography_point.put()

	return render_json_response({'message':'Calculate point %s daily successful' % date['date']})
Exemple #29
0
def get_brand_image(request, brand_key, image_key):
    if request.method == 'DELETE':
        brand = Brand.get_by_id(brand_key)
        if brand:
            for image in brand.images:
                if image.uid == image_key:
                    image.pre_delete()
                    brand.images.remove(image)
                    brand.put()
                    data = {'api_success': True,
                            'api_msg': 'BrandImage %s deleted' % image_key}
                    return render_json_response(data)

        data = {'api_success': False,
                'api_msg': 'BrandImage %s not found' % image_key}
        return render_json_response(data)
Exemple #30
0
def get_products(request):
    products = memcache.get("json_products")
    if not products:
        products = Product.query().fetch()
        products = [product.to_json() for product in products]
        memcache.add("json_products", products, 600)
    return render_json_response(products)
Exemple #31
0
def get_value(request, property_key, value_key):

    if request.method == 'GET':
        try:
            value = ProductPropertyValue.get_by_id(value_key)
            if not value:
                data = {'success': False,
                        'msg': 'Value %s not found' % value_key}
                return render_json_response(data)
        except Exception, e:
            data = {'api_success': False,
                    'api_msg': str(e)}
            return render_json_response(data)
        data = {'api_success': True, 'api_msg': 'Value created'}
        data.update(value.to_json)
        return render_json_response(data)
Exemple #32
0
 def checking_right(*args, **kwargs):
     api_key = args[0].values.get('private_api_key', False)
     if not api_key:
         return render_json_response({
             'api_success': False,
             'api_msg': 'Invalid private API key',
             'api_function': func.__name__
         })
     customer = ApiKey.query(ApiKey.private_api_key == api_key).get()
     if not customer or not customer.is_writer:
         return render_json_response({
             'api_success': False,
             'api_msg': 'Oops, you do not have write permission',
             'api_function': func.__name__
         })
     return func(*args, **kwargs)
Exemple #33
0
def track(request):
	if request.method != "POST":
		return render_json_response({'error':'Invalid method'})
	
	data = json.loads(request.form['data'])
	if len(data['move_events']) == 0: 
		return render_json_response({'error':'Invalid arguments'})

	# referer check and site activate
	from admin.models import Sites
	sites = Sites.all().filter('activate_code =', data['activate_code']).fetch(10)
	if not sites: return render_json_response({'error':'Invalid activate code'})
	site = sites[0]
	if not data['url'].startswith(site.url.rstrip('/')): return render_json_response({'error':'Invalid url'})
	if not site.activated:
		site.activated = True
		site.put()
	
	t = Thermographies(data=request.form['data'], calculate_status=0, url=db.Link(data['url'].rstrip('/')), site=site)
	t.put()
	return render_json_response({'message':'Tracking successful'})
Exemple #34
0
def task_calculate_points(request):
	thermographies = Thermographies.all().filter("calculate_status =", 0).fetch(10)
	if not thermographies: return render_json_response({'message':'Calculate points unsuccessful'})

	for thermography in thermographies:
		data = json.loads(thermography.data)
		points = {}
		for event in data['move_events']:
			x = int(event['pageX'])
			y = int(event['pageY'])
			key = "%s:%s" % (x, y)
			if points.has_key(key):
				points[key] += 1
			else:
				points[key] = 1

		ts = int(str(data['move_events'][-1]['timeStamp'])[0:10])
		event_time = datetime.fromtimestamp(ts)
		ThermographyPoints(
			thermography = thermography,
            site = thermography.site,
            url = db.Link(thermography.url),
			data = json.dumps(points),
			year_calculate_status = 0,
			month_calculate_status = 0,
			day_calculate_status = 0,
			date = "%04d%02d%02d" % (event_time.year, event_time.month, event_time.day),
			year = event_time.year,
			month = event_time.month,
			day = event_time.day,
		).put()

		thermography.calculate_status = 1
		thermography.put()

	return render_json_response({'message':'Calculate points successful'})