Exemplo n.º 1
0
 def _updateResources(self):
     query = {'status':self.computer_status,'is_mac': self.is_mac}
     if self.computer_status == 0:
         query['update0'] = functions.now()
     else:
         query['update1'] = functions.now()
     self._simpleQuery(update(schema.computers,schema.computers.c.computername==self.computer_id,values=query))  
Exemplo n.º 2
0
def upgrade(migrate_engine):
    meta.bind = migrate_engine
    col = Column('created', TIMESTAMP, default=now())
    col.create(projects, populate_default=True)
    assert col is projects.c.created
    col = Column('updated', TIMESTAMP, default=now())
    col.create(projects, populate_default=True)
    assert col is projects.c.updated
Exemplo n.º 3
0
def s_titles():
  if request.method == 'POST':
    ablog=blogs(title=request.form['title'], author=app.config['USERNAME'], \
      content=request.form['content'], \
      created_at=now(), updated_at=now())
    DSession.add(ablog)
    DSession.commit()
  blog = DSession.query(blogs).order_by(blogs.title)
  return render_template('s_titles.html', blogs=blog)
Exemplo n.º 4
0
def fx_external_ids(fx_session):
    f = FixtureModule('fx_external_ids')

    f.jane_eyre = Work()
    f.jane_eyre.names.update({
        Name(nameable=f.jane_eyre,
             name='jane eyre',
             locale=Locale.parse('en_US'))
    })

    f.jane_eyre_wikipedia = WikipediaEntity(
        name='http://dbpedia.org/resource/Jane_Eyre',
        revision=606655259,
        label='Jane Eyre',
        country='England',
        last_crawled=now(),
        type='book',
    )

    f.jane_eyre_ex = ExternalId(
        work_id=f.jane_eyre.id,
        work=f.jane_eyre,
        wikipedia_id=f.jane_eyre_wikipedia.name,
        wikipedia=WikipediaEntity,
    )

    return f
Exemplo n.º 5
0
	def updateSession(self, token=None):
		if not token:
			token = self.getTokenIfExists()
		
		if not token:
			return Result({'success': False, 'ecode': 0, 'message': "Invalid Token"})
		
		self.db.update(self.sessions, {'lastupdate': now()}, self.sessions.c.token == token)
		return Result({'success': True})
def upgrade():
    op.create_table(
        'news',
        sa.Column('id', sa.Integer, primary_key=True),
        sa.Column('title', sa.Unicode(512), nullable=False),
        sa.Column('link', sa.Unicode(512)),
        sa.Column(
            'created_at', sa.DateTime(),
            default=functions.now(),
            index=True))
    def present(self, query_time):
        response = super(S3JSONResultPresenter, self).present(query_time)
        connection = S3Connection()
        bucket = connection.get_bucket('results.sentimentron.co.uk')
        key = Key(bucket)
        key.key = 'results/'+str(self.query.id)
        key.set_contents_from_string(response)

        self.query.fulfilled = now()
        self._session.commit()
Exemplo n.º 8
0
    def get(self):
        per_page = int(current_app.config["POSTS_PER_PAGE"])

        page = int(request.args.get("page")) if request.args.get("page") else 1

        query = Post.query.filter(Post.published_at <= now()).order_by(
            desc("published_at")
        )

        return paginated_json_response(query=query, per_page=per_page, page=page)
Exemplo n.º 9
0
class Comment(db.Model):
    __tablename__ = "comments"
    __pushrod_fields__ = ("author", "timestamp", "content")

    id = db.Column(db.Integer, primary_key=True, nullable=False)
    author = db.Column(db.String(80), nullable=False)
    timestamp = db.Column(db.DateTime, nullable=False, default=now())
    content = db.Column(db.Text, nullable=False)

    post_id = db.Column(db.Integer, db.ForeignKey(Post.id), nullable=False)
    post = db.relationship(Post, backref='comments')
Exemplo n.º 10
0
class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    author_id = db.Column(db.Integer, db.ForeignKey("user.id"))
    title = db.Column(db.String(500), nullable=False)
    body = db.Column(db.Text, nullable=False)
    image_path = db.Column(db.String(200), nullable=True)
    created = db.Column(db.DateTime(timezone=True), server_default=now())
    author = db.relationship("User")
    tags = db.relationship(
        "Tag", secondary=post_tag, backref=db.backref("posts", lazy=True)
    )
Exemplo n.º 11
0
    def get(self):
        per_page = int(current_app.config["POSTS_PER_PAGE"])

        page = int(request.args.get("page")) if request.args.get("page") else 1

        query = Post.query.filter(Post.published_at <= now()).order_by(
            desc("published_at"))

        return paginated_json_response(query=query,
                                       per_page=per_page,
                                       page=page)
Exemplo n.º 12
0
def s_info(title):
  for blog in DSession.query(blogs).filter(blogs.title==title):
    pass
  if (request.method == 'PUT') or (request.args.get('_method') == 'PUT'):
    blog.updated_at=now()
    DSession.commit()
  if request.method == 'DELETE':
    DSession.delete(blog)
    DSession.commit()
    return redirect(url_for('s_titles'))
  return render_template('s_info.html', blog=blog)
Exemplo n.º 13
0
class PlayList(Base):
    id = Column(Integer, primary_key=True)
    owner = Column(BigInteger, ForeignKey('user.id'))
    name = Column(UnicodeText, nullable=False)
    play_list = Column(UnicodeText, nullable=False)
    created_at = Column(DateTime(timezone=True), nullable=False, default=now())

    __tablename__ = 'playlist'

    def __repr__(self):
        return '<User %r\'s %r>' % (self.owner, self.name)
Exemplo n.º 14
0
 def process_item(self, item, spider):
     original_uri = item['file_urls'][0]
     session = self.Session()
     gazette = session.query(WebScrapedGazette).filter_by(original_uri=original_uri).first()
     if gazette:
         gazette.last_seen = func.now()
         gazette.referrer = item['referrer']
     else:
         gazette = WebScrapedGazette(
             label=item['label'],
             original_uri=item['file_urls'][0],
             referrer=item['referrer'],
             store_path=item['files'][0]['path'],
             published_date=item['published_date'],
             last_seen=func.now(),
             first_seen=func.now()
         )
         session.add(gazette)
     session.commit()
     return item
Exemplo n.º 15
0
def upgrade():
    op.create_table(
        'user',
        sa.Column('user_id', sa.Integer, primary_key=True),
        sa.Column('first_name', sa.String(255)),
        sa.Column('last_name', sa.String(255)),
        sa.Column('phone_number', sa.String(255)),
        sa.Column('create_dttm', sa.DateTime(), server_default=now()),
        sa.Column('update_dttm', sa.DateTime(), nullable=True),
        sa.Column('delete_dttm', sa.DateTime(), nullable=True),
    )
Exemplo n.º 16
0
class ChatLogDO(BaseModel):
    """ 聊天记录表 """
    __tablename__ = 'my_chat_log'
    id = Column(Integer, primary_key=True)
    from_user = Column(String(50), nullable=True)
    to_user = Column(String(50))
    sendtime = Column(String(50), nullable=True)
    content = Column(String(500), nullable=True)

    gmt_created = Column(DateTime, default=now())
    gmt_modified = Column(DateTime, default=now())
    deleted = Column(Boolean, default=False)

    def row2dict(self):
        d = {}
        for column in self.__table__.columns:
            if column in ['gmt_created', 'gmt_modified', 'deleted']:
                continue
            d[column.name] = getattr(self, column.name)
        return d
Exemplo n.º 17
0
class DemoData(Base):
    """"""
    implements(IDemoData)

    __tablename__ = TABLE_NAMESPACE_DEMO + "demodata"

    id = sa.Column("id", sa.Integer, primary_key=True)
    demo1 = sa.Column("demo1", sa.String(255))
    demo2 = sa.Column("damo2", sa.String(255))
    created = sa.Column(sa.DateTime, default=functions.now())
    updated = sa.Column(sa.DateTime, onupdate=functions.current_timestamp())
Exemplo n.º 18
0
class Area(Base):
    """
        区域信息
    """
    __tablename__ = 't_area'

    Fid = Column(Integer, primary_key=True)
    Farea_id = Column(Integer)
    Farea_name = Column(String(128))                 #区域名称
    Ffather = Column(Integer)
    Fgmt_created = Column(DateTime,default=now())
    Fgmt_modified = Column(DateTime,default=now())
    Fdeleted = Column(Boolean,default=0)

    def to_dict(self):
        dic = {}
        dic["Farea_id"] = self.Farea_id
        dic["Fcity_id"] = self.Ffather
        dic["Farea_name"] = self.Farea_name
        return dic
Exemplo n.º 19
0
class Company(Base):
    '''
        商户公司信息
    '''
    __tablename__ = 't_company'

    Fid = Column(Integer, primary_key=True)
    Fuser_id = Column(Integer)                   #:商家ID

    Fcompany_name = Column(String(128))                  #公司名称
    Fprovince = Column(Integer)          #省
    Fcity = Column(Integer)              #市
    Farea = Column(Integer)              #区
    Fdetail_address = Column(String(200),default='') #街道详细地址
    Faddress = Column(String(256),default='')               #从省开始的 整个地址
    Fcontact = Column(String(64),default='')                #联系人
    Fphone = Column(String(256),default='')                  #联系人电话
    Fqq = Column(String(20),default='')                  #联系人qq
    Fmail = Column(String(50),default='')                  #联系人邮箱
    Fphoto_url = Column(String(512),default='')             #logo 图片地址
    Fbackground_url = Column(String(512),default='')             #背景图片地址
    level = Column(Integer,default=6)               #商户星级1-10 代表0-5 颗星
    Fdescription = Column(Text,default='')          #商家描述
    Fis_activity = Column(Boolean,default=0)        #参加活动
    Flat = Column(Float,nullable=True)              #经度
    Flng = Column(Float,nullable=True)              #纬度
    Fapp_url = Column(String(256),default='')       #微信app地址
    Fapp_token = Column(String(256),default='')     #微信token
    Fapp_id = Column(String(256),default='')        #微信app id
    Fapp_secret = Column(String(256),default='')    #微信secret
    Fmenu_codes = Column(String(256),default='')    #微信菜单编码,aaa,bb,cc,最多三个

    Fstyle_tags = Column(String(256),default='',doc='风格标签')

    Fcheapest = Column(Integer,default=0)
    Fmost_expensive = Column(Integer,default=0)
    Ffavorite_count = Column(Integer,default=0,doc='收藏数')

    Fcreate_time = Column(DateTime, default=now())
    Fmodify_time = Column(DateTime, default=now())
    Fdeleted = Column(Boolean, default=0)
Exemplo n.º 20
0
class Users(Base):
    """用户信息表"""
    __tablename__ = 't_users'

    STATUS = {'normal': '正常', 'inactive': '未激活', 'delete': '删除', 'reeze': '冻结'}

    Fid = Column(Integer, primary_key=True)
    Fuid = Column(String(64))  #用户ID 内部使用
    Fuser_mobi = Column(String(32), nullable=False)  #手机号码 注册/登陆用
    Fuser_name = Column(String(128), default='', server_default='')  #用户姓名
    Fuser_pwd = Column(String(128), nullable=False)  #用户密码
    Fnick_name = Column(String(128), default='', server_default='')  #显示名称
    Frealname = Column(String(128), default='', server_default='')  #真实名称
    Femail = Column(String(128), default='', server_default='')  #email地址
    Fsex = Column(String(32), nullable=True)  #性别
    Frole_codes = Column(String(256), default='')  #角色
    Fpermission = Column(String(512), default='')  #权限
    is_employee = Column(Boolean, doc='是否是员工')  #是否是员工
    Fstatus = Column(String(128), default='inactive')  #状态
    Fweibo = Column(String(128), default='', server_default='')  #微博号
    Fweixin = Column(String(128), default='', server_default='')  #微信号
    Fqq = Column(String(16), default='', server_default='')  #QQ号
    Fphoto_url = Column(String(128), server_default='')  #用户头像url
    Fbirthday = Column(Date, default='1980-12-12',
                       server_default='1980-12-12')  #出生年月

    Fprovince = Column(Integer)  #省
    Fcity = Column(Integer)  #市
    Farea = Column(Integer)  #区
    Fdetail_address = Column(String(256))  #街道详细地址
    Faddress = Column(String(256))
    Fsign_text = Column(String(256), default='')  #个性签名
    Flast_visit = Column(DateTime, default=now())  #暴露
    Flast_visit_ip = Column(String(16), default='')
    Fvisit_times = Column(Integer, default=0)  #暴露 访问次数
    Fcoin = Column(Integer, default=0)
    Femail_check_url = Column(String(256), default='')  #邮件激活链接

    Fcreate_time = Column(DateTime, default=now())  #创建日期
    Fmodify_time = Column(TIMESTAMP, default=now())  #修改日期
    Fdeleted = Column(Boolean, default=0, server_default='0')  #默认存在
Exemplo n.º 21
0
class StripeSubscription(StripeBase):
    __tablename__ = "stripe_subscription"

    stripe_id = Column(String(255), nullable=False, primary_key=True)
    stripe_customer_id = Column(String(255), nullable=False)
    default_payment_method_id = Column(String(255), nullable=True)
    default_source_id = Column(String(255), nullable=True)

    stripe_created = Column(DateTime(timezone=True), nullable=False)
    cancel_at_period_end = Column(Boolean, nullable=False)
    canceled_at = Column(DateTime(timezone=True), nullable=True)
    current_period_end = Column(DateTime(timezone=True), nullable=False)
    current_period_start = Column(DateTime(timezone=True), nullable=False)
    ended_at = Column(DateTime(timezone=True), nullable=True)
    start_date = Column(DateTime(timezone=True), nullable=False)
    status = Column(String(20), nullable=False)

    create_timestamp = Column(TIMESTAMP(timezone=True),
                              nullable=False,
                              server_default=now())
    update_timestamp = Column(
        TIMESTAMP(timezone=True),
        nullable=False,
        server_default=now(),
        server_onupdate=now(),
    )

    customer = relationship(
        "StripeCustomer",
        uselist=False,
        primaryjoin=(" remote(StripeCustomer.stripe_id)=="
                     "foreign(StripeSubscription.stripe_customer_id)"),
    )
    subscription_items = relationship("StripeSubscriptionItem",
                                      back_populates="subscription",
                                      uselist=True)

    def get_email_id(self) -> Optional[PythonUUID]:
        if self.customer:
            return cast(PythonUUID, self.customer.get_email_id())
        return None
Exemplo n.º 22
0
class WeddingPhotoProductImages(Base):
    '''
    产品图片
    '''
    __tablename__ = 't_wedding_photo_product_images'

    Fid = Column(Integer, primary_key=True)
    Fwedding_photo_product_id = Column(Integer, doc='产品 楼上表ID')

    Fimg_id = Column(Integer, doc='图片ID')
    Furl = Column(String(512), doc='图片请求地址')
    Fsort = Column(Integer, doc='图片显示排序')
    Fdescription = Column(String(512), doc="图片描述")

    Fassist_count = Column(Integer, default=0)  #赞的次数
    Fcomments_count = Column(Integer, default=0)  #评论次数
    Fcollection = Column(Integer, default=0)  #收藏次数

    Fcreate_time = Column(DateTime, default=now())  #创建日期
    Fmodify_time = Column(DateTime, default=now())  #修改日期
    Fdeleted = Column(Boolean, default=0)
Exemplo n.º 23
0
class Run(UuidMixin, Base):
    __tablename__ = 'runs'

    pipeline_id = Column(UUID, ForeignKey('pipelines.id'), nullable=False)
    pipeline = relationship('Pipeline')
    date = Column(DateTime, nullable=False,
                  server_default=functions.now())
    reason = Column(String, nullable=False)
    type = Column(Enum(RunType), nullable=False)
    special = Column(Boolean, nullable=False, default=False)
    inputs = relationship('Input')
    outputs = relationship('Output')
Exemplo n.º 24
0
class AccountStatistics(Base):
    """Statistically relevant data concerning an account."""

    __tablename__ = "account"

    id = schema.Column(types.Integer(), primary_key=True, autoincrement=True)
    account_type = schema.Column(Enum(["guest", "converted", "full"]),
                                 default="full",
                                 nullable=True)
    creation_date = schema.Column(types.DateTime,
                                  nullable=True,
                                  default=functions.now())
Exemplo n.º 25
0
 def create(cls, author_name, topic_id, content):
     user = User.get_by_name(author_name)
     now = functions.now()
     Topic.get(topic_id)._new_comment(now)
     c = cls(author_id=user.id, topic_id=topic_id, content=content, date=now)
     try:
         db_session.add(c)
         db_session.commit()
     except (DataError, IntegrityError, ProgrammingError):
         db_session.rollback()
         raise
     return c
Exemplo n.º 26
0
class TopicReply(Base):

    __tablename__ = 't_topic_reply'

    Fid = Column(Integer, primary_key=True)
    Freply_index = Column(Integer, doc='同一话题回帖序号')
    Fuser_id = Column(Integer)  #用户ID
    Fparent_user_id = Column(Integer, nullable=True)  #用户ID
    Ftopic_id = Column(Integer, doc='话题ID')
    Fparent_id = Column(Integer, doc='回复ID', default=0)  #回复ID
    Ffull_parent_id = Column(String(512), doc='全路径', default='0')  #全路径ID
    Fcontent = Column(Text, default='')  #回复内容
    Fpraise = Column(Integer, default=0)  #点赞数

    Fis_top = Column(Boolean, default=0, doc='是否置顶')
    Fis_prime = Column(Boolean, default=0, doc='是否精华')
    Ftags = Column(String(256), doc='标签', default='')

    Fcreate_time = Column(DateTime, default=now())  #创建日期
    Fmodify_time = Column(DateTime, default=now())  #修改日期
    Fdeleted = Column(Boolean, default=0)
Exemplo n.º 27
0
class RelatorioProdutividadeModel(Base):
    __table_args__ = {'schema': 'radius_taas'}
    __tablename__ = "relatorio_produtividade"

    identificador = Column(Integer, primary_key=True)
    data_hora_geracao = Column(DateTime, nullable=False)
    data_inicio_referencia = Column(Date, nullable=False, default=now())
    data_fim_referencia = Column(Date, nullable=False)
    identificador_estabelecimento_saude = Column(Integer, nullable=True)
    identificador_profissional_saude = Column(Integer, nullable=True)
    nome_arquivo = Column(String, nullable=False)
    conteudo = Column(LargeBinary)
Exemplo n.º 28
0
 def get_investment_posts(currentUser, numPosts, lookbackHours):
     """
 Get investments a user can see.
 :param currentUser: current user id
 :param numPosts: limit how many posts a user can get
 :param lookbackHours: posts made within the past lookbackhours
 :return:
 """
     look_back_time = datetime.timedelta(hours=lookbackHours)
     look_back = now() - look_back_time
     return PostModel.query.filter(and_(PostModel.created_at > look_back, PostModel.owner_id != currentUser))\
       .filter(not_(exists().where(and_(InvestmentsModel.post_id == PostModel.id, InvestmentsModel.investor_id == currentUser)))).order_by(asc(PostModel.created_at)).limit(100)
Exemplo n.º 29
0
class Meal(db.Model):

    (BREAKFAST, AM_SNACK, LUNCH, PM_SNACK, DINNER, EXTRA_SNACK) = (0, 1, 2, 3,
                                                                   4, 5)

    id = db.Column(db.Integer, primary_key=True)

    meal_time = db.Column(db.Integer, nullable=False)

    data = db.Column(db.Text)

    timestamp = db.Column(db.DateTime, default=now())
Exemplo n.º 30
0
class Event(Base):
    __tablename__ = 'event'
    id = Column(Integer, primary_key=True)
    nom_bill_kn = Column(Integer, nullable=True)
    date_event = Column(DateTime, default=now())
    name_event = Column(String, nullable=True)

    def __init__(self, nom_bill_kn):
        self.nom_bill_kn = nom_bill_kn

    def __repr__(self):
        return "%s: %s (%s)" % (self.nom_bill_kn, self.name_event, self.date_event)
Exemplo n.º 31
0
class Ticker(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(140))

    @validates('name')
    def convert_upper(self, key, value):
        return value.upper()

    # https://stackoverflow.com/questions/13370317/sqlalchemy-default-datetime
    time_created = db.Column(
        db.DateTime,
        # best to use sql DB server time
        default=func.now())
    time_updated = db.Column(db.DateTime, onupdate=func.now())
    subscribed_users = db.relationship('TickerUser',
                                       backref='list',
                                       lazy='dynamic')

    # https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords=xiaomi&apikey=demo
    full_name = db.Column(db.String(140))
    type = db.Column(db.String(50))
    region = db.Column(db.String(140))
    currency = db.Column(db.String(50))
    timezone = db.Column(db.String(50))

    # https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=MSFT&apikey=demo
    open = db.Column(db.Float)
    high = db.Column(db.Float)
    low = db.Column(db.Float)
    price = db.Column(db.Float)
    volume = db.Column(db.Integer)
    latest_trading_day = db.Column(db.String(50))
    previous_close = db.Column(db.Float)
    change = db.Column(db.Float)
    change_percent = db.Column(db.Float)

    is_deleted = db.Column(db.Boolean, default=False)

    def __repr__(self):
        return '<Ticker {}: {}>'.format(self.id, self.name)
Exemplo n.º 32
0
class StripeInvoice(StripeBase):
    __tablename__ = "stripe_invoice"

    stripe_id = Column(String(255), nullable=False, primary_key=True)
    stripe_customer_id = Column(String(255), nullable=False)
    default_payment_method_id = Column(String(255),
                                       nullable=True,
                                       default=None)
    default_source_id = Column(String(255), nullable=True, default=None)

    stripe_created = Column(DateTime(timezone=True), nullable=False)
    currency = Column(String(3), nullable=False)
    total = Column(Integer, nullable=False)
    status = Column(String(15), nullable=False)

    create_timestamp = Column(TIMESTAMP(timezone=True),
                              nullable=False,
                              server_default=now())
    update_timestamp = Column(
        TIMESTAMP(timezone=True),
        nullable=False,
        server_default=now(),
        server_onupdate=now(),
    )

    customer = relationship(
        "StripeCustomer",
        uselist=False,
        viewonly=True,
        primaryjoin=(" remote(StripeCustomer.stripe_id) =="
                     "foreign(StripeInvoice.stripe_customer_id)"),
    )
    line_items = relationship("StripeInvoiceLineItem",
                              back_populates="invoice",
                              uselist=True)

    def get_email_id(self) -> Optional[PythonUUID]:
        if self.customer:
            return cast(PythonUUID, self.customer.get_email_id())
        return None
class TokenDevice(db.Model):
    __tablename__ = "tokendevice"
    id = db.Column(db.Integer, primary_key=True)

    user_id = db.Column(db.Integer, db.ForeignKey('user.id',
                                                  ondelete='CASCADE'))

    public_key = db.Column(db.String(512),
                           primary_key=False,
                           unique=False,
                           nullable=False)
    device_model = db.Column(db.String(100), nullable=True, unique=False)

    device_os = db.Column(db.String(100), nullable=True, unique=False)
    fcm_token = db.Column(db.String(200), nullable=False, unique=False)
    is_active = db.Column(db.Boolean,
                          index=False,
                          unique=False,
                          nullable=False,
                          default=True)
    created_at = db.Column(db.DateTime,
                           index=False,
                           unique=False,
                           nullable=False,
                           server_default=sqla_funcs.now())
    updated_at = db.Column(db.DateTime,
                           index=False,
                           unique=False,
                           nullable=True,
                           onupdate=sqla_funcs.now())
    last_login = db.Column(db.DateTime,
                           index=False,
                           unique=False,
                           nullable=False)

    def __str__(self):
        return self.name

    def get_id(self):
        return self.id
Exemplo n.º 34
0
class Run(Base):
    """A run.

    This is created when a user submits parameters and triggers the run of an
    experiment. It contains logs and the location of output files.
    """
    __tablename__ = 'runs'

    id = Column(Integer, primary_key=True)
    experiment_hash = Column(
        String, ForeignKey('experiments.hash', ondelete='CASCADE'))
    experiment = relationship('Experiment',
                              uselist=False,
                              back_populates='runs')
    upload_id = Column(Integer, ForeignKey('uploads.id', ondelete='RESTRICT'))
    upload = relationship('Upload', uselist=False)
    submitted = Column(DateTime,
                       nullable=False,
                       server_default=functions.now())
    started = Column(DateTime, nullable=True)
    done = Column(DateTime, nullable=True)

    parameter_values = relationship('ParameterValue', back_populates='run')
    input_files = relationship('InputFile', back_populates='run')
    ports = relationship('RunPort', back_populates='run')

    log = relationship('RunLogLine', back_populates='run')
    output_files = relationship('OutputFile', back_populates='run')

    @property
    def short_id(self):
        return run_short_ids.encode(self.id)

    @staticmethod
    def decode_id(short_id):
        return run_short_ids.decode(short_id)

    def get_log(self, from_line=0):
        return [log.line for log in self.log[from_line:]]

    def __repr__(self):
        if self.done:
            status = "done"
        elif self.started:
            status = "started"
        else:
            status = "submitted"
        return ("<Run id=%d, experiment_hash=%r, %s, %d parameters, "
                "%d inputs, %d outputs>") % (
                    self.id, self.experiment_hash, status,
                    len(self.parameter_values), len(
                        self.input_files), len(self.output_files))
Exemplo n.º 35
0
class TryEntity(Base):
    __tablename__ = 'tryEntities'
    id = Column(Integer, primary_key=True)
    currentRound = Column(Integer)
    createdAt = Column(DateTime, server_default=func.now())
    timeoutSeconds = Column(Integer)
    thresholdReachDate = Column(DateTime)
    threshold = Column(Integer)

    clients = relationship(
        "Client",
        secondary=association_clients_tryEntities,
        back_populates="tryEntities")
Exemplo n.º 36
0
class DBRequest(Base):
    __tablename__ = "request"
    id = Column(Integer, primary_key=True, autoincrement=True)
    type_id = Column(Integer, ForeignKey("request_type.id"))
    state_id = Column(Integer, ForeignKey("request_state.id"))
    cbsd_id = Column(String, nullable=False)
    created_date = Column(DateTime(timezone=True), nullable=False, server_default=now())
    updated_date = Column(DateTime(timezone=True), server_default=now(), onupdate=now())
    payload = Column(JSON)

    state = relationship("DBRequestState", back_populates="requests")
    type = relationship("DBRequestType", back_populates="requests")
    response = relationship("DBResponse", back_populates="request")

    def __repr__(self):
        return f"<{self.__class__.__name__}(id='{self.id}', " \
            f"type='{self.type.name}', " \
            f"state='{self.state.name}', " \
            f"cbsd_id='{self.cbsd_id}' " \
            f"created_date='{self.created_date}' " \
            f"updated_date='{self.updated_date}' " \
            f"payload='{self.payload}')>"
Exemplo n.º 37
0
    def get(self, slug):
        tag = find_or_fail(Tag, Tag.slug == slug)

        per_page = int(current_app.config["POSTS_PER_PAGE"])

        page = int(request.args.get("page")) if request.args.get("page") else 1

        query = (Post.query.filter(Post.published_at <= now()).filter(
            Post.tags.any(slug=slug)).order_by(desc("published_at")))

        return paginated_json_response(query=query,
                                       per_page=per_page,
                                       page=page)
Exemplo n.º 38
0
class WeddingCompanyShotPackageImage(Base):
    '''婚庆公司套系里的图片
    '''
    __tablename__ = 't_weddingcompany_shot_package_image'

    Fid = Column(Integer, primary_key=True)
    Fimg_id = Column(Integer, nullable=False, doc='图片ID')
    Fshot_package_id = Column(Integer,
                              nullable=False,
                              doc='表WeddingCompanyShotPackage的id')

    Furl = Column(String(512), nullable=False, doc='图片请求地址')
    Fsort = Column(Integer, default=0, doc='图片显示排序')
    Fdescription = Column(String(512), default='', doc="图片描述")

    Fcreate_time = Column(DateTime, default=now(), doc='创建日期')
    Fmodify_time = Column(DateTime, default=now(), doc='修改日期')
    Fdeleted = Column(Boolean, default=0)

    def __repr__(self):
        return '<WeddingCompanyShotPackageImage(img_id={0}, url={1})>'.format(
            self.Fimg_id, self.Furl)
Exemplo n.º 39
0
def s_info(title):
  for blog in DSession.query(blogs).filter(blogs.title==title):
    pass
  if request.method == 'POST':
    if request.form['choices'] == app.config['UPDATED']:
      blog.updated_at=now()
      DSession.commit()
    elif request.form['choices'] == app.config['DELETED']:
      DSession.delete(blog)
      DSession.commit()
      return redirect(url_for('s_titles'))
    else:pass
  return render_template('s_info.html', blog=blog)
Exemplo n.º 40
0
class BespeakOrders(Base):

    ORDER_STATUS = [(0, '下单待处理'), (1, '已处理,预定成功'), (2, '已处理,不预定'), (3, '已完结')]

    ORDER_TYPE = [(1, '商户订单'), (2, '套系订单'), (3, '作品订单')]
    __tablename__ = 't_bespeak_orders'

    Fid = Column(Integer, primary_key=True)
    Fuser_id = Column(Integer, doc='用户ID', nullable=True)
    Fmerchant_id = Column(Integer, doc='商户ID')
    Forder_type = Column(SmallInteger, doc='订单类型')  #1.商户订单,2.套系订单 3.作品订单
    Frefer_id = Column(Integer, doc='引用ID')
    Fcontact = Column(String(128), doc='联系人')
    Fmobile = Column(String(32), doc='联系电话')

    Fstatus = Column(SmallInteger, doc='状态')  #订单状态
    Fintention = Column(SmallInteger, nullable=True,
                        default=0)  #意向 0.待定 1.没意向  2.有意向

    Fcreate_time = Column(DateTime, default=now())
    Fmodify_time = Column(DateTime, default=now())
    Fdeleted = Column(Boolean, default=0)
Exemplo n.º 41
0
class BaseModel(db.Model):
    """模型基类"""

    __abstract__ = True

    # 这里的ID可加可不加,这个demo很小,所以统一用integer,如果是其他类型,请在表中具体写出
    id = db.Column(INTEGER(unsigned=True),
                   primary_key=True,
                   autoincrement=True,
                   comment='主键ID')
    update_time = db.Column(db.DateTime,
                            nullable=False,
                            default=datetime.now,
                            server_default=now(),
                            server_onupdate=current_timestamp(),
                            onupdate=datetime.now,
                            comment='更新时间')
    create_time = db.Column(db.DateTime,
                            nullable=False,
                            default=datetime.now,
                            server_default=now(),
                            comment='创建时间')
Exemplo n.º 42
0
class Activity(Base):

    __tablename__ = 't_activities'

    Fid = Column(Integer, primary_key=True)
    Fmerchant_id = Column(Integer)
    Fproduct_id = Column(Integer)
    Fproduct_name = Column(String(256), doc='产品名称')
    Fcover_img = Column(String(512), doc='封面图')
    Fproduct_type = Column(Integer)  #套系 1 其他类型再定
    Fcompany_name = Column(String(256), doc='公司名')
    Fprice = Column(Integer, doc='原价')
    Fsale_price = Column(Integer, doc='现价')
    Forder_gift = Column(String(512), doc='优惠')
    Fcompany_gift = Column(String(512))
    Fend_date = Column(DateTime)
    Flink_url = Column(String(1024), doc='链接')
    Fsort = Column(Integer, doc='排序')

    Fcreate_time = Column(DateTime, default=now())
    Fmodify_time = Column(DateTime, default=now())
    Fdeleted = Column(Boolean, default=False)
Exemplo n.º 43
0
    def get(self, slug):
        tag = find_or_fail(Tag, Tag.slug == slug)

        per_page = int(current_app.config["POSTS_PER_PAGE"])

        page = int(request.args.get("page")) if request.args.get("page") else 1

        query = (
            Post.query.filter(Post.published_at <= now())
            .filter(Post.tags.any(slug=slug))
            .order_by(desc("published_at"))
        )

        return paginated_json_response(query=query, per_page=per_page, page=page)
Exemplo n.º 44
0
def leaderboard_query(session, start_date, until_date):
    """
    This is, admittedly, a really ugly sql query. Query optimization has not
    been performed, but it shouldn't be anything more complicated than a few
    indices. Good luck.
    """
    #start_date = datetime.strptime(start_date, '%Y-%m-%d')
    #until_date = datetime.strptime(until_date_str, '%Y-%m-%d')
    subq = session\
        .query(
            Instance,
            InstanceType,
            User,
            case([(Instance.end_date != None, Instance.end_date)], else_=now()).label('stop_date'))\
        .join(Instance.user)\
        .join(Instance.type)\
        .subquery()

    uptime_column = case(
        [
            (subq.c.created_date > until_date, 0),
            (subq.c.stop_date < start_date, 0)
        ],
        else_=extract('epoch',
            func.LEAST(subq.c.stop_date, cast(until_date, DateTime)) -
            func.GREATEST(subq.c.created_date, cast(start_date, DateTime))
        )
    )

    print subq.c
    subq2 = session.query(
        subq.c.user_id,
        sum(case([(uptime_column == 0, 0)], else_=1)).label('instance_count'),
        #func.count(subq.c.instance_id).label('instance_count'),
        sum(uptime_column).label('uptime'),
        sum(uptime_column * subq.c.cpu).label('cpu_seconds')
    ).group_by(subq.c.user_id).order_by(desc('cpu_seconds')).subquery()

    q = session.query(
        subq2.c.user_id,
        subq2.c.uptime,
        subq2.c.cpu_seconds,
        subq2.c.instance_count,
        User.username,
        User.is_staff,
        User.name
    ).join(User)

    return q
Exemplo n.º 45
0
async def set_toggle_state(env, feature, state):
    results = await pg.fetch(db.toggles.select()
                             .where(db.toggles.c.feature == feature)
                             .where(db.toggles.c.env == env))

    results = _transform_toggles(results)
    if not results:
        if state == 'ON':
            await pg.fetchval(
                db.toggles.insert()
                    .values(feature=feature, env=env, state='ON', date_on=functions.now())
            )
    elif state == 'OFF':
        await pg.fetchval(db.toggles
                          .delete()
                          .where(db.toggles.c.feature == feature)
                          .where(db.toggles.c.env == env))
    return {
        'toggle': {
            'env': env,
            'feature': feature,
            'state': state,
        }
    }
Exemplo n.º 46
0
    pm = EmailProcessor()
    for uq_id in qq:
        user_query = session.query(UserQuery).get(uq_id)
        if user_query is None:
            logging.error("Query with id '%d' not found!" % (uq_id,))
            sys.exit(1)
        if user_query.fulfilled is not None:
            logging.info("Query '%d' already fulfilled, skipping....", (user_query.id))
            continue 
        try:    
            for msg in process_query(user_query.text, uq_id):
                user_query.message = msg.message 
                logging.info(msg.message)
                session.commit()

            user_query.fulfilled = now()
            session.commit()
            if user_query.email is not None:
                pm.send_success(user_query.email, user_query.id)
            user_query.email = None 
            session.commit()
        except QueryException as ex:
            except_type, except_class, tb = sys.exc_info()
            logging.critical(traceback.extract_tb(tb))
            logging.critical(except_type)
            logging.critical(except_class)
            logging.critical(ex)
            user_query.message = ex.message
            user_query.cancelled = True
            if user_query.email is not None:
                pm.send_failure(user_query.email, ex.message)
Exemplo n.º 47
0
 def _insertResources(self):
     query = {'status':self.computer_status , 'update0':functions.now() , 'update1':functions.now() , 
              'computername':self.computer_id, 'is_mac': self.is_mac}
     self._simpleQuery(insert(schema.computers).values(query))
Exemplo n.º 48
0
async def add_feature(feature_name, username):
    await pg.fetchval(db.features.insert().values(name=feature_name,
                                                  created_on=functions.now(),
                                                  created_by=username))
    return {'name': feature_name}
Exemplo n.º 49
0
 def update(self):
     self.updated_at = functions.now()
     self.update_serial = self.update_serial + 1
Exemplo n.º 50
0
from sqlalchemy.sql.functions import current_date, current_time, now
from database_setup import Base, Catalog, Item, User

engine = create_engine('sqlite:///catlog.db')
# Bind the engine to the metadata of the Base class so that the
# declaratives can be accessed through a DBSession instance
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
session = DBSession()


# Create an special user
user1 = User(name="admin",
             picture='https://lh3.googleusercontent.com/-v_3iOVC5VI0/AAAAAAAAAAI/AAAAAAAAAAA/ye0_gnqSwI4/s120-c/photo.jpg',
             last_login = now())
session.add(user1)
session.commit()
sleep(2)

meat = Catalog(name = "Meat",
               last_edit = now(),
               user = user1,)
session.add(meat)
session.commit()
sleep(2)
beef = Item(name = "Beef",
            catalog = meat,
            picture = "https://upload.wikimedia.org/wikipedia/commons/6/60/Standing-rib-roast.jpg",
            description = '''Beef muscle meat can be cut into roasts, short ribs or steak (filet mignon, sirloin steak, rump steak, rib steak, rib eye steak, hanger steak, etc.). Some cuts are processed (corned beef or beef jerky), and trimmings, usually mixed with meat from older, leaner cattle, are ground, minced or used in sausages.''',
            user = user1)