#python #flask #time #flask-sqlalchemy #flask-login
#python #flask #время #flask-sqlalchemy #flask-login
Вопрос:
Я пытаюсь перевести время ввода из HTML в sqlite, используя логин Flask
Это модель
class Shop(db.Model):
__tablename__ = 'shop'
id = db.Column(db.Integer, primary_key=True)
shop_id = db.Column(db.BigInteger)
shop_name = db.Column(db.String(50))
shop_phone = db.Column(db.String(10))
shop_email = db.Column(db.String(100))
shop_calendarId = db.Column(db.String)
shop_address = db.Column(db.String(300))
shop_provinces = db.Column(db.String(20))
shop_start_time = db.Column(db.Time)
shop_end_time = db.Column(db.Time)
shop_workers = db.Column(db.Integer)
shop_slots = db.Column(db.Integer)
shop_step_time = db.Column(db.Integer)
shop_duration = db.Column(db.Integer)
shop_web = db.Column(db.String)
shop_fanpage = db.Column(db.String)
shop_facebook_mes = db.Column(db.String)
shop_logo = db.Column(db.String)
shop_description = db.Column(db.String(300))
shop_created_date = db.Column(db.Date)
shop_ended_date = db.Column(db.Date)
shop_token = db.Column(db.String)
def __str__(self):
return "{}".format(self.name)
def __repr__(self):
return "{}: {}".format(self.shop_id, self.__str__())
Это код python для получения формы
@main.route('/dashboard', methods=['POST'])
@login_required
def dashboard_post():
email = current_user.email
shop = Shop.query.filter_by(shop_email=email).first()
shop_workers = request.form.get('shop_workers')
shop_slots = request.form.get('shop_slots')
shop_step_time = request.form.get('shop_step_time')
shop_duration = request.form.get('shop_duration')
shop_provinces = request.form.get('shop_provinces')
shop_address = request.form.get('shop_address')
shop_phone = request.form.get('shop_phone')
shop_token = request.form.get('shop_token')
shop_name = request.form.get('shop_name')
shop_start_time = request.form.get('shop_start_time')
shop_end_time = request.form.get('shop_end_time')
shop_web = request.form.get('shop_web')
shop_fanpage = request.form.get('shop_fanpage')
shop_facebook_mes = request.form.get('shop_facebook_mes')
shop_logo = request.form.get('shop_logo')
shop_description = request.form.get('shop_description')
if shop_workers != '':
shop.shop_workers = shop_workers
db.session.commit()
if shop_slots != '':
shop.shop_slots = shop_slots
db.session.commit()
if shop_step_time != shop_step_time:
shop.shop_step_time = shop_step_time
db.session.commit()
if shop_duration != '':
shop.shop_duration = shop_duration
db.session.commit()
if shop_provinces !='':
shop.shop_provinces = shop_provinces
db.session.commit()
if shop_phone !='':
shop.shop_phone = shop_phone
db.session.commit()
if shop_address !='':
shop.shop_address = shop_address
db.session.commit()
if shop_name !='':
shop.shop_name = shop_name
db.session.commit()
if shop_address !='':
shop.shop_address = shop_address
db.session.commit()
if shop_start_time !='':
shop.shop_start_time = shop_start_time
db.session.commit()
if shop_end_time !='':
shop.shop_end_time = shop_end_time
db.session.commit()
if shop_web !='':
shop.shop_web = shop_web
db.session.commit()
if shop_fanpage !='':
shop.shop_fanpage = shop_fanpage
db.session.commit()
if shop_facebook_mes !='':
shop.shop_facebook_mes = shop_facebook_mes
db.session.commit()
if shop_logo !='':
shop.shop_logo = shop_logo
db.session.commit()
if shop_description !='':
shop.shop_description = shop_description
db.session.commit()
return redirect(url_for('main.dashboard_redirect'))
Это html-код
<div class="col"><label
class="label-input-group">Giờ mở cửa: {{ shop_start_time }}</label>
<div class=""><input id="shop_start_time" name="shop_start_time" type="Time"
class="next-input"
placeholder="{{ shop_start_time }}" step="1"
value="">
</div>
</div>
<div class="col"><label
class="label-input-group">Giờ đóng cửa: {{ shop_end_time }}</label>
<div class=""><input id="shop_end_time" name="shop_end_time" type="Time"
class="next-input"
placeholder="{{ shop_end_time }}" step="1"
value="">
</div>
</div>
Ошибка выглядит следующим образом
sqlalchemy.exc.StatementError: (raised as a result of Query-invoked autoflush; consider using a session.no_autoflush block if this flush is occurring prematurely)
(builtins.TypeError) SQLite Time type only accepts Python time objects as input.
[SQL: UPDATE shop SET shop_start_time=? WHERE shop.id = ?]
[parameters: [{'shop_start_time': '08:00', 'shop_id_1': 1}]]
Кто-нибудь мне поможет, спасибо
Ответ №1:
Исключение вызвано тем, что вы пытались передать строку ’08:00′ непосредственно из вашего поля ввода объекту.
Объект ожидает, что вы предоставите time
объект, такой как объекты, созданные с помощью datetime
. Подробнее об объектах времени python.. Вы можете создавать эти объекты, например, с помощью strptime datetime. Если вы хотите, чтобы он анализировался автоматически, взгляните на Flask wtf.
Ответ №2:
Спасибо за все, я изменил свой код, и это сработало
if shop_start_time !='':
shop.shop_start_time = datetime.strptime(shop_start_time,"%H:%M").time()
db.session.commit()
if shop_end_time !='':
shop.shop_end_time = datetime.strptime(shop_end_time,"%H:%M").time()