Код: Выделить всё
@celery.task()
def download_csv():
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
file_name = f"service_requests_{timestamp}.csv"
file_path = os.path.join(current_app.config['EXPORT_FOLDER'], file_name)
service_requests = ServiceRequest.query.filter_by(service_status="closed").all()
with open(file_path, mode='w', newline='') as csvfile:
csv_writer = csv.writer(csvfile)
csv_writer.writerow([
"Service ID",
"Customer ID",
"Professional ID",
"Date of Request",
"Date of Completion",
"Remarks"
])
for request in service_requests:
csv_writer.writerow([
request.service_id,
request.customer_id,
request.professional_id,
request.date_of_request.strftime('%Y-%m-%d %H:%M:%S'),
request.date_of_completion.strftime('%Y-%m-%d %H:%M:%S') if request.date_of_completion else None,
request.rating or "No remarks"
])
print(f"CSV export completed. File saved at {file_path}")
return file_path
Код: Выделить всё
class ExportCsv(Resource):
# @auth_token_required
# @roles_required('admin')
def post(self):
task = download_csv.delay()
return make_response(jsonify({'message': 'Task has been triggered', 'task_id': task.id}),200)
def get(self, task_id):
res = AsyncResult(task_id, app=celery)
if res.ready():
file_path = res.result
return send_file(file_path, as_attachment=True, mimetype='text/csv')
return make_response(jsonify({'message': 'Task still running'}), 400)
Код: Выделить всё
service_requests = ServiceRequest.query.filter_by(service_status="closed").all()
Подробнее здесь: https://stackoverflow.com/questions/792 ... with-redis