Beispiel #1
0
    def perform(self, listing=None):
        doc = listing
        amazon = Vendor.query.filter_by(name='Amazon').one()
        listing = Listing.query.filter_by(vendor_id=amazon.id,
                                          sku=doc['sku']).first()
        if listing is None:
            listing = Listing(vendor=amazon)

        amz_details = {
            k: v
            for k, v in {
                'offers': doc.pop('offers', None),
                'prime': doc.pop('prime', None)
            }.items() if v is not None
        }

        listing.update(doc)
        if amz_details:
            if not listing.details or listing.details[-1].id:
                listing.details.append(ListingDetails(listing_id=listing.id))
            listing.details[-1].update(amz_details)

        db.session.add(listing)
        db.session.commit()

        self.context['listing_id'] = listing.id
        return listing.id
Beispiel #2
0
def scrape_area_jobs(area, searchcity, jobcategory, internship):
    cl_j = CraigslistJobs(site=searchcity,
                          area=area,
                          category=jobcategory,
                          filters={'is_internship': internship})
    genJ = cl_j.get_results(sort_by='newest', geotagged=True, limit=2)
    RESULTS = []
    while True:
        try:
            result = next(genJ)
        except StopIteration:
            break
        except Exception:
            continue
        listing = Listing.query.filter_by(JobKeyOrID=result["id"]).first()
        if listing is None:
            # Create Listing Object:
            listing = Listing(link=result["url"],
                              created=result["datetime"],
                              name=result["name"],
                              location=result["where"],
                              city=searchcity,
                              JobKeyOrID=result['id'],
                              InorCl="CL")
            #Save Session:
            try:
                RESULTS.append(listing)
                db.session.add(listing)
                db.session.commit()
            except Exception as inst:
                print(inst)
                print("Error DB")
                db.session.rollback()
    return RESULTS
Beispiel #3
0
def dict_to_listing(d):
    """
    Convert dictionary to listing object
    :param d: dictionary
    :return: listing object
    """
    ls = Listing()
    ls.title = d['title'] if 'title' in d else ''
    ls.description = d['description'] if 'description' in d else ''
    ls.employer = d['employer'] if 'employer' in d else ''
    ls.student_matches = d['student_matches'] if 'student_matches' in d else []
    ls.salary = float(d['salary']) if 'salary' in d else 0
    ls.location = d['location'] if 'location' in d else ''
    if 'desired_skills' in d:
        if type(d['desired_skills']) == 'str':
            skills = d['desired_skills'].strip().split(',')
            ls.desired_skills = [i.strip() for i in skills]
        else:
            ls.desired_skills = d['desired_skills']
    else:
        ls.desired_skills = []
    ls.job_type = d['job_type'] if 'job_type' in d else [
        'Internship', 'Full-Time'
    ]
    return ls
Beispiel #4
0
def scrape_area_indeed(keyword, searchcity):
    #Can use JobKey to see whether or not it's in the database
    RESULTS = []
    api = EZIndeed(indeedToken)
    EZIndeedResults = api.search(keyword=keyword, limit=3, location=searchcity)

    for result in EZIndeedResults:
        listing = Listing.query.filter_by(JobKeyOrID=result.jobkey).first()
        #If the listing already exist. Don't add it again.
        if listing is None:
            #If it does not exist. Get in more detail with it.
            #Create Listing Object:
            listing = Listing(link=result.url,
                              created=result.date,
                              name=result.company,
                              title=result.jobtitle,
                              location=result.date,
                              JobKeyOrID=result.jobkey,
                              city=searchcity,
                              InorCl="IN")
            #Save Session:
            try:
                RESULTS.append(listing)
                db.session.add(listing)
                db.session.commit()
            except Exception as inst:
                print(inst)
                print("Error DB")
                db.session.rollback()
    return RESULTS
Beispiel #5
0
def add_listing(comment):
    submission = comment.submission
    try:
        listing = Session.query(Listing).filter(Listing.submission_id == submission.id).one()
    except NoResultFound:
        listing = Listing()
    listing.submission_id = submission.id
    listing.title = submission.title
    listing.permalink = submission.permalink
    listing.flair_text = submission.link_flair_text
    listing.url = submission.url
    listing.redditor = submission.author.name
    listing.created_utc = datetime.utcfromtimestamp(submission.created_utc)
    listing.updated_utc = datetime.utcnow()
    if submission.thumbnail.startswith('https:'):
        listing.thumbnail_url = submission.thumbnail
    for line in comment.body.splitlines():
        m1 = p1.search(line)
        m2 = p2.search(line)
        m3 = p3.search(line)
        m4 = p4.search(line)
        m5 = p5.search(line)
        m6 = p6.search(line)
        m7 = p7.search(line)
        m8 = p8.search(line)
        m9 = p9.search(line)
        m10 = p10.search(line)
        m11 = p11.search(line)
        m12 = p12.search(line)
        if m1:
            listing.brand = m1.group(1).strip('*').strip()
        if m2:
            listing.model = m2.group(1).strip('*').strip()
        if m3:
            listing.size = m3.group(1).strip('*').strip()
        if m4:
            listing.width = m4.group(1).strip('*').strip()
        if m5:
            listing.last = m5.group(1).strip('*').strip()
        if m6:
            listing.upper = m6.group(1).strip('*').strip()
        if m7:
            listing.sole = m7.group(1).strip('*').strip()
        if m8:
            listing.condition = m8.group(1).strip('*').strip()
        if m9:
            listing.images = m9.group(1).strip('*').strip()
        if m10:
            listing.notes = m10.group(1).strip('*').strip()
        if m11:
            listing.price = m11.group(1).strip('*').strip()
        if m12:
            listing.country = m12.group(1).strip('*').strip()
    if not listing.size or not listing.brand or not listing.price:
        return
    Session.add(listing)
    return True
Beispiel #6
0
def ParseAsoListing(url):
    request = urllib.request.Request(url, headers=_HEADERS)
    html = urllib.request.urlopen(request).read().decode('utf-8')
    soup = bs4.BeautifulSoup(html, 'lxml')
    listing = Listing()

    listing.title = soup.find(
        'div', class_='adSpecView-header-Descr').find('div').string.strip()
    listing.url = url

    spans = soup.find_all('span')
    for span in spans:
        if span.find(text=re.compile(r'Price')):
            price_str = re.sub(r'[^(\d\.)]', '', span.next_element)
            if price_str:
                listing.price = float(price_str)
        elif span.find(text=re.compile(r'Reg #')):
            listing.registration = span.next_element.split()[-1].upper()
        elif span.find(text=re.compile(r'Serial #')):
            listing.serial = span.next_element.split()[-1].upper()
        elif span.find(text=re.compile(r'TTAF:')):
            hours_str = re.sub(r'[^(\d\.)]', '', span.next_element)
            if hours_str:
                listing.airframe_hours = float(hours_str)
        elif span.find(text=re.compile(r'Location:')):
            locations = span.next_element.split()
            if len(locations) > 1:
                listing.state = SanitizeState(locations[1].strip(' ,'))

    year = re.search(r'(19|20)\d\d', listing.title)
    if year:
        listing.year = int(year.group(0))

    model = re.search(r'M20[A-Z]\s*(\d{3})?', listing.title.upper())
    if model:
        listing.model = model.group(0)

    engine_table = soup.find('table', class_='enginePropView')
    if engine_table:
        rows = engine_table.find_all('tr')
        if len(rows) == 2:
            for i, col in enumerate(rows[1].find_all('td')):
                if not re.search(r'[^\d]', col.string):
                    listing.engine_hours = float(col.string)
                    listing.overhaul_type = rows[0].find_all(
                        'td')[i].string.upper()
                    break

    listing.gps = FindGps(html)
    listing.transponder = FindTransponder(html)

    return listing
Beispiel #7
0
def add_listing(asin, listing={}):
    # We may need to add a listing with just an asin.
    listing_exists = dbapi.listing_exists(asin)
    if not (listing_exists or listing):
        dbapi.add(Listing(asin=asin))
    elif not listing_exists:
        try:
            fprice = float(listing['lowest_price'])
        except:
            fprice = None
        try:
            l = Listing(asin=asin,
                        manufacturer=listing['manufacturer'],
                        title=listing['title'],
                        part_number=listing['part_number'],
                        price=fprice,
                        upc=listing['upc'])
            dbapi.add(l)
        except:
            print('Unable to add listing to db')
    else:
        print('{0} already exists in db'.format(asin))
Beispiel #8
0
def ParseTradeAPlaneListing(url):
    request = urllib.request.Request(url, headers=_HEADERS)
    html = urllib.request.urlopen(request).read().decode('utf-8')
    soup = bs4.BeautifulSoup(html, 'lxml')
    listing = Listing()

    listing.title = FindTradeAPlaneSpec(soup.find('h1'), 'string')
    listing.url = url
    listing.price = FindTradeAPlaneSpec(soup.find('span', itemprop='price'),
                                        'string', float)
    listing.year = FindTradeAPlaneSpec(soup.find('label', string='Year:'),
                                       'next_sibling', int)
    listing.registration = FindTradeAPlaneSpec(
        soup.find('label', string='Registration #:'), 'next_sibling')
    if not re.search(r'\d', listing.registration):
        listing.registration = None
    listing.model = FindTradeAPlaneSpec(
        soup.find('span', itemprop='manufacturer'), 'next_sibling')
    listing.serial = FindTradeAPlaneSpec(
        soup.find('label', string='Serial #:'), 'next_sibling')
    listing.airframe_hours = FindTradeAPlaneSpec(
        soup.find('label', string='Total Time:'), 'next_sibling', float)

    overhaul_str = FindTradeAPlaneSpec(
        soup.find('label', string='Engine 1 Overhaul Time:'), 'next_sibling')
    if overhaul_str:
        overhaul_strs = overhaul_str.split()
        if len(overhaul_strs) > 0:
            listing.engine_hours = float(overhaul_strs[0].replace(',', ''))
        if len(overhaul_strs) > 1:
            listing.overhaul_type = overhaul_strs[1]

    location_str = FindTradeAPlaneSpec(soup.find('label', string='Location:'),
                                       'next_sibling')
    if location_str:
        location_strs = location_str.split(',')
        if len(location_strs) == 1:
            listing.state = SanitizeState(location_strs[0].split()[0]\
                .replace('\n', ''))
        elif len(location_strs) == 2:
            listing.city = location_strs[0]
            listing.state = SanitizeState(location_strs[1].strip().split()[0]\
                .replace('\n', ''))

    listing.gps = FindGps(html)
    listing.transponder = FindTransponder(html)

    return listing
Beispiel #9
0
def create_listing():
    is_valid = True
    date = datetime.strptime(request.form.get("datepicker"), '%Y-%m-%d %I:%M')
    price = request.form.get("price")
    driving_from = request.form.get("from")
    going_to = request.form.get("to")
    description = f"Driving from {driving_from} to {going_to}"
    new_listing = Listing(user_id=session['user_id'],
                          date=date,
                          price=price,
                          location_from=driving_from,
                          location_to=going_to,
                          description=description)
    db.session.add(new_listing)
    db.session.commit()
    return redirect('/profile')
Beispiel #10
0
def ParseAirplaneMartListing(url):
    request = urllib.request.Request(url, headers=_HEADERS)
    html = urllib.request.urlopen(request).read().decode('utf-8', 'ignore')
    soup = bs4.BeautifulSoup(html, 'lxml')
    listing = Listing()

    listing.title = soup.find('font', size='5').find('b').string.strip()
    listing.url = url

    price_str = re.sub(r'[^(\d\.)]', '', FindAirplaneMartSpec(soup, 'Price:'))
    if price_str:
        listing.price = float(price_str)

    listing.registration = FindAirplaneMartSpec(soup, 'Registration:')
    listing.serial = FindAirplaneMartSpec(soup, 'Serial:')
    listing.airframe_hours = FindAirplaneMartSpec(soup, 'Airframe Time:',
                                                  float)

    engine_str = FindAirplaneMartSpec(soup, 'Engine Time\(s\):')
    if engine_str:
        match = re.search(r'([0-9\.]+)(?:\s+([A-Z]+))?', engine_str.upper())
        if match:
            listing.engine_hours = float(match.group(1))
            if len(match.groups()) >= 2:
                listing.overhaul_type = match.group(2)

    location_str = FindAirplaneMartSpec(soup, 'Aircraft Location:')
    if location_str:
        location_str = re.sub(r'\s*\(.*\)\s*', '', location_str)
        if location_str:
            locations = location_str.split(',')
            listing.city = locations[0].strip()
            if len(locations) >= 2:
                listing.state = SanitizeState(locations[1].split()[0].strip())

    year = re.search(r'(19|20)\d\d', listing.title)
    if year:
        listing.year = int(year.group(0))

    model = re.search(r'M20[A-Z]\s*(\d{3})?', listing.title.upper())
    if model:
        listing.model = model.group(0)

    listing.gps = FindGps(html)
    listing.transponder = FindTransponder(html)

    return listing
Beispiel #11
0
def ParseControllerListing(url):
    request = urllib.request.Request(url, headers=_HEADERS)
    html = urllib.request.urlopen(request).read().decode('utf-8')
    soup = bs4.BeautifulSoup(html, 'lxml')
    listing = Listing()

    listing.title = soup.find('h1').string.strip()
    listing.url = url

    h4s = soup.find_all('h4')
    for h4 in h4s:
        if h4.find(text=re.compile(r'For Sale Price:')):
            price_str = re.sub(r'[^(\d\.)]', '', h4.next_element)
            if price_str:
                listing.price = float(price_str)
            break

    listing.year = FindControllerSpec(soup, 'Year', int)
    listing.registration = FindControllerSpec(soup, 'Registration #')
    if not re.search(r'\d', listing.registration):
        listing.registration = None
    listing.model = FindControllerSpec(soup, 'Model')
    listing.serial = FindControllerSpec(soup, 'Serial #')
    listing.airframe_hours = FindControllerSpec(soup, 'Total Time', float)

    overhaul_str = FindControllerSpec(soup, 'Overhaul')
    if overhaul_str:
        hours_match = re.search(r'([0-9,\.]+)', overhaul_str)
        type_match = re.search(r'(?:[0-9,\.]+)\s*([a-zA-Z]+)', overhaul_str)
        if hours_match:
            listing.engine_hours = float(hours_match.group(1).replace(',', ''))
        if type_match:
            listing.overhaul_type = type_match.group(1)

    location = soup.find('a', class_='machinelocation').string
    if location and location.string:
        location_strs = location.string.split(',')
        if len(location_strs) == 1:
            listing.state = SanitizeState(location_strs[0])
        elif len(location_strs) == 2:
            listing.city = location_strs[0]
            listing.state = SanitizeState(location_strs[1].strip())

    listing.gps = FindGps(html)
    listing.transponder = FindTransponder(html)

    return listing
Beispiel #12
0
def private_listing(request,board_slug,category_slug,listing_slug=None):
    """Create or edit listing"""
    category = get_object_or_404(Category,slug=category_slug, is_active=True)   
    board = get_object_or_404(Board,slug=board_slug, is_active=True)  
    if listing_slug is not None:
        listing = get_object_or_404(Listing,slug=listing_slug, 
            category=category, board=board, user=request.user)
    else:
        listing = Listing(category=category, board=board, user=request.user)
    if request.method == "POST":
        form = ListingForm(request.POST, instance=listing)
        if form.is_valid():
            form.save()
            form.instance.create_slug()
            args = form.instance.board.slug, form.instance.category.slug, 
                form.instance.slug
            return HttpResponseRedirect(reverse('public_listing', args=args))
Beispiel #13
0
def get_part_listings(part):
    print('fetching listings for part', part)
    listings = []
    url = 'http://www.bricklink.com/search.asp'
    params = {
        'viewFrom': 'sf',
        'qMin': part.qty,
        'colorID': part.color_id,
        'shipCountryID': 'US',
        'sellerCountryID': 'US',
        'moneyTypeID': 1,
        'w': part.element_id,
        'sellerLoc': 'C',
        'searchSort': 'P',
        'sz': 500
    }
    html = requests.get(url, headers=headers, params=params).text
    if 'Quota Exceeded' in html:
        raise QuotaExceededError()
    results = soup(html, 'html.parser').findAll('td', {'valign' : 'TOP'})
    if len(results) == 0:
        raise PartNotFoundError(part)
    for r in results:
        try:
            link = r.find('a')
            price = r.findAll('b')[1].text
            price = float(price.replace('US $', ''))
            store_id = parse_qs(urlparse(link['href']).query)['p'][0]
            inventory_id = int(parse_qs(urlparse(link['href']).query)['itemID'][0])
            if not price > 0:
                price = 0.01
                print('price: fallback on price 0.01')
            if price is None or link['href'] is None or store_id is None:
                raise ListingParsingError()
            listing = Listing(part.element_id, part.color_id, part.qty, price, link.text, link['href'], store_id, inventory_id)
            if not listing.price > 0:
                raise PriceZeroError(listing)
            listings.append(listing)
        except KeyError as e:
            # Skip the malformed listing
            print('KeyError', e)
    print('Found {} listings'.format(len(listings)))
    return listings
Beispiel #14
0
def check_market():
    push_context()
    log.info('Checking market prices')

    psa = PixelStarshipsApi()
    market_data = psa.get_market_data()
    for k, v in market_data.items():
        listing = Listing(id=k,
                          sale_at=v['sale_at'],
                          item_name=v['item_name'],
                          item_id=v['item_id'],
                          amount=v['amount'],
                          currency=v['currency'],
                          price=v['price'],
                          user_id=v['user_id'],
                          modification=v['modification'])
        db.session.merge(listing)

    log.info('{} listings updated'.format(len(market_data)))
    db.session.commit()
Beispiel #15
0
    def perform(self, vendor_id=None, order_id=None, items=None):
        amazon = Vendor.query.filter_by(name='Amazon').one()
        vendor = Vendor.query.filter_by(id=vendor_id).one()

        for item_doc in items:
            sku = item_doc['sku']
            amz_listing = Listing.query.filter_by(vendor_id=amazon.id, sku=sku).first() \
                          or Listing(vendor=amazon, sku=sku)

            item = OrderItem.query.filter(
                OrderItem.order_id == order_id,
                OrderItem.extra['order_item_id'].astext
                == item_doc['order_item_id']).first() or OrderItem(
                    order_id=order_id)

            item.quantity = item_doc.pop('qty_shipped')
            item.received = item.quantity
            item.source = Inventory.query.filter_by(owner_id=vendor.id, listing_id=amz_listing.id).first() \
                          or Inventory(owner=vendor, listing=amz_listing)
            item.destination = None
            item.update(item_doc)

            db.session.add(item)
            db.session.commit()
Beispiel #16
0
def list_book():
    form = ListBook()
    msg = ""
    if request.method == "POST":
        isbn = clean_isbn(form.isbn.data)
        if valid_isbn(isbn):
            book = get_book_by_isbn(isbn)
            print book
            if book is not None:
                listing = Listing(user_id=g.user.id,
                                  listing_ref=book.id,
                                  course=form.course.data.replace(" ",
                                                                  "").upper(),
                                  notes=form.notes.data,
                                  cost=form.cost.data)
                db.session.add(listing)
                db.session.commit()
                msg = "Listing added successfully!"
            else:
                msg = "Book not found!"
        else:
            msg = "ISBN was not 10 or 13 characters long!"

    return render_template("list_book.html", form=form, msg=msg)
def import_listings():
    listings = pd.read_csv('../../data/listings/nyc_listings.csv')
    failed_import = []
    for idx, listing in listings.iterrows():
        db_item = Listing(airBnbId=listing['id'],
                          url=listing['listing_url'],
                          name=listing['name'],
                          picture_url=listing['picture_url'],
                          host_url=listing['host_url'],
                          host_name=listing['host_name'],
                          latitude=listing['latitude'],
                          longitude=listing['longitude'],
                          room_type=listing['room_type'],
                          price=listing['price'][1:],
                          minimum_nights=listing['minimum_nights'],
                          number_of_reviews=listing['number_of_reviews'],
                          review_scores_rating=listing['review_scores_rating'])
        try:
            db_item.save()
        except:
            failed_import.append(listing['id'])

    with open('../../data/listings/failed_import.json', 'w') as outfile:
        json.dump(failed_import, outfile)
Beispiel #18
0
    def perform(self, listing=None):
        # Do some basic cleaning
        for field, value in listing.items():
            if isinstance(value, str):
                listing[field] = value.strip()

        # Try to locate the listing in the database
        sku = listing.pop('sku')
        vendor_id = listing.pop('vendor_id', None)

        if vendor_id is None:
            netloc = urlparse(listing['detail_url'])[1]
            vendor = Vendor.query.filter(Vendor.url.ilike(f'%{netloc}%')).one()
            vendor_id = vendor.id

        model = Listing.query.filter_by(vendor_id=vendor_id, sku=sku).one_or_none()\
                    or Listing(vendor_id=vendor_id, sku=sku)

        # Update and commit
        model.update(listing)
        db.session.add(model)
        db.session.commit()

        return model.id
Beispiel #19
0
def create_listing(args, identity):

    listing = Listing(
        id=args.get("id") or str(uuid.uuid4()), reference=random_letters_numbers(8)
    )

    if args.get("address"):

        # get your object
        address_details = args.get("address")

        # pythonize js obj
        addr = snake_case_keys(remove_empty_values(address_details))

        # grab keys from the model
        keys = Address.get_attributes().keys()

        # dictionary comprehension to create final obj
        # aka this is making a constructor to match the keys from the model and
        # disregarding anything that doesn't match so there aren't problems
        # later
        listing.address = Address(**{k: v for k, v in addr.items() if k in keys})

        # make default property details
        listing.property_details = PropertyDetails(bedrooms=0, bathrooms=0, carparks=0)

    else:
        raise ValueError("Invalid input, no addressDetails!")

    if args.get("contact_id"):
        contact = call_service(
            CONTACTS_LAMBDA, identity, "getContact", {"id": args["contact_id"]}
        )

        listing.contacts = [remove_empty_values(contact)]

    elif args.get("contacts"):
        contacts = []
        for contact in args["contacts"]:
            result = call_service(
                CONTACTS_LAMBDA,
                identity,
                "createContact",
                {"input": camel_case_keys(contact)},
            )
            contacts.append(remove_empty_values(result))
        listing.contacts = contacts
    else:
        raise ValueError("Invalid input, no contactId or contacts were provided")
    if args.get("primary_agent"):
        listing.agent_usernames = [args["primary_agent"]]

        try:
            logger.debug(
                "Fetching agent team from auth profile for %s", args["primary_agent"]
            )
            agent = call_service(
                PROFILE_LAMBDA, identity, "getUser", {"email": args["primary_agent"]}
            )

            listing.teams = [agent["team"]]
        except:
            raise ValueError("Provided agent does not have an auth profile!")
    else:
        listing.teams = [get_team(identity)]
        listing.agent_usernames = [get_email(identity)]
    listing.save()
    sns_client.publish(
        TopicArn='arn:aws:sns:ap-southeast-2:889389499482:listing-created-prod',
        Message=json.dumps(
            {"listingId": listing.id, "fullAddress": listing.address.full_address}
        ),
    )
    return listing.to_json()
Beispiel #20
0
            q.put(offer)
        print(f'Current queue size: {q.qsize()}')
        # go through every listing and insert data into the database
        queue_size = q.qsize()
        listing_counter = 1
        while(not q.empty()):
            print(f'Processing listing {listing_counter}/{queue_size} on page #{page_counter}...')
            listing = q.get()
            try:
                (id, brand, model, year, mileage, engine_capacity, fuel_type, price) = get_car_data(listing)
            except ValueError as e:
                print(e.args)
                continue
            except IndexError as ie:
                print(ie.args)
                continue
                
            if(session.query(Listing).filter_by(id=id).first()):
                print('Listing already in the database...')
            else:
                car = Listing(id=id, brand=brand, model=model, year=year, mileage=mileage, engine_capacity=engine_capacity, fuel_type=fuel_type, price=price)
                session.add(car)
                session.commit()
            listing_counter += 1

        page_url = get_next_page_url(soup)
        page_counter += 1
        sleep(0.1)

    session.close()
Beispiel #21
0
def newListing():
    categories = session.query(Category).all()
    if request.method == 'POST':
        if checkIfExists(request.form['name'],Listing):
            existingListing = session.query(Listing).filter_by(name=request.form['name']).one()
            flash('A listing called "%s" already exists. Please re-name your listing.' % existingListing.name)
            return render_template('newListing.html', categories=categories)
        elif request.form['name'] == '':
            flash('Please enter a name for your listing.')
            return render_template('newListing.html', categories=categories)
        elif request.form['new-category'] == '' and request.form['category'] == 'False':
            flash('You must select or create a category')
            return render_template('newListing.html', categories=categories)
        elif request.form['description'] == '':
            flash('You must fill out a description')
            return render_template('newListing.html', categories=categories)
        else:
            imagename = ''
            # check if user uploaded an image
            if request.files['image']:
                if 'image' not in request.files:
                    flash('No file part')
                    return render_template('newListing.html', categories=categories)
                image = request.files['image']
                # if user does not select file, browser also
                # submits an empty part without the filename
                if image.filename == '':
                    flash('No selected image')
                    return redirect(request.url)
                if image and allowed_file(image.filename):
                    imagename = secure_filename(image.filename)
                    image.save(os.path.join(app.config['UPLOAD_FOLDER'], imagename))
            if request.form['new-category']:
                if checkIfExists(request.form['new-category'],Category):
                    flash('A category with that name already exists. Please re-name your category.')
                    return render_template('newListing.html', categories=categories)
                else:
                    newCategory = Category(name=request.form['new-category'])
                    session.add(newCategory)
                    session.commit()
                newListing = Listing(
                    name=request.form['name'], 
                    description=request.form['description'], 
                    image=imagename,
                    category_id=getCategoryID(request.form['new-category']),
                    user_id=login_session['user_id'])
                session.add(newListing)
                flash('New Listing "%s" Successfully Created' % newListing.name)
                session.commit()
                return redirect(url_for('showListings'))
            else:
                newListing = Listing(
                    name=request.form['name'], 
                    description=request.form['description'], 
                    image=imagename,
                    category_id=getCategoryID(request.form['category']), 
                    user_id=login_session['user_id'])
                session.add(newListing)
                flash('New Listing "%s" Successfully Created' % newListing.name)
                session.commit()
                return redirect(url_for('showListings'))   
    else:
        return render_template('newListing.html', categories=categories)
Beispiel #22
0
def add_listing_to_database(downloaded_json, session):
    try:
        data = json.loads(downloaded_json) 

        if 'error' in data or 'data' not in data:
            print 'Listing had no data field.'
            return

        actual_data = data['data']

        id = actual_data['id']

        photos = [
            Photo(
                id=photo['id'],
                url=photo['url'],
                width=photo['width'],
                height=photo['height'],
                image_api=photo['image_api'],
                rotate=photo['rotate'],
            )
            for photo in actual_data['photos']
        ]

        buyer_id = actual_data.get('buyer_id')
        if not buyer_id:
            buyer = None
        else:
            buyer = User(id=actual_data.get('buyer_id'))

        seller_id = actual_data['seller'].get('id')
        seller = User(id=actual_data['seller'].get('id'))

        # follower information isn't stored with the listing
        new_listing = Listing(
            id=id,
            title=actual_data.get('title'),
            created_at=parse_datetime(actual_data.get('created_at')),
            price=actual_data.get('price'),
            currency=actual_data.get('currency'),
            ship_cost=actual_data.get('ship_cost'),
            ship_to=actual_data.get('ship_to'),
            fee=actual_data.get('fee'),
            designer_name=actual_data.get('designer')['name'],
            designer_id=actual_data.get('designer')['id'],
            description=actual_data.get('description'),
            size=actual_data.get('size'),
            category=actual_data.get('category'),
            followed=actual_data.get('followed'),
            buy_now=actual_data.get('buy_now'),
            make_offer=actual_data.get('make_offer'),
            accept_binding_offers=actual_data.get('accept_binding_offers'),
            sold=actual_data.get('sold'),
            sold_price=actual_data.get('sold_price'),
            sold_at=parse_datetime(actual_data.get('sold_at')),
            dropped=actual_data.get('dropped'),
            price_drops=parse_price_drops(actual_data.get('price_drops')),
            price_updated_at=parse_datetime(actual_data.get('price_updated_at')),
            strata=actual_data.get('strata'),
            followers=[],
            follower_count=actual_data.get('follower_count'),
            photos=photos,
            num_photos=len(photos),
            buyer_id=buyer_id,
            buyer=buyer,
            seller_id=seller_id,
            seller=seller,
        )

        session.merge(new_listing)
        session.commit()

    except Exception as e:
        print 'Unhandled error: {}'.format(e.message)
        return None
Beispiel #23
0
def create_new_listing(user_id):
    json_data = request.get_json()
    name = json_data.get('name', '')
    item_description = json_data.get('item_description', '')
    total_value = float(json_data.get('total_value', ''))
    # location_lat 		= float(json_data.get('location_lat',''))
    # location_lon		= float(json_data.get('location_lon',''))

    # Check to see if the user exists
    u = User.get_by_id(user_id)
    if u is None:
        raise InvalidUsage('UserID does not match any existing user',
                           status_code=400)

    u_key = ndb.Key('User', user_id)

    # if total_value > MAX_ITEM_VALUE:
    # 	raise InvalidUsage('Total value is too large', status_code=400)

    status = 'Available'
    rating = -1.0
    location = ndb.GeoPt(40.112814, -88.231786)

    # INSERT FUNCTION TO CALCULATE RENTAL RATES HERE
    hourly_rate, daily_rate, weekly_rate = get_rates(total_value)

    # Add listing to Datastore
    l = Listing(owner=u_key,
                status=status,
                name=name,
                item_description=item_description,
                rating=rating,
                total_value=total_value,
                hourly_rate=hourly_rate,
                daily_rate=daily_rate,
                weekly_rate=weekly_rate,
                location=location)
    try:
        listing_key = l.put()
        listing_id = str(listing_key.id())
    except:
        abort(500)

    # Add listing to Search App
    new_item = search.Document(doc_id=listing_id,
                               fields=[
                                   search.TextField(name='name', value=name),
                                   search.GeoField(name='location',
                                                   value=search.GeoPoint(
                                                       location.lat,
                                                       location.lon)),
                                   search.TextField(name='owner_id',
                                                    value=str(user_id))
                               ])
    try:
        index = search.Index(name='Listing')
        index.put(new_item)
    except:
        abort(500)

    data = {
        'listing_id': listing_id,
        'date_created': l.date_created,
        'date_last_modified': l.date_last_modified,
        'status': status
    }
    resp = jsonify(data)
    resp.status_code = 201
    return resp
Beispiel #24
0
        print('Objective value =', solver.Objective().Value())
    else:
        print('The problem does not have an optimal solution.')

    return optimal_listings


def to_var_index(parts, listings, part_index, listing_index):
    return len(listings) * part_index + listing_index


def to_listing_index(parts, listings, var_index):
    return math.floor(var_index / len(parts))


def to_part_index(parts, listings, var_index):
    return var_index % len(parts)


if __name__ == '__main__':
    parts = [
        Part(3010, 1, 10),
        Part(3011, 1, 6),
    ]
    listings = [
        Listing(3010, 1, 10, 0.1, '', '', 's1', 301000),
        Listing(3011, 1, 10, 0.1, '', '', 's2', 301100)
    ]
    stores = [Store('s1'), Store('s2')]
    optimize(parts, listings, stores)