コード例 #1
0
ファイル: account.py プロジェクト: dilimanlabs/Pitstop
    def post(self, *ar, **kw):
        accountId_id = ar[0]

        accountId_key = ndb.Key(models.AccountId, accountId_id)
        accountId_obj = accountId_key.get()

        if not accountId_obj:
            self.abort(404)

        accountBody_obj = None
        if accountId_obj.accountBody_key:
            accountBody_obj = accountId_obj.accountBody_key.get()

        if not accountBody_obj:
            self.abort(404)

        authToken = self.get_authToken(accountBody_obj.key)

        img_key = models.Image(title=self.request.POST['title'].encode('ascii', 'ignore'),
                               full_size_image=self.request.POST['image'].file.read(), parent=accountBody_obj.key).put()
        img_id = urlhash.int_to_base62(img_key.integer_id())

        self.response.headers.add_header('Access-Control-Allow-Origin', '*')
        self.response.headers.add_header('Location', '/accnt/' + urlhash.int_to_base62(accountBody_obj.key.integer_id()) + '/img/' + img_id)
        self.response.status = '201 Created'
コード例 #2
0
 def post(self):
     args = file_upload.parse_args()
     # token = request.headers['Authorization']
     # userid = oidc.user_getfield('sub', token)
     # canpr = pyquots.can_user_proceed(userid=userid, usagetype='PREDICTION', usagesize="1")
     # if canpr.proceed is not True:
     #     abort(402, "Not enough credits available")
     if args['file'].mimetype == 'image/jpeg' or args[
             'file'].mimetype == 'image/png' or args[
                 'file'].mimetype == 'application/octet-stream':
         token = request.headers['Authorization']
         token = token.split(" ")[1]
         userid = oidc.user_getfield('sub', token)
         file = request.files['file']
         control = args['control']
         exposed = args['exposed']
         exposedAt = args['exposedAt']
         age = args['age']
         generation = args['generation']
         mm = args['mm']
         pixels = args['pixels']
         time_got = int(round(time.time() * 1000))
         filename = file.filename
         file.save(image_path['IMAGE_PATH'] + filename)
         # filename = image_path['IMAGE_PATH'] + filename
         # im = Image.open("./" + file.filename)
         # pyquots.can_user_proceed(userid=userid, usagetype='SAVEIMAGE', usagesize="-1")
         users_bucket = userid + "-deepdaph"
         photoid = randomString(12)
         image = models.Image(userId=userid,
                              photo=users_bucket + "/" + filename,
                              imageId=photoid,
                              control=control,
                              exposed=exposed,
                              exposedAt=exposedAt,
                              age=age,
                              generation=generation,
                              mm=mm,
                              pixels=pixels,
                              time=time_got)
         mongoClient['image'].insert_one(image._asdict())
         try:
             minioClient.make_bucket(users_bucket)
         except BucketAlreadyOwnedByYou as err:
             minioClient.fput_object(users_bucket, filename,
                                     image_path['IMAGE_PATH'] + filename)
             os.remove(image_path['IMAGE_PATH'] + filename)
         except BucketAlreadyExists as err:
             minioClient.fput_object(users_bucket, filename,
                                     image_path['IMAGE_PATH'] + filename)
             os.remove(image_path['IMAGE_PATH'] + filename)
         resp = Response(json.dumps(image._asdict()))
         resp.headers["Access-Control-Expose-Headers"] = '*'
         return resp
     else:
         abort(404)
コード例 #3
0
    def post(self, *ar, **kw):
        business_id = ar[0]

        business_model = self.get_model(models.Business, business_id)

        image_key = models.Image(
            title=self.request.POST['title'].encode('ascii', 'ignore'),
            full_size_image=self.request.POST['image'].file.read(),
            parent=business_model.key).put()

        image_model_url = '/businesses/' + business_id + '/images/' + urlhash.int_to_base62(
            image_key.integer_id())
        image_model = image_key.get()
        image_model.url = image_model_url
        image_model.put()

        self.set_response('201 Created',
                          extra_headers=[['Location', image_model_url]])
コード例 #4
0
    def process(self):
        result = None
        category_key_name = ''
        try:
            department_key = str(self.request.get('department_key'))
            category_url = str(self.request.get('category_url'))

            response = urlfetch.fetch(url=category_url,
                                      method=self.urlfetch['method'],
                                      deadline=self.urlfetch['deadline'],
                                      headers=self.urlfetch['headers'])

            # Get available colours from Product
            colours = models.Product.properties()['colour'].choices

            if response.status_code == 200:
                result = response.content

                # Parse the response content into a MiniDom object
                minidom_document = html_parser.parse_html_document(result)

                # Set the Department
                department = models.Department.get_or_insert(
                    key_name=department_key, name=department_key.title())
                department_display_name = department.name

                # Get the Category Name form the Page H1 Header
                category_name = minidom_document.getElementsByTagName(
                    'h1')[0].childNodes[0].nodeValue
                try:
                    if category_name is not None:
                        category_key_name = category_name.lower().replace(
                            ' ', '')
                except Exception, e:
                    logging.error('Get Category')
                    logging.error(e)

                # Create the Category Model
                category = models.Category.get_or_insert(
                    key_name=category_key_name,
                    name=category_name,
                    department=department)

                # Collect all DIVs
                all_div_elements = minidom_document.getElementsByTagName('div')

                # For each DIV in the MiniDom object
                for div in all_div_elements:

                    # If the DIV id is productsList, we've found the product list container
                    if div.getAttribute('id') == 'productsList':
                        # Get it's child DIVs
                        product_list_divs = div.getElementsByTagName('div')
                        # For each of those
                        for div in product_list_divs:
                            # If the DIV includes a class value of 'productCont' then we expect it to be a product
                            if 'productCont' in div.getAttribute('class'):
                                sku = None
                                name = ''
                                price = None
                                product = div
                                colour = ''
                                _type = None
                                collection = None
                                url = None
                                # Get SKU code
                                try:
                                    sku = product.getAttribute('id')
                                    sku = sku.replace('id_', '')
                                except Exception, e:
                                    logging.error('Get SKU')
                                    logging.error(e)
                                    raise Exception(
                                        'No product SKU found for category_url : '
                                        + category_url)

                                # Get Collection and Name
                                try:
                                    for div in product.getElementsByTagName(
                                            'div'):
                                        if 'product_info' in div.getAttribute(
                                                'class'):
                                            spans = div.getElementsByTagName(
                                                'span')
                                            for span in spans:
                                                if 'product_collection' in span.getAttribute(
                                                        'class'):
                                                    collection = span.childNodes[
                                                        0].nodeValue
                                                else:
                                                    nodes = span.childNodes
                                                    for node in nodes:
                                                        name = name + node.nodeValue.strip(
                                                        ) + ' '

                                            name = name.strip()
                                            break
                                except Exception, e:
                                    logging.error(
                                        'Error getting Collection and Name')
                                    logging.error(e)
                                    raise Exception(
                                        'No Product Name found for category_url : '
                                        + category_url)

                                # Get Product Colour
                                try:
                                    for word in name.split(' '):
                                        if word in colours:
                                            colour = word
                                            break
                                except Exception, e:
                                    logging.error('Error Getting Colour')

                                # Get Product URL
                                try:
                                    anchors = product.getElementsByTagName('a')
                                    if len(anchors) > 0:
                                        for anchor in anchors:
                                            if 'product_image_link' in anchor.getAttribute(
                                                    'class'):
                                                url = anchor.getAttribute(
                                                    'href')
                                                break
                                except Exception, e:
                                    logging.error('Error Getting Product URL')

                                # Get Product Price
                                try:
                                    product_paragraphs = product.getElementsByTagName(
                                        'p')
                                    for paragraph in product_paragraphs:
                                        if 'product_price' in paragraph.getAttribute(
                                                'class'):
                                            spans = paragraph.getElementsByTagName(
                                                'span')
                                            for span in spans:
                                                span_class = span.getAttribute(
                                                    'class')

                                                if 'one_price' in span_class:
                                                    price = span.childNodes[
                                                        1].nodeValue
                                                    break
                                                elif 'now_price' in span_class:
                                                    for price_span in span.getElementsByTagName(
                                                            'span'):
                                                        if 'price_value' in price_span.getAttribute(
                                                                'class'):
                                                            price = price_span.childNodes[
                                                                1].nodeValue
                                                            break
                                    if price is not None:
                                        price = price.replace(',', '')
                                        price = float(price)

                                except Exception, e:
                                    logging.error('Get Price')
                                    logging.error(e)

                                # Create or Get the Product if it already exists
                                product = models.Product.get_or_insert(
                                    key_name=sku,
                                    name=name,
                                    price=price,
                                    colour=colour,
                                    type=_type,
                                    category=category,
                                    department=department_display_name,
                                    collection=collection,
                                    url=url)

                                # Now check for changes to Product attributes
                                change = False

                                # Create Images
                                try:
                                    for key, src in self.product_template[
                                            'images'].items():
                                        path = src.replace('@id@', sku)
                                        image = models.Image(type=key,
                                                             url=path)
                                        image_key = image.save()
                                        product.images.append(image_key)

                                    change = True
                                except Exception, e:
                                    logging.error('Get Medium Image')
                                    logging.error(e)
                                    raise Exception(
                                        'No Product Medium Image found for category_url : '
                                        + category_url)