当数据库为空时,它应该满足第一个 if 条件并只返回错误,但由于某种原因,它会执行其余部分。即使我在 if 语句之后注释掉所有代码,它也会执行所有代码并返回一个 ICS 文件。
不知何故,if 之后的其余代码被保存在别处或 ICS 文件存储在某处并每次都被返回。
from flask import Flask, request, Response, send_file, make_response
from flask_restx import Api, Resource, fields, reqparse
from ics import Calendar, Event
@api.route('/calendar')
class ICSCalendar(Resource):
@api.response(200, 'Successfully Retrieved Calendar')
@api.response(404, 'No Events Found')
@api.doc(description="Get all events in an ``ICS`` calendar format")
def get(self):
'''Get all events in an ICS calendar format'''
events = execute_query("SELECT * FROM events")
print(events)
if not events:
return {"Error": "No events found"}, 404
cal = Calendar()
for row in events:
event = Event()
event.name = row[1]
event.begin = pytz.timezone('Australia/Sydney').localize(datetime.combine(datetime.strptime(row[2], '%Y-%m-%d').date(), datetime.strptime(row[3], '%H:%M:%S').time()))
event.end = pytz.timezone('Australia/Sydney').localize(datetime.combine(datetime.strptime(row[2], '%Y-%m-%d').date(), datetime.strptime(row[4], '%H:%M:%S').time()))
event.location = f"{row[5]}, {row[6]}, {row[7]} {row[8]}"
event.description = row[9]
event.last_modified = pytz.utc.localize(datetime.strptime(row[10], '%Y-%m-%d %H:%M:%S'))
cal.events.add(event)
# Write the ICS data to an in-memory buffer
buffer = StringIO(cal.serialize(), newline=None)
buffer.seek(0)
# Create a response with the ICS data as an attachment
response = make_response(send_file(buffer, as_attachment=True, attachment_filename='calendar.ics', mimetype='text/calendar'))
response.headers['Content-Disposition'] = 'attachment; filename=calendar.ics'
buffer.truncate(0)
return response`
@api.route('/calendar')
class ICSCalendar(Resource):
@api.response(200, 'Successfully Retrieved Calendar')
@api.response(404, 'No Events Found')
@api.doc(description="Get all events in an ``ICS`` calendar format")
def get(self):
'''Get all events in an ICS calendar format'''
events = execute_query("SELECT * FROM events")
print(events)
if not events:
return {"Error": "No events found"}, 404
我已经将数据库设置为空,并且只使用了上面的代码,但它返回了一个 ICS 文件。
我只希望它在事件中有内容时返回一个 ICS 文件。
有谁知道为什么这会在不应该返回 ICS 数据的情况下返回 ICS 数据?
1- events 是一个对象,因此您不能使用 if not events: 语句。由于这个对象实际存在。例如,您应该使用类似下面的内容;
if events.get("...") is None: # if it is dict type object
请看它是什么类型的对象并适应它。例如,如果它是一个 .json 对象,那么它可以有键,但值可以是 "" 或 None 那么下面的代码块将不会产生影响,因此 ICS 文件将返回。
if not events:
return {"Error": "No events found"}, 404
2- 当您在 if 语句之后注释掉所有代码时,它实际上不能返回 ICS 文件。它可能以某种方式被缓存,这就是它可能返回的原因。
谢谢。