最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[已解决]Flask的SQLAlchemy中定义和使用日期时间类型

Flask crifan 8361浏览 0评论

flask sqlalchemy Datetime

Quickstart — Flask-SQLAlchemy Documentation (2.1)

Flask-SQLAlchemy 使用小坑-rrestjs

Column and Data Types — SQLAlchemy 1.1 Documentation

“class sqlalchemy.types.Date

Bases: sqlalchemy.types._DateAffinity, sqlalchemy.types.TypeEngine

A type for datetime.date() objects.

class sqlalchemy.types.DateTime(timezone=False)

Bases: sqlalchemy.types._DateAffinity, sqlalchemy.types.TypeEngine

A type for datetime.datetime() objects.

Date and time types return objects from the Python datetime module. Most DBAPIs have built in support for the datetime module, with the noted exception of SQLite. In the case of SQLite, date and time types are stored as strings which are then converted back to datetime objects when rows are returned.

__init__(timezone=False)

Construct a new DateTime.

Parameters:    timezone – boolean. If True, and supported by the backend, will produce ‘TIMESTAMP WITH TIMEZONE’. For backends that don’t support timezone aware timestamps, has no effect.

class sqlalchemy.types.Time(timezone=False)

Bases: sqlalchemy.types._DateAffinity, sqlalchemy.types.TypeEngine

A type for datetime.time() objects.”

from sipevents import app
from . import db
# from app import db
# from datetime import datetime
class Event(db.Model):
    __tablename__ = “events”
    # Columns
    id = db.Column(db.Integer, primary_key = True, autoincrement = True)
    user_openid = db.Column(db.String(64))
    title = db.Column(db.String(128))
    start_date = db.Column(db.DateTime)
    end_date = db.Column(db.DateTime)
    location = db.Column(db.String(256))
    user_limit = db.Column(db.Integer)
    is_public = db.Column(db.Boolean)
    description = db.Column(db.Text)
    def __init__(self,
                 id,
                 user_openid,
                 title = “”,
                 start_date = None,
                 end_date = None,
                 user_limit = 0,
                 is_public = False,
                 description = “”):
        self.id = id
        self.user_openid = user_openid
        self.title = title
        self.start_date = start_date
        self.end_date = end_date
        self.user_limit = user_limit
        self.is_public = is_public
        self.description = description
    def __repr__(self):
        return ‘<Event id=%d user_openid=%s title=%s>’ % (self.id, self.user_openid, self.title)

对应的初始化,就是用datetime初始化:

# test Event create/query/delete
startDatetime = datetime.now()
app.logger.debug(‘startDatetime=%s’, startDatetime)
oneDayDelta = timedelta(days=1)
app.logger.debug(‘oneDayDelta=%s’, oneDayDelta)
endDatetime = startDatetime + oneDayDelta
app.logger.debug(‘endDatetime=%s’, endDatetime)
eventDict = {
    ‘id’            : 1,
    ‘user_openid’   : crifanUserJson[‘openid’],
    ‘title’         : u”讨论日历的公众号名字”,
    ‘start_date’    : startDatetime,
    ‘end_date’      : endDatetime,
    ‘user_limit’    : 5,
    ‘is_public’     : False,
    ‘description’   : u”头脑风暴讨论公众号的名字”,
}
app.logger.debug(‘eventDict=%s’, eventDict)
existedEvent= Event.query.filter_by(id=eventDict[‘id’]).first()
app.logger.debug(‘existedEvent=%s’, existedEvent)
if existedEvent :
    # has exsited this event
    app.logger.debug(‘已存在此活动 existedEvent=%r’, existedEvent)
else :
    eventObj = Event(id = eventDict[‘id’],
                    user_openid = eventDict[‘user_openid’],
                    title = eventDict[‘title’],
                    start_date = eventDict[‘start_date’],
                    end_date = eventDict[‘end_date’],
                    user_limit = eventDict[‘user_limit’],
                    is_public = eventDict[‘is_public’],
                    description = eventDict[‘description’])
    app.logger.debug(‘eventObj=%s’, eventObj)
    db.session.add(eventObj)
db.session.commit()
    app.logger.debug(‘added eventObj=%s’, eventObj)
currentEvents= Event.query.all()
app.logger.debug(‘currentEvents=%s’, currentEvents)
currentEventsCount = len(currentEvents)
app.logger.debug(‘currentEventsCount=%s’, currentEventsCount)
if currentEventsCount > 0  :
    firstEvent = currentEvents[0]
    app.logger.debug(‘firstEvent=%s’, firstEvent)
    db.session.delete(firstEvent)
db.session.commit()
    app.logger.debug(‘deleted firstEvent=%s’, firstEvent)

转载请注明:在路上 » [已解决]Flask的SQLAlchemy中定义和使用日期时间类型

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.207 seconds, using 22.11MB memory