本文整理汇总了Python中sqlalchemy.func.now函数的典型用法代码示例。如果您正苦于以下问题:Python now函数的具体用法?Python now怎么用?Python now使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了now函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: modified
def modified(self):
"""
Modification Timestamp
"""
from .types.date import DateTime
return DateTime(server_default=func.now(), server_onupdate=func.now(), info=dict(readonly=True))
开发者ID:MartinMartimeo,项目名称:avalon,代码行数:7,代码来源:__init__.py
示例2: get_delay
def get_delay(self, update):
"""Return the minutes to delay the viewing of submission results.
Only store information into the datebase when `update` is set.
"""
if hasattr(self, '_delay'):
return self._delay
now = datetime.now(UTC())
zero = timedelta(0)
delay = self.project.delay - (now - self.created_at)
if delay <= zero: # Never delay longer than the project's delay time
self._delay = None
elif self.group.viewed_at is None: # Don't delay
if update:
self.group.viewed_at = func.now()
self._delay = None
elif self.created_at <= self.group.viewed_at: # Show older results
self._delay = None
else:
pv_delay = self.project.delay - (now - self.group.viewed_at)
if pv_delay <= zero:
if update: # Update the counter
self.group.viewed_at = func.now()
self._delay = None
else:
self._delay = min(delay, pv_delay).total_seconds() / 60
return self._delay
开发者ID:ucsb-cs,项目名称:submit,代码行数:29,代码来源:models.py
示例3: _db_update
def _db_update(self, ok, msg):
db = self._db_manager.get_db()
try:
while True:
try:
if ok:
if msg['message_name'] == 'ExecScript':
db.messages.filter(
db.messages.messageid == msg['messageid']).delete()
else:
db.messages.filter(db.messages.messageid == msg['messageid']).update({
'status': 1,
'message': '',
'dtlasthandleattempt': func.now()},
synchronize_session=False)
if msg['event_id']:
db.events.filter(db.events.event_id == msg['event_id']).update({
db.events.msg_sent: db.events.msg_sent + 1})
else:
db.messages.filter(db.messages.messageid == msg['messageid']).update({
'status': 0 if msg['handle_attempts'] < 2 else 3,
'handle_attempts': msg['handle_attempts'] + 1,
'dtlasthandleattempt': func.now()},
synchronize_session=False)
db.session.commit()
break
except db_exc.SQLAlchemyError:
db.session.remove()
LOG.error(helper.exc_info())
time.sleep(5)
finally:
db.session.remove()
开发者ID:AnyBucket,项目名称:scalr,代码行数:32,代码来源:messaging.py
示例4: advance
def advance(session, group_id, station_id):
state = GroupStation.get(group_id, station_id)
# The first state to set - if there is nothing yet - is "ARRIVED"
if not state:
group = Group.one(id=group_id)
station = Station.one(id=station_id)
state = GroupStation(group_id, station_id)
state.state = STATE_ARRIVED
session.add(state)
return STATE_ARRIVED
group = state.group
station = state.station
if state.state == STATE_UNKNOWN:
state.state = STATE_ARRIVED
elif state.state == STATE_ARRIVED:
if not group.departure_time and station.is_start:
group.departure_time = func.now()
if not group.finish_time and station.is_end:
group.finish_time = func.now()
group.completed = True
state.state = STATE_FINISHED
elif state.state == STATE_FINISHED:
state.state = STATE_UNKNOWN
else:
raise ValueError('%r is not a valid state!' % state.state)
return state.state
开发者ID:exhuma,项目名称:lost-tracker,代码行数:30,代码来源:models.py
示例5: set_group_state
def set_group_state(session, group_id, station_id, new_state):
"""
Updates the group state for a given station
"""
station = session.query(Station).filter_by(id=station_id).first()
if not station:
LOG.debug('No station found with ID %r', station_id)
return False
group = session.query(Group).filter_by(id=group_id).first()
if not group:
LOG.debug('No group found with ID %r', group_id)
return False
if new_state == STATE_FINISHED:
if not group.departure_time and station.is_start:
group.departure_time = func.now()
if not group.finish_time and station.is_end:
group.finish_time = func.now()
group.completed = True
state = GroupStation(
group_id=group_id,
station_id=station_id,
state=new_state)
state = session.merge(state)
session.flush()
return state
开发者ID:exhuma,项目名称:lost-tracker,代码行数:28,代码来源:core.py
示例6: group
def group(self, group, current=None):
# Filter by group
sub_query = db.session.query(GroupPatient)
sub_query = sub_query.filter(GroupPatient.group == group, GroupPatient.patient_id == Patient.id)
if current is not None:
if current:
# Between from and to date
sub_query = sub_query.filter(
GroupPatient.from_date <= func.now(),
or_(
GroupPatient.to_date == null(),
GroupPatient.to_date >= func.now(),
)
)
else:
# Outside from or to date
sub_query = sub_query.filter(or_(
GroupPatient.from_date > func.now(),
and_(
GroupPatient.to_date != null(),
GroupPatient.to_date < func.now()
)
))
self.query = self.query.filter(sub_query.exists())
return self
开发者ID:renalreg,项目名称:radar,代码行数:28,代码来源:patient_search.py
示例7: run
def run(self):
import time
from v2ex.service.fetcher_manager import FetcherManager
while not self._stop_flag:
time.sleep(1)
nid = FetcherManager.get_task()
ntf_token = NtfTokenDao.get_from_nid(nid)
if ntf_token is None:
FetcherManager.remove_task(nid)
continue
if self.should_check_update(ntf_token):
if self.has_update(ntf_token):
logging.debug("found update for %s", ntf_token.token)
self.gcm_send(ntf_token.uid, gcm.send_notify)
else:
logging.debug("not found update for %s", ntf_token.token)
ntf_token.last_fetch_time = func.now()
db.get_session().commit()
elif self.should_ping(ntf_token):
self.gcm_send(ntf_token.uid, gcm.send_ping)
ntf_token.last_ping_time = func.now()
db.get_session().commit()
开发者ID:CzBiX,项目名称:v2ex-server,代码行数:26,代码来源:fetcher.py
示例8: upgrade
def upgrade(migrate_engine):
metadata.bind = migrate_engine
instance_table = Table(
"instance",
metadata,
Column("id", Integer, primary_key=True),
Column("key", Unicode(20), nullable=False, unique=True),
Column("label", Unicode(255), nullable=False),
Column("description", UnicodeText(), nullable=True),
Column("required_majority", Float, nullable=False),
Column("activation_delay", Integer, nullable=False),
Column("create_time", DateTime, default=func.now()),
Column("access_time", DateTime, default=func.now(), onupdate=func.now()),
Column("delete_time", DateTime, nullable=True),
Column("creator_id", Integer, ForeignKey("user.id"), nullable=False),
Column("default_group_id", Integer, ForeignKey("group.id"), nullable=True),
Column("allow_adopt", Boolean, default=True),
Column("allow_delegate", Boolean, default=True),
Column("allow_propose", Boolean, default=True),
Column("allow_index", Boolean, default=True),
Column("hidden", Boolean, default=False),
Column("locale", Unicode(7), nullable=True),
Column("css", UnicodeText(), nullable=True),
Column("frozen", Boolean, default=False),
Column("milestones", Boolean, default=False),
Column("use_norms", Boolean, nullable=True, default=True),
Column("require_selection", Boolean, nullable=True, default=False),
Column("is_authenticated", Boolean, nullable=True, default=False),
)
hide_categories = Column("hide_global_categories", Boolean, nullable=True, default=False)
hide_categories.create(instance_table)
u = instance_table.update(values={"hide_global_categories": False})
migrate_engine.execute(u)
开发者ID:vigri,项目名称:adhocracy,代码行数:34,代码来源:042_instance_hide_global_categories.py
示例9: _recover_delete_revisions
def _recover_delete_revisions(revisions_table, event,
last_available_revision_ids):
"""Log an action="deleted" copy for revisions with ids in passed list."""
if not last_available_revision_ids:
return
columns_to_clone = sorted(set(c.name for c in revisions_table.c) -
{"id", "event_id", "action", "created_at",
"updated_at"})
db.session.execute(
revisions_table.insert().from_select(
["event_id",
"action",
"created_at",
"updated_at"] + columns_to_clone,
select(
[event.id,
literal("deleted"),
func.now(),
func.now()] + columns_to_clone,
).select_from(
revisions_table,
).where(
revisions_table.c.id.in_(last_available_revision_ids),
),
),
)
开发者ID:Smotko,项目名称:ggrc-core,代码行数:26,代码来源:revisions.py
示例10: whereInEquipement
def whereInEquipement(self,fullQueryJoin,criteria):
sensorObj = list(filter(lambda x:'FK_Sensor'==x['Column'], criteria))[0]
sensor = sensorObj['Value']
table = Base.metadata.tables['MonitoredSiteEquipment']
joinTable = outerjoin(table,Sensor, table.c['FK_Sensor'] == Sensor.ID)
if sensorObj['Operator'].lower() in ['is','is not'] and sensorObj['Value'].lower() == 'null':
subSelect = select([table.c['FK_MonitoredSite']]
).select_from(joinTable).where(
and_(MonitoredSite.ID== table.c['FK_MonitoredSite']
,or_(table.c['EndDate'] >= func.now(),table.c['EndDate'] == None)
))
if sensorObj['Operator'].lower() == 'is':
fullQueryJoin = fullQueryJoin.where(~exists(subSelect))
else :
fullQueryJoin = fullQueryJoin.where(exists(subSelect))
else :
subSelect = select([table.c['FK_MonitoredSite']]
).select_from(joinTable).where(
and_(MonitoredSite.ID== table.c['FK_MonitoredSite']
,and_(eval_.eval_binary_expr(Sensor.UnicIdentifier,sensorObj['Operator'],sensor)
,or_(table.c['EndDate'] >= func.now(),table.c['EndDate'] == None))
))
fullQueryJoin = fullQueryJoin.where(exists(subSelect))
return fullQueryJoin
开发者ID:FredericBerton,项目名称:ecoReleve-Data,代码行数:26,代码来源:List.py
示例11: get_dag_duration_info
def get_dag_duration_info():
'''get duration of currently running DagRuns
:return dag_info
'''
driver = Session.bind.driver
durations = {
'pysqlite': func.sum(
(func.julianday(func.current_timestamp()) - func.julianday(DagRun.start_date)) * 86400.0
),
'mysqldb': func.sum(func.timestampdiff(text('second'), DagRun.start_date, func.now())),
'default': func.sum(func.now() - DagRun.start_date)
}
duration = durations.get(driver, durations['default'])
with session_scope(Session) as session:
return session.query(
DagRun.dag_id,
DagRun.run_id,
duration.label('duration')
).group_by(
DagRun.dag_id,
DagRun.run_id
).filter(
DagRun.state == State.RUNNING
).all()
开发者ID:slash-cyberpunk,项目名称:airflow-exporter,代码行数:25,代码来源:prometheus_exporter.py
示例12: active_duration_range
def active_duration_range(query, minimum_active_duration,
maximum_active_duration):
if minimum_active_duration is not None:
minimum_active_duration = datetime.timedelta(
seconds=minimum_active_duration)
finished_claims = query.filter(
models.Claim.activated != None,
models.Claim.deactivated != None,
models.Claim.deactivated - models.Claim.activated
>= minimum_active_duration)
active_claims = query.filter(
models.Claim.activated != None,
models.Claim.deactivated == None,
func.now() - models.Claim.activated
>= minimum_active_duration)
query = finished_claims.union(active_claims)
if maximum_active_duration is not None:
maximum_active_duration = datetime.timedelta(
seconds=maximum_active_duration)
finished_claims = query.filter(
models.Claim.activated != None,
models.Claim.deactivated != None,
models.Claim.deactivated - models.Claim.activated
<= maximum_active_duration)
active_claims = query.filter(
models.Claim.activated != None,
models.Claim.deactivated == None,
func.now() - models.Claim.activated
<= maximum_active_duration)
query = finished_claims.union(active_claims)
return query
开发者ID:genome,项目名称:nessy-server,代码行数:33,代码来源:filters.py
示例13: upgrade
def upgrade(migrate_engine):
meta.bind = migrate_engine
instance_table = Table('instance', meta,
Column('id', Integer, primary_key=True),
Column('key', Unicode(20), nullable=False, unique=True),
Column('label', Unicode(255), nullable=False),
Column('description', UnicodeText(), nullable=True),
Column('required_majority', Float, nullable=False),
Column('activation_delay', Integer, nullable=False),
Column('create_time', DateTime, default=func.now()),
Column('access_time', DateTime, default=func.now(), onupdate=func.now()),
Column('delete_time', DateTime, nullable=True),
Column('creator_id', Integer, ForeignKey('user.id'), nullable=False),
Column('default_group_id', Integer, ForeignKey('group.id'), nullable=True),
Column('allow_adopt', Boolean, default=True),
Column('allow_delegate', Boolean, default=True),
Column('allow_index', Boolean, default=True),
Column('hidden', Boolean, default=False),
Column('locale', Unicode(7), nullable=True),
Column('css', UnicodeText(), nullable=True),
Column('use_norms', Boolean, nullable=True, default=True)
)
propose = Column('allow_propose', Boolean, default=True)
propose.create(instance_table)
u = instance_table.update(values={'allow_propose': True})
migrate_engine.execute(u)
开发者ID:AnonOnWarpath,项目名称:adhocracy,代码行数:27,代码来源:025_instance_gets_norm_propose_option.py
示例14: send_profile_visitor_email
def send_profile_visitor_email(**kwargs):
template = email_template_env.get_template('profile_visitors.html')
senders = AccountUser.query.filter(
extract('dow', AccountUser.date_added) == extract('dow', func.now()),
extract('hour', AccountUser.date_added) == extract('hour', func.now()),
).join(
AccountUserVisit,
(AccountUserVisit.profile_user_id == AccountUser.id) &
(AccountUserVisit.notified == False)
)
for sender in senders:
visitors = AccountUserVisit.get_all_visits_in_last_7_days(sender, 5)
visitors = [AccountUserVisit.visit_item(*v) for v in visitors.all()]
if visitors:
body = template.render(
sender=sender,
visitors=visitors,
**kwargs
)
send_email(sender.username, body)
try:
db.session.query(AccountUserVisit).filter_by(profile_user_id=sender.id).update({"notified": True})
db.session.commit()
except:
db.session.rollback()
raise
开发者ID:philpill,项目名称:romeo,代码行数:29,代码来源:commands.py
示例15: __init__
def __init__(self, master, id_num):
session = Session()
frame = Frame(master)
frame.pack()
member = session.query(Member).filter_by(mid=id_num).first()
topline = "%s\n[%s]" % (member.name, str(id_num))
nameline = Label(frame, text=topline, bg="black", fg="white", font="Monospace 30")
nameline.pack(fill=X)
lastLog = session.query(CheckIn).filter_by(mid=id_num).filter_by(timeOut=None)
if lastLog.count() == 0:
statusline = Label(frame, text="CHECKED IN", bg="black", fg="green", font="Monospace 30")
statusline.pack(fill=X)
newLog = CheckIn(mid=id_num, timeIn=func.now(), timeOut=None)
session.add(newLog)
else:
lastLog = lastLog.first()
statusline = Label(frame, text="CHECKED OUT", bg="black", fg="red", font="Monospace 30")
statusline.pack(fill=X)
lastLog.timeOut = func.now()
if os.path.isfile("images/%s.png" % str(id_num).replace("'", '')):
img = PIL.Image.open("images/%s.png" % str(id_num).replace("'", ''))
photo = PIL.ImageTk.PhotoImage(img)
picture = Label(frame, image=photo)
picture.image = photo
picture.pack()
session.commit()
session.close()
开发者ID:illinoistechrobotics,项目名称:frontdoor,代码行数:34,代码来源:gui.py
示例16: __init__
def __init__(self):
self.create_date =func.now()
self.write_date = func.now()
self.write_uid = 1
obj_conexion = configuracion()
engine=create_engine(obj_conexion.config())
Session= sessionmaker(bind=engine)
self.session=Session()
开发者ID:lriccombene,项目名称:Slam_Sistema_creditos,代码行数:8,代码来源:E_party_party.py
示例17: timestamp_mixin
def timestamp_mixin(cls):
"""
Model column: timestamp mixin decorator.
"""
cls.created_at = Column(DateTime, default=func.now(), nullable=False)
cls.updated_at = Column(DateTime, default=func.now(), onupdate=func.now(), nullable=False)
return cls
开发者ID:main1015,项目名称:co-work,代码行数:8,代码来源:__init__.py
示例18: active_filter
def active_filter(columns):
if not is_nonstr_iter(columns):
columns = [columns]
and_queries = []
for column in columns:
and_queries.append(or_(column.start_date <= func.now(), column.start_date.is_(None)))
and_queries.append(or_(column.end_date > func.now(), column.end_date.is_(None)))
return and_(*and_queries)
开发者ID:hjalves,项目名称:ines,代码行数:9,代码来源:sql.py
示例19: _perform_sql
def _perform_sql(self):
filter = {}
filter["last_check"] = "now()"
query = self.session.query(self.tables.monitor_obs)\
.add_column((func.datediff(self.tables.monitor_obs.last_check, func.now())).label("test"))\
.filter(self.tables.monitor_obs.locked == False)\
.filter(func.datediff(self.tables.monitor_obs.last_check, func.now()) <= self.tables.monitor_obs.frequency) \
.order_by('last_check')
logger.debug(query)
开发者ID:sfister,项目名称:Projects,代码行数:10,代码来源:Test.py
示例20: test_generic_now
def test_generic_now(self):
assert isinstance(func.now().type, sqltypes.DateTime)
for ret, dialect in [
('CURRENT_TIMESTAMP', sqlite.dialect()),
('now()', postgresql.dialect()),
('now()', mysql.dialect()),
('CURRENT_TIMESTAMP', oracle.dialect())
]:
self.assert_compile(func.now(), ret, dialect=dialect)
开发者ID:cpcloud,项目名称:sqlalchemy,代码行数:10,代码来源:test_functions.py
注:本文中的sqlalchemy.func.now函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论