def publish_date(self): datestamp = self.frontmatter.get('publish_date') if not datestamp: match = re.match(DATE_RE, self.is_dir and self.dir_name or self.file_name) datestamp = match and match.group('date') or None if datestamp: datestamp = parse_datetime(datestamp) return datestamp and datestamp.astimezone(pytz.UTC) or utcnow()
def maybe_convert_values(self, model_class, data): ret = data.copy() for col_name, value in data.items(): col = getattr(model_class, col_name) if isinstance(col, AssociationProxy) or col.impl.uses_objects: ret[col_name] = self.convert_identifiers(value) elif not hasattr(col, 'type'): continue elif isinstance(col.type, Date): if value in ('today', 'now', 'utcnow'): ret[col_name] = utcnow().date else: ret[col_name] = parse_datetime(value).date elif isinstance(col.type, DateTime): if value in ('now', 'utcnow'): ret[col_name] = utcnow() elif not isinstance(value, datetime.datetime): ret[col_name] = parse_datetime(value) return ret
def fixtures(file, reset): """Load database fixtures from JSON.""" import json from backend.extensions import db if reset: _reset_db() # sqlalchemy and postgres sequences don't play so nice together when ids are # explicitly set. so we need to modify the sequence start-point ourselves is_postgres = current_app.config.get('SQLALCHEMY_DATABASE_URI', '').startswith('postgres') sequences = [] if is_postgres: sequences = [ row[0] for row in db.session.execute(""" SELECT relname FROM pg_class WHERE relkind = 'S' """) ] click.echo('Loading fixtures.') for fixture in json.load(file): model = current_app.models[fixture['model']] for model_kwargs in fixture['items']: d = {} for k, v in model_kwargs.items(): # FIXME is this too heavy-handed of an approach? (will it ever # create a date when it wasn't supposed to?) maybe better to # somehow declare explicit date fields in the fixtures file try: d[k] = parse_datetime(v) except: d[k] = v model.create(**d) count = len(fixture['items']) suffix = 's' if count > 1 else '' click.echo(f"Adding {count} {fixture['model']} record{suffix}.") if is_postgres: seq_name = f'{model.__tablename__}_id_seq' if seq_name in sequences: db.session.execute( f'ALTER SEQUENCE {seq_name} RESTART WITH :count', {'count': count + 1}) db.session.commit() click.echo('Done.')