示例#1
0
 def __init__(self,
              license_plate,
              make,
              model,
              year,
              type_of_vehicle,
              seats,
              fuel,
              transmission,
              dates=[]):
     self.__price_list = Price()
     self.__license = license_plate
     self.__make = make
     self.__model = model
     self.__year = year
     self.__type_of_vehicle = type_of_vehicle
     self.__seats = seats
     self.__fuel = fuel
     self.__transmission = transmission
     self.__rent_dates = dates
     self.__rented_dates = []
     self.__price_per_day = self.__price_list.get_price(type_of_vehicle)
     self.__insurance_per_day = self.__price_list.get_insurance(
         type_of_vehicle)
     self.set_rented_dates()
示例#2
0
def create_prices():
    price1 = Price(id=1, show_id=ndb.Key(Show, 1), category_id=ndb.Key(Category, 1), amount=500)
    price2 = Price(id=2, show_id=ndb.Key(Show, 1), category_id=ndb.Key(Category, 2), amount=200)
    price3 = Price(id=3, show_id=ndb.Key(Show, 2), category_id=ndb.Key(Category, 3), amount=200)
    price4 = Price(id=4, show_id=ndb.Key(Show, 3), category_id=ndb.Key(Category, 4), amount=200)
    price5 = Price(id=5, show_id=ndb.Key(Show, 4), category_id=ndb.Key(Category, 4), amount=1000)
    ndb.put_multi([price1, price2, price3, price4, price5])
def update_data(input_data: list[str]):
    try:
        for data in input_data:
            state, district, mandi, crop, crop_variety, date, price = data.split(
                ', ')

            # check for the instance of mandi in mandi_instances else create
            if (mandi, state, district) in mandi_instances:
                mandi_instance = mandi_instances[(mandi, state, district)]
            else:
                mandi_instance = Mandi(mandi, state, district)
                mandi_instances[(mandi, state, district)] = mandi_instance

            # add crop for the particular mandi
            mandi_instance.add_crop(crop)

            # check for the instance of crop in crop_instances else create
            if crop in crop_instances:
                crop_instance = crop_instances[crop]
            else:
                crop_instance = Crop(crop)
                crop_instances[crop] = crop_instance

            # add crop_variety for the crop
            crop_instance.add_crop_variety(crop_variety)

            # check for the instance of crop_variety in crop_variety_instances else create
            if crop_variety in crop_variety_instances:
                crop_variety_instance = crop_variety_instances[crop_variety]
            else:
                crop_variety_instance = CropVariety(crop_variety)
                crop_variety_instances[crop_variety] = crop_variety_instance

            # check for the instance of date, price in price_instance else create
            if (mandi, crop, crop_variety) in price_instances:
                price_instance = price_instances[(mandi, crop, crop_variety)]
            else:
                price_instance = Price(mandi, crop, crop_variety)
                price_instances[(mandi, crop, crop_variety)] = price_instance

            # add date and price for a paticular mandi, crop and crop_variety
            price_instance.add_date_price(date, price)

            # check for the instance of mandi in mandi_instance else create
            if (district, state) in district_instances:
                district_instance = district_instances[(district, state)]
            else:
                district_instance = District(district, state)
                district_instances[(district, state)] = district_instance

            # add mandi in district
            district_instance.add_mandi(mandi)

    except Exception as e:
        print(e)
        raise Exception(e)

    print("Data successfully updated")
    return 1
示例#4
0
    def post(self):
        show = Show()
        # show.key=ndb.Key('Show', int(request.form['id']))
        show.event_id = ndb.Key('Event', int(request.form['event_id']))
        show.client_id = ndb.Key('Client', int(request.form['client_id']))
        show.screen_id = ndb.Key('Screen_Layout', int(request.form['screen_id']))
        show.name = request.form['name']
        show.datetime = datetime.datetime.now()
        screen = ndb.Key('Screen_Layout', int(request.form['screen_id']))
        seats = screen.get().seats
        print type(seats)
        updated_seats = {}
        for each in seats:
            updated_seats[str(each['row'])+'-'+str(each['column'])]= {'status':4}
        show.seats = updated_seats
        res = show.put()

        # The below paragraph should be deleted later
        offset_id = 21
        prices = []
        print show.screen_id
        categories = Category.query(Category.screen_id == show.screen_id).fetch()
        for category in categories:
            price1 = Price(id=show.key.id() + offset_id, show_id=show.key, category_id=category.key, amount=500)
            offset_id += 1
            prices.append(price1)
        print "###"
        print prices
        for price in prices:
            price.put()

        # The above paragraph should be deleted later

        return jsonify({'id': res.id(), 'message': "Success"})
示例#5
0
def onePriceRequests(product_id):
    if request.method == 'GET':
        try:
            prices = Price.query.filter_by(product_id=product_id)
            return jsonify([price.serialize for price in prices]), 200
        except Exception as e:
            return jsonify({'error': "{}".format(e.__cause__)}), 400

    if request.method == 'POST':
        try:
            body = json.loads(request.get_data())
            price_entry = Price(product_id, body['price'], body['currency'])
            db.session.add(price_entry)
            db.session.commit()
            return jsonify({
                'response':
                "Added price {} {} to product '{}'".format(
                    body['currency'], body['price'], product_id)
            }), 200
        except Exception as e:
            return jsonify({'error': "{}".format(e.__cause__)}), 400

    if request.method == 'DELETE':
        try:
            prices = Price.query.filter_by(product_id=product_id)
            [db.session.delete(price) for price in prices]
            db.session.commit()
            return jsonify({
                'response':
                "Product '{}' prices were successfully deleted from the database"
                .format(product_id)
            }), 200
        except Exception as e:
            return jsonify({'error': "{}".format(e.__cause__)}), 400
示例#6
0
 def symbol_ticker(self):
     response = self.client.get_symbol_ticker(symbol=self.get_symbol())
     print(response)
     return Price(pair=self.get_symbol(),
                  currency=self.currency.lower(),
                  asset=self.asset.lower(),
                  exchange=self.name.lower(),
                  current=response['price'],
                  openAt=utils.format_date(datetime.now()))
示例#7
0
 def post(self):
     try:
         data = json.loads(request.data)
         new_price = Price(data["id_company"], data["price"])
         db.session.add(new_price)
         db.session.commit()
         return {
             "message": f"Price {new_price.price} has been created successfully."
         }
     except Exception as e:
         return {"message": "Error :"}
示例#8
0
    def post(self):
        logging.info("Running scrape handler")
        scraper = Scraper()
        scrape_result = scraper.scrape_all()

        seats = []
        parties = []
        prices = []
        winners = {}
        for s in scrape_result:
            if s.name not in seats:
                seats.append(Seat(name=s.name, state=s.state, id=s.name))
                seats[-1].put()

            lowest_price = 1000
            winner = ''
            for c in s.candidates:
                if c.name not in parties:
                    parties.append(Party(name=c.name, id=c.name))
                party_key = ndb.Key(Party, c.name)
                seat_key = ndb.Key(Seat, s.name)
                price = Price(party=party_key, seat=seat_key, price=c.price)
                price.put()

                if c.price < lowest_price:
                    lowest_price = c.price
                    winner = c.name

            if winner in winners:
                winners[winner] += 1
            else:
                winners[winner] = 1

        for party in parties:
            if party.name in winners:
                party.num_seats = winners[party.name]
            else:
                party.num_seats = 0
            party.put()

        self.response.out.write(winners)
示例#9
0
  def post(self):
    logging.info("Running scrape handler")
    scraper = Scraper()
    scrape_result = scraper.scrape_all()

    seats = []
    parties = []
    prices = []
    winners = {}
    for s in scrape_result:
      if s.name not in seats:
        seats.append(Seat(name=s.name, state=s.state, id=s.name))
        seats[-1].put()

      lowest_price = 1000
      winner = ''
      for c in s.candidates:
        if c.name not in parties:
          parties.append(Party(name=c.name, id=c.name))
        party_key = ndb.Key(Party, c.name)
        seat_key = ndb.Key(Seat, s.name)
        price = Price(party=party_key, seat=seat_key, price=c.price)
        price.put()

        if c.price < lowest_price:
          lowest_price = c.price
          winner = c.name

      if winner in winners:
        winners[winner] += 1
      else:
        winners[winner] = 1

    for party in parties:
      if party.name in winners:
        party.num_seats = winners[party.name]
      else:
        party.num_seats = 0
      party.put()

    self.response.out.write(winners)
示例#10
0
    def generate_listing():
        origin = vars(Location("Townsend", "54175", "WI"))
        destination = vars(Location("Beverly Hills", "90210", "CA"))
        partner_reference_id = "multi-car"
        trailer_type = "OPEN"
        vehicles = [
            vars(Vehicle("5", 2008, "nissan", "altima", 1, False, "CAR")),
            vars(Vehicle("6", 2014, "toyota", "camry", 1, True, "CAR"))
        ]
        has_in_op_vehicle = False
        available_date = "2021-12-31"
        desired_delivery_date = "2021-12-31"
        cod = vars(Cod("1600", "CHECK", "DELIVERY"))
        bla = vars(Price(cod, "1600"))
        price = {'cod': cod, 'total': '1600'}
        price_two = json.loads(
            json.dumps(Price(cod, "1600"), default=lambda o: o.__dict__))

        return Listing(origin, destination, partner_reference_id,
                       desired_delivery_date, trailer_type, vehicles,
                       has_in_op_vehicle, available_date, price)
示例#11
0
 def __init__(self, origin, destination, partnerReferenceId,
              desiredDeliveryDate, trailerType, vehicles,
              hasInOpVehicle: bool, availableDate, price, **kwargs):
     self.origin = Location(**origin)
     self.destination = Location(**destination)
     self.partnerReferenceId = partnerReferenceId
     self.desiredDeliveryDate = desiredDeliveryDate
     self.trailerType = trailerType
     self.vehicles = [Vehicle(**x) for x in vehicles]
     self.hasInOpVehicle = hasInOpVehicle
     self.availableDate = availableDate
     self.price = Price(**price)
示例#12
0
    def post(self):
        # Got client ID from environ
        user_id = request.environ['USER_ID']
        client_id = user_id.get().detail_id

        show = Show()
        show.event_id = ndb.Key('Event', int(request.json['event_id']))
        show.client_id = client_id  # Fetched from the environ values.
        show.screen_id = ndb.Key('Screen_Layout',
                                 int(request.json['screen_id']))
        show.datetime = datetime.strptime(request.json['datetime'],
                                          "%d-%m-%Y %H:%M")
        screen = ndb.Key('Screen_Layout', int(request.json['screen_id']))
        seats = screen.get().seats
        updated_seats = {}
        for each in seats:
            updated_seats[str(each['row']) + '-' + str(each['column'])] = {
                'status': 4
            }
        show.seats = updated_seats

        categories_price = request.json['category-price']
        res = show.put()

        # Creating a price for each request
        try:
            for each in categories_price:
                price = Price(show_id=res,
                              category_id=ndb.Key('Category',
                                                  int(each['category'])),
                              amount=int(each['price']))
                print '########'
                print type(price.category_id.id())
                price.put()

        except:
            return jsonify({"code": 500, "message": "server error"})

        return jsonify({"code": 200, "id": res.id(), "message": "Success"})
示例#13
0
 def post(self):
     price = Price()
     # price.key=ndb.Key('Price', int(request.form['id']))
     price.show_id = ndb.Key('Show', int(request.form['show_id']))
     price.category_id = ndb.Key('Category', int(request.form['category_id']))
     price.amount = int(request.form['amount'])
     res = price.put()
     return jsonify({'id': res.id(), 'message': "Success"})
示例#14
0
 def websocket_event_handler(self, msg):
     if msg['e'] == 'error':
         print(msg)
         self.close_socket()
     else:
         self.strategy.set_price(
             Price(pair=self.compute_symbol_pair(),
                   currency=self.currency,
                   asset=self.asset,
                   exchange=self.name,
                   current=msg['b'],
                   lowest=msg['l'],
                   highest=msg['h']))
         self.strategy.run()
示例#15
0
 def GetCurrentPriceDic():
     tCurrentPrice = Price()
     tPriceQuery = Price().all()
     tPriceQuery.order("-priceDateCreated")
     tPriceQuery.filter("priceType", 'regular')
     tCurrentPrice = tPriceQuery.fetch(limit=1)[0]
         
     tPriceDictionary = PriceContainer.GetBasePriceDictionary()
     
     tSortedProperties = sorted(tCurrentPrice.properties().keys())
     for tCurrentProperty in tSortedProperties:
         try:
             tMatches = re.match(r'price(?P<number>[0-9]{4}m)', str(tCurrentProperty))
             tMatchedKey = str(tMatches.group('number'))
             
             tPriceDictionary[tMatchedKey] = tCurrentPrice.__getattribute__(tCurrentProperty)
         except:
             logging.debug('Could not find a key in: ' + str(tCurrentProperty))
     
     tPriceList = []
     tSortedPriceKeys = sorted(tPriceDictionary.keys())
     
     tCleanPriceDictionary = {}
     for tCurrentKey in tSortedPriceKeys:
         if(tCurrentKey[:3] == '000'):
             tKey = tCurrentKey[3:]
         elif(tCurrentKey[:2] == '00'):
             tKey = tCurrentKey[2:]
         elif(tCurrentKey[:1] == '0'):
             tKey = tCurrentKey[1:]
         else:
             tKey = tCurrentKey
             
         tCleanPriceDictionary[tKey] = str(tPriceDictionary[tCurrentKey])
         tCleanPriceDictionary[tKey.upper()] = str(tPriceDictionary[tCurrentKey])
             
     return tCleanPriceDictionary
示例#16
0
    def historical_symbol_ticker_candle(
            self,
            start: datetime,
            end=None,
            interval=Client.KLINE_INTERVAL_1MINUTE):
        # Convert default seconds interval to string like "1m"
        if isinstance(interval, int):
            interval = str(floor(interval / 60)) + 'm'

        output = []
        for candle in self.client.get_historical_klines_generator(
                self.get_symbol(), interval, start, end):
            """
                [
                    [
                        1499040000000,      # Open time
                        "0.01634790",       # Open
                        "0.80000000",       # High
                        "0.01575800",       # Low
                        "0.01577100",       # Close
                        "148976.11427815",  # Volume
                        1499644799999,      # Close time
                        "2434.19055334",    # Quote asset volume
                        308,                # Number of trades
                        "1756.87402397",    # Taker buy base asset volume
                        "28.46694368",      # Taker buy quote asset volume
                        "17928899.62484339" # Can be ignored
                    ]
                ]

            """
            output.append(
                Price(pair=self.compute_symbol_pair(),
                      currency=self.currency.lower(),
                      asset=self.asset.lower(),
                      exchange=self.name.lower(),
                      current=candle[1],
                      lowest=candle[3],
                      highest=candle[2],
                      volume=candle[5],
                      openAt=utils.format_date(
                          datetime.fromtimestamp(int(candle[0]) / 1000))))

        return output
示例#17
0
    def get(self, event_id, show_id):
        print request.headers
        event_id = int(event_id)
        show_id = int(show_id)
        show = ndb.Key(Show, show_id).get()
        show_screen = show.screen_id.get()
        screen_max_row_col = (show_screen.max_rows, show_screen.max_columns)
        seats_price_category = {}

        categories = Category.query(
            Category.screen_id == show.screen_id).fetch()
        for category in categories:
            price = Price.query(Price.show_id == show.key,
                                Price.category_id == category.key).get()
            if price is not None:
                price_amount = price.amount
            else:
                price_amount = 0
            for seat in category.seats:
                seats_price_category[(seat['row'], seat['column'])] = {
                    'price': price_amount,
                    'category': category.name
                }

        seats_info = {}
        for seat, description in show.seats.iteritems():
            row, column = seat.split('-')
            row = int(row)
            column = int(column)
            # seat_detail = seat
            seats_info[seat] = {
                'price': seats_price_category[(row, column)]['price'],
                'status': description['status'],
                'category': seats_price_category[(row, column)]['category']
            }
            # seat_detail['price'] = seats_price[(seat['row'], seat['column'])]
            # seats_info.append(seat_detail)
        print "now here"
        return jsonify({
            'show_id': show.key.id(),
            'screen_max_row_col': screen_max_row_col,
            'screen_seats': seats_info
        })
示例#18
0
def _fetch_price(stock: Stock):
    ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko)' \
         'Chrome/78.0.3904.97 Safari/537.36'
    url = f'https://finance.naver.com/item/sise_day.nhn?code={stock.code}'
    price_list = []

    for idx in range(1, 3):
        response = requests.get(headers={'user-agent': ua},
                                url=f'{url}&page={idx}')
        soup = BeautifulSoup(response.text, features='html.parser')
        tr_list = soup.find_all('tr')
        for tr in tr_list:
            if 'onmouseover' in tr.attrs:
                tds = tr.find_all('td')
                date_str = tds[0].find('span').text
                date = datetime.strptime(date_str, '%Y.%m.%d')
                price_str = tds[1].find('span').text
                price = int(price_str.replace(',', ''))
                price_list.append(
                    Price(price=price, stock=stock, created_at=date))

    return price_list
示例#19
0
    def __init__(self,
                 exchange: Exchange,
                 period_start: datetime,
                 period_end=None,
                 interval=60):
        self.launchedAt = datetime.now()
        # Try to find dataset
        dataset = Dataset().get({
            "exchange": exchange.name.lower(),
            "currency": exchange.currency.lower(),
            "asset": exchange.asset.lower(),
            "periodStart": period_start,
            "periodEnd": period_end,
            "candleSize": interval
        })
        if dataset and len(dataset) > 0:
            print(dataset)
            print(dataset[0])
            print("Dataset found: " + dataset[0]['uuid'])
            price = Price()
            for prices in price.query('get', {"dataset": dataset[0]['uuid']}):
                for price in prices:
                    print(price)
                    newPrice = Price()
                    newPrice.populate(price)
                    exchange.strategy.set_price(newPrice)
                    exchange.strategy.run()
        else:
            print("Dataset not found, external API call to " + exchange.name)
            for price in exchange.historical_symbol_ticker_candle(
                    period_start, period_end, interval):
                exchange.strategy.set_price(price)
                exchange.strategy.run()

        execution_time = datetime.now() - self.launchedAt
        print('Execution time: ' + str(execution_time.total_seconds()) +
              ' seconds')
        sys.exit(0)
示例#20
0
class Vehicle:
    def __init__(self,
                 license_plate,
                 make,
                 model,
                 year,
                 type_of_vehicle,
                 seats,
                 fuel,
                 transmission,
                 dates=[]):
        self.__price_list = Price()
        self.__license = license_plate
        self.__make = make
        self.__model = model
        self.__year = year
        self.__type_of_vehicle = type_of_vehicle
        self.__seats = seats
        self.__fuel = fuel
        self.__transmission = transmission
        self.__rent_dates = dates
        self.__rented_dates = []
        self.__price_per_day = self.__price_list.get_price(type_of_vehicle)
        self.__insurance_per_day = self.__price_list.get_insurance(
            type_of_vehicle)
        self.set_rented_dates()

    def set_rented_dates(self):
        """converts all dates in rent_dates to date instances and saves
        them to rented_dates.
        """
        try:
            for d in self.__rent_dates:
                rent_day = date(int(d[:4]), int(d[4:6]), int(d[6:]))
                self.__rented_dates.append(rent_day)
        except ValueError:
            pass

    def get_rented_dates(self):
        return self.__rented_dates

    def __str__(self):
        return "{} | {}".format(self.__license, self.__make)

    def availability_string(self):
        return "{:<20} {:<20} {:<20} {:<20}".format(self.__license,
                                                    self.__make, self.__model,
                                                    self.__seats)

    def get_license(self):
        return self.__license

    def get_make(self):
        return self.__make

    def get_model(self):
        return self.__model

    def get_vehicle_type(self):
        return self.__type_of_vehicle

    def get_seats(self):
        return self.__seats

    def get_price_per_day(self):
        return self.__price_per_day

    def get_insurance_per_day(self):
        return self.__insurance_per_day

    def get_attributes(self):
        return (self.__license, self.__make, self.__model, self.__year,
                self.__type_of_vehicle, self.__seats, self.__fuel,
                self.__transmission)

    def return_details(self):
        """Returns vehicle details in a dictionary"""
        return {
            "Vehicle type": self.__type_of_vehicle,
            "Make": self.__make,
            "Model": self.__model,
            "Year": self.__year,
            "Number of seats": self.__seats,
            "License": self.__license,
            "Fuel": self.__fuel,
            "Driving transmission": self.__transmission,
        }
    def GetContext(self):
        tContext = {}

        typeOfGold = self.GOLDTYPE

        tCurrentPrice = Price()
        tPriceQuery = Price().all()
        tPriceQuery.order("-priceDateCreated")
        tPriceQuery.filter("priceType", typeOfGold)
        tCurrentPrice = tPriceQuery.fetch(limit=1)[0]

        tPriceDictionary = _data.PriceContainer.GetBasePriceDictionary()

        typeOfGold = self.GOLDTYPE
        if typeOfGold is "regular":
            tCurrentPrice.priceType = "regular"
            tContext["post_location"] = "/price"
        elif typeOfGold is "07":
            tCurrentPrice.priceType = "07"
            tContext["post_location"] = "/price07"

        tSortedProperties = sorted(tCurrentPrice.properties().keys())
        for tCurrentProperty in tSortedProperties:
            try:
                tMatches = re.match(r"price(?P<number>[0-9]{4}m)", str(tCurrentProperty))
                tMatchedKey = str(tMatches.group("number"))

                tPriceDictionary[tMatchedKey] = tCurrentPrice.__getattribute__(tCurrentProperty)
            except:
                logging.debug("Could not find a key in: " + str(tCurrentProperty))

        tPriceList = []
        tSortedPriceKeys = sorted(tPriceDictionary.keys())

        for tCurrentKey in tSortedPriceKeys:
            if tCurrentKey[:3] == "000":
                tKey = tCurrentKey[3:]
            elif tCurrentKey[:2] == "00":
                tKey = tCurrentKey[2:]
            elif tCurrentKey[0] == "0":
                tKey = tCurrentKey[1:]
            else:
                tKey = tCurrentKey

            tTuple = (tKey, tPriceDictionary[tCurrentKey])
            tPriceList.append(tTuple)

        # logging.debug(tPriceList)
        tContext["prices"] = tPriceList

        return tContext
    def PostContext(self):
        tContext = {}

        tPriceDictionary = _data.PriceContainer.GetBasePriceDictionaryWithoutZeros()

        tPriceList = []
        tSortedPriceKeys = sorted(tPriceDictionary.keys())

        for tCurrentKey in tSortedPriceKeys:
            if len(tCurrentKey) == 2:
                tKey = "000" + tCurrentKey
            elif len(tCurrentKey) == 3:
                tKey = "00" + tCurrentKey
            elif len(tCurrentKey) == 4:
                tKey = "0" + tCurrentKey
            else:
                tKey = tCurrentKey
            # logging.debug('tCurrentKey ' + tCurrentKey)
            tTuple = (tKey, self.request.get(tCurrentKey))
            tPriceList.append(tTuple)
        # logging.debug('Price List construction complete')

        tCurrentPrice = Price()

        typeOfGold = self.GOLDTYPE
        if typeOfGold is "regular":
            tCurrentPrice.priceType = "regular"
            self.LOCATION = "/price"
            tContext["post_location"] = "/price"
        elif typeOfGold is "07":
            tCurrentPrice.priceType = "07"
            self.LOCATION = "/price07"
            tContext["post_location"] = "/price07"

        # logging.debug(tPriceList)
        for tVolume, tNewPrice in tPriceList:
            # logging.debug("tVolume " + tVolume)
            # logging.debug("tNewPrice " + tNewPrice)
            tPropertyName = "price" + tVolume
            if tPropertyName in tCurrentPrice.properties().keys():
                try:
                    tCurrentPrice.__setattr__(tPropertyName, float(tNewPrice))
                except:
                    tCurrentPrice.__setattr__(tPropertyName, tNewPrice)

        # logging.debug("New price object constructed")
        # for tProperty in tCurrentPrice.properties().keys():
        #    logging.debug("Property " + tProperty + " is " + str(tCurrentPrice.properties()[tProperty]))

        tCurrentPrice.priceCreator = str(self.GetUser().email())

        # typeOfGold = self.request.get('goldtype')

        tCurrentPrice.put()

        self.REDIRECT = True

        return tContext
    def PostContext(self):
        tContext = {}

        tPriceDictionary = _data.PriceContainer.GetBasePriceDictionaryWithoutZeros(
        )

        tPriceList = []
        tSortedPriceKeys = sorted(tPriceDictionary.keys())

        for tCurrentKey in tSortedPriceKeys:
            if (len(tCurrentKey) == 2):
                tKey = "000" + tCurrentKey
            elif (len(tCurrentKey) == 3):
                tKey = "00" + tCurrentKey
            elif (len(tCurrentKey) == 4):
                tKey = "0" + tCurrentKey
            else:
                tKey = tCurrentKey
            #logging.debug('tCurrentKey ' + tCurrentKey)
            tTuple = (tKey, self.request.get(tCurrentKey))
            tPriceList.append(tTuple)
        #logging.debug('Price List construction complete')

        tCurrentPrice = Price()

        typeOfGold = self.GOLDTYPE
        if typeOfGold is 'regular':
            tCurrentPrice.priceType = 'regular'
            self.LOCATION = '/price'
            tContext['post_location'] = '/price'
        elif typeOfGold is '07':
            tCurrentPrice.priceType = '07'
            self.LOCATION = '/price07'
            tContext['post_location'] = '/price07'

        #logging.debug(tPriceList)
        for tVolume, tNewPrice in tPriceList:
            #logging.debug("tVolume " + tVolume)
            #logging.debug("tNewPrice " + tNewPrice)
            tPropertyName = "price" + tVolume
            if tPropertyName in tCurrentPrice.properties().keys():
                try:
                    tCurrentPrice.__setattr__(tPropertyName, float(tNewPrice))
                except:
                    tCurrentPrice.__setattr__(tPropertyName, tNewPrice)

        #logging.debug("New price object constructed")
        #for tProperty in tCurrentPrice.properties().keys():
        #    logging.debug("Property " + tProperty + " is " + str(tCurrentPrice.properties()[tProperty]))

        tCurrentPrice.priceCreator = str(self.GetUser().email())

        #typeOfGold = self.request.get('goldtype')

        tCurrentPrice.put()

        self.REDIRECT = True

        return tContext
    def GetContext(self):
        tContext = {}

        typeOfGold = self.GOLDTYPE

        tCurrentPrice = Price()
        tPriceQuery = Price().all()
        tPriceQuery.order("-priceDateCreated")
        tPriceQuery.filter("priceType", typeOfGold)
        tCurrentPrice = tPriceQuery.fetch(limit=1)[0]

        tPriceDictionary = _data.PriceContainer.GetBasePriceDictionary()

        typeOfGold = self.GOLDTYPE
        if typeOfGold is 'regular':
            tCurrentPrice.priceType = 'regular'
            tContext['post_location'] = '/price'
        elif typeOfGold is '07':
            tCurrentPrice.priceType = '07'
            tContext['post_location'] = '/price07'

        tSortedProperties = sorted(tCurrentPrice.properties().keys())
        for tCurrentProperty in tSortedProperties:
            try:
                tMatches = re.match(r'price(?P<number>[0-9]{4}m)',
                                    str(tCurrentProperty))
                tMatchedKey = str(tMatches.group('number'))

                tPriceDictionary[tMatchedKey] = tCurrentPrice.__getattribute__(
                    tCurrentProperty)
            except:
                logging.debug('Could not find a key in: ' +
                              str(tCurrentProperty))

        tPriceList = []
        tSortedPriceKeys = sorted(tPriceDictionary.keys())

        for tCurrentKey in tSortedPriceKeys:
            if (tCurrentKey[:3] == '000'):
                tKey = tCurrentKey[3:]
            elif (tCurrentKey[:2] == '00'):
                tKey = tCurrentKey[2:]
            elif (tCurrentKey[0] == '0'):
                tKey = tCurrentKey[1:]
            else:
                tKey = tCurrentKey

            tTuple = (tKey, tPriceDictionary[tCurrentKey])
            tPriceList.append(tTuple)

        #logging.debug(tPriceList)
        tContext['prices'] = tPriceList

        return tContext
示例#25
0
    def create_or_update(cls, good_model, data):
        """
        Создаем либо обновляем цену в товаре.

        Для начала нам нужно найти цену в системе по номенклатуре и цене с НДС(по сути из цены с НДС и складывается
        конечная стоимость продажи).

        Есть момент, что цен прихода может быть несколько. А вот цена продажи у них все равно единая.

        В случае отсутствия цены по условию выше, создаем новую цену со всеми переданными параметрами.

        Если находим, то корректируем у цены НДС, цены розницы и опта и дату действия цены.

        :argument good_model - инстанс Good
        :argument data - инстанс DataToUpdatePrice.

        :return инстанс Price

        """
        invoice = data.invoice
        if not data.price_retail and not data.price_gross:
            raise PriceArgumentExc(u"Нету розничной и оптовой цены")
        try:
            price, _ = cls.get_price_priceparish(
                commodity_id=data.id_commodity, price_post=data.price_post, number_local=data.number_local,
                number_global=data.number_global, date=invoice.date)
        except NotFindPriceExc:
            """
            Если не найдено цен вообще на номенклатуру, то создаем и цену прихода, и цену продажи.
            """
            price = Price(price_retail=data.price_retail, price_gross=data.price_gross)
            priceparish = PriceParish(commodity_id=data.id_commodity, number_local_from=data.number_local,
                                      number_global_from=data.number_global, NDS=data.NDS, price_prev=data.price_prev,
                                      price_post=data.price_post, date_from=invoice.date)
            priceparish.invoice = invoice
            priceparish.price = price
            db.session.add(price)
            db.session.add(priceparish)
            good_model.price = price
            db.session.add(good_model)

        except NotFindPriceParishExc as exc:
            """
            Если не найдена цена прихода с "ценой с НДС", надо найти в системе, есть ли цены продажи с указанными
            розничными и оптовыми ценами, и если такое есть, надо добавить новую цену прихода
            """
            price = cls.get_final_price_to_commodity_numbers_date(
                data.id_commodity, data.price_retail, data.price_gross, data.number_local, data.number_global,
                invoice.date)

            if not price:
                price = Price(price_retail=data.price_retail, price_gross=data.price_gross)
                db.session.add(price)

            priceparish = PriceParish(
                commodity_id=data.id_commodity, number_local_from=data.number_local,
                number_global_from=data.number_global, NDS=data.NDS, price_prev=data.price_prev,
                price_post=data.price_post, date_from=invoice.date)
            priceparish.invoice = invoice
            priceparish.price = price
            db.session.add(priceparish)
            good_model.price = price
            db.session.add(good_model)
        else:
            """
            иначе нашли цену и изменим ее
            """
            good_model.price = price
            price.price_retail = data.price_retail
            price.price_gross = data.price_gross

            db.session.add(good_model)
            db.session.add(price)
        return price
示例#26
0
        period_start, period_end, interval))

    # Try to find dataset
    dataset = Dataset().query(
        'get', {
            "exchange": '/api/exchanges/' + exchange.name.lower(),
            "currency": '/api/currencies/' + currency.lower(),
            "asset": '/api/currencies/' + asset.lower(),
            "period_start": period_start,
            "period_end": period_end,
            "candleSize": interval
        })

    if dataset and len(dataset) > 0:
        print(dataset[0])
        price = Price()
        for price in price.query('get', {"dataset": dataset[0]['uuid']}):
            newPrice = Price()
            newPrice.populate(price)
            exchange.strategy.set_price(newPrice)
            exchange.strategy.run()
    else:
        print("Dataset not found, external API call to " + exchange.name)
        for price in exchange.historical_symbol_ticker_candle(
                period_start, period_end, interval):
            exchange.strategy.set_price(price)
            exchange.strategy.run()

    sys.exit()

elif mode == 'import':