class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False) date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) content = db.Column(db.Text, nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) respostas = db.relationship('Resposta', backref='post', lazy=True) scores = db.relationship('Scores', backref='scores', lazy=True) total_score = db.Column(db.Integer, default=0) def __repr__(self): return f"Post('{self.title}', '{self.date_posted}')"
class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) image_file = db.Column(db.String(20), nullable=False, default='default.jpg') password = db.Column(db.String(60), nullable=False) posts = db.relationship('Post', backref='author', lazy=True) respostas = db.relationship('Resposta', backref='responser', lazy=True) scores = db.relationship('Scores', backref='scorer', lazy=True) user_type = db.Column(db.String(1), nullable=False, default="U") def __repr__(self): return f"User('{self.username}', '{self.email}', '{self.image_file}')"
class User(db.Model, UserMixin): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) profile_image = db.Column(db.String(64), nullable=False, default='default_profile.png') email = db.Column(db.String(64), unique=True, index=True) registered_on = db.Column(db.DateTime, nullable=False) username = db.Column(db.String(64), unique=True, index=True) password_hash = db.Column(db.String(128)) is_active = db.Column(db.Boolean, nullable=False, default=False) posts = db.relationship('BlogPost', backref='author', lazy=True) def __init__(self, email, username, password, is_active): self.email = email self.registered_on = datetime.now() self.username = username self.password_hash = generate_password_hash(password) self.is_active = is_active def check_password(self, password): return check_password_hash(self.password_hash, password)
class Product(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(20)) description = db.Column(db.String(120)) img = db.relationship('Product_img', backref='product', lazy=True) register_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow()) def __repr__(self): return f"User('{self.id}','{self.title}','{self.description}','{self.img}','{self.register_date}'"
class BlogPost(db.Model): users = db.relationship(User) id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) title = db.Column(db.String(140), nullable=False) text = db.Column(db.Text, nullable=False) def __init__(self, title, text, user_id): self.title = title self.text = text self.user_id = user_id
class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), index=True) email = db.Column(db.String(100), index=True) password = db.Column(db.String(20)) avatar = db.Column(db.String(20), default='default.jpg') zvonki = db.relationship('Zvonok', backref='author', lazy='dynamic') def __repr__(self): return f'Пользователь: {self.username}, email {self.email}' def set_password(self, password): self.password = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.password, password)
class Product(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(32, collation='NOCASE')) slug = db.Column(db.String(140, collation='NOCASE'), unique=True) discription = db.Column(db.Text) created = db.Column(db.DateTime, default=datetime.utcnow()) img = db.Column(db.String(20), nullable=False, default='default_product.jpg') tags = db.relationship('Tag', secondary='product_tags', backref=db.backref('products', lazy='dynamic')) def __init__(self, *args, **kwargs): super(Product, self).__init__(*args, **kwargs) self.generate_slug() def generate_slug(self): if self.title: self.slug = slugify(self.title) def __repr__(self): return f"Product('{self.title}','{self.created}','{self.discription}')"
class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(20), nullable=False) email = db.Column(db.String(50), nullable=False) password = db.Column(db.String(20), nullable=False) p_img = db.Column(db.String(8), nullable=False, default="3zma.jpg") posts = db.relationship("Post", backref='author', lazy=True) def rest(self, sec=1800): s = srial(app.config['SECRET_KEY'], sec) return s.dumps({'user_id': self.id}).decode("utf-8") @staticmethod def verify(token): s = srial(app.config['SECRET_KEY']) try: user_id = s.loads(token)['user_id'] except: return None return User.query.get(user_id)
def user(cls): return db.relationship('User')
class VanguardFund(db.Model): __tablename__ = 'vanguard_funds' id = db.Column(db.Integer, primary_key=True) fund_type = db.Column(db.String(64), nullable=False) name = db.Column(db.String(64), nullable=False) ticker = db.Column(db.String(64), nullable=False) asset_class = db.Column(db.String(64), nullable=False) exp_ratio = db.Column(db.Float, nullable=False) category = db.Column(db.String(64), nullable=False) minimum = db.Column(db.Integer, nullable=False) prices = db.relationship('VanguardPrice', backref='fund') dividends = db.relationship('VanguardDividend', backref='fund') fees = db.relationship('VanguardFee', backref='fund') def __init__(self, id, fund_type, name, ticker, asset_class, exp_ratio): self.id = id self.fund_type = fund_type self.name = name self.ticker = ticker self.asset_class = asset_class self.exp_ratio = exp_ratio def __repr__(self): return "<VanguardFund(%d, '%s', '%s')>" % ((self.id or 0), self.name, self.ticker) def json(self): return { 'id': self.id, 'name': self.name, 'fund_type': self.fund_type, 'ticker': self.ticker, 'asset_class': self.asset_class, 'exp_ratio': self.exp_ratio, 'category': self.category, 'minimum': self.minimum, } @property def overview_url(self): return "https://personal.vanguard.com/us/funds/snapshot?FundIntExt=INT&FundId=%04d#tab=0" % self.id def parse_overview(self, driver): logger.info('parse_overview: %s' % self.overview_url) (table,) = _web_lookup( self.overview_url, driver, "//table[@id='fundFactsTable']/tbody", ) logger.info(table) trs = [ x for x in table.find_elements(By.TAG_NAME, 'tr') if len(x.find_elements(By.TAG_NAME, 'td')) > 1 ] self.category = trs[1].find_elements(By.TAG_NAME, 'td')[1].text logger.info('category: %s' % self.category) minimum = trs[3].find_elements(By.TAG_NAME, 'td')[1].text.lower() logger.info('minimum: %s' % self.minimum) self.minimum = minimum if minimum == 'closed' else _to_float(minimum) @property def market_data_url(self): return "https://advisors.vanguard.com/VGApp/iip/site/advisor/investments/price?fundId=%04d" % self.id def parse_market_data(self, http): logger.info('parse_market_data: %s' % self.market_data_url) r = http.urlopen('GET', self.market_data_url) soup = BeautifulSoup(r.data, 'html5lib') prices_table = soup.find(id='priceForm:historicalPricesTable') for row in prices_table.find_all('tr')[1:]: self.add_price([x.text for x in row.find_all('td')]) dividends_table = soup.find(id='priceForm:priceDistributionsTable') trs = dividends_table.find_all('tr') for tr in trs[1:]: self.add_dividend([x.text for x in tr.find_all('td')]) def add_dividend(self, data): try: dividend_type = data[0] price_per_share = _to_float(data[1]) payable_date = datetime.datetime.strptime(data[2], "%m/%d/%Y").date() record_date = datetime.datetime.strptime(data[3], "%m/%d/%Y").date() reinvest_date = datetime.datetime.strptime(data[4], "%m/%d/%Y").date() reinvest_price = _to_float(data[5]) fd = [ fd for fd in self.dividends if fd.payable_date == payable_date and fd.dividend_type == dividend_type ] if fd: fd = fd[0] fd.price_per_share = price_per_share fd.record_date = record_date fd.reinvest_date = reinvest_date fd.reinvest_price = reinvest_price else: fd = VanguardDividend( self, dividend_type, price_per_share, payable_date, record_date, reinvest_date, reinvest_price ) logger.debug(fd) db.session.add(fd) except (ValueError, IndexError): pass def add_price(self, data): try: date = datetime.datetime.strptime(data[0], "%m/%d/%Y").date() price = _to_float(data[1]) fp = [fp for fp in self.prices if fp.date == date] if fp: fp = fp[0] fp.price = price else: fp = VanguardPrice(self, date, price) logger.debug(fp) db.session.add(fp) except (ValueError, IndexError): pass def historical_prices(self, driver, directory): logger.info('historical prices: %s' % self.market_data_url) header, button = _web_lookup( self.market_data_url, driver, "//*[@id='fundHeader']/h1", "//*[@id='priceForm:sinceInceptionLink']" ) button.click() # sometimes file isn't saved in time for os.listdir() time.sleep(.5) _process_file(directory, header, self.add_price) def historical_dividends(self, driver, directory): logger.info('historical dividends: %s' % self.market_data_url) header, startdate, enddate, button = _web_lookup( self.market_data_url, driver, "//*[@id='fundHeader']/h1", "//*[@id='priceForm:distPricesStartDate']", "//*[@id='priceForm:distPricesEndDate']", "//*[@id='priceForm:exportDistributions']", ) mm, dd, yyyy = [int(x) for x in enddate.get_attribute('value').split('/')] startdate.send_keys("%d/%d/%d", mm, dd, yyyy-10) button.click() # sometimes file isn't saved in time for os.listdir() time.sleep(.5) _process_file(directory, header, self.add_dividend)