QuerySet в Excel , файл должен упасть в загрузки
У меня есть эндпоинт actions в view который его обрабатывает есть queryset и условия в зависимости от action в запросе будет вызываться функция , я написал функцию которая работает с помощью openpyxl класса Workbook , подскажите почему файл не падает в загрузки?
urls.py
path('pipelines/actions/', PipelineActions.as_view())
views.py Последнее действие
class PipelineActions(APIView):
"""
Page audience, bulk actions
Передается список id pipeline_user' в переменную bot_ids
action передается в переменную action
Action type = add_tag, remove_tag, subscribe_to_sequence, unsubscribe_from_sequence, set_custom_field,
clear_custom_field, unsubscribe_from_bot, export_numbers
Дополнительный id передается в переменную additional_id
дополлнительный id - это id тега, сиквенса, переменной
Новое значение переменной передается в перемнную var_value
сейчас endpoint не делает каких либо действий, стоит заглушка.
Но можете делать запросы и получите в ответе success = true
"""
def post(self, request, *args, **kwargs):
# todo доделать этот метод. Методы брать из pipeline_users_actions
response = {}
bot_ids = request.data.get("bot_ids")
action = request.data.get("action", None)
additional_id = request.data.get("additional_id", None)
var_value = request.data.get("var_value", None)
pipeline_users = []
for bot_id in bot_ids:
pipeline_users.append(PipelineUser.objects.get(id=bot_id))
if action == "add_tag":
add_tag(pipeline_users, additional_id)
elif action == "remove_tag":
remove_tag(pipeline_users, additional_id)
elif action == "subscribe_to_sequence":
subscribe_to_sequence(pipeline_users, additional_id)
elif action == "unsubscribe_from_sequence":
unsubscribe_from_sequence(pipeline_users, additional_id)
elif action == "set_custom_field":
set_custom_field(pipeline_users, additional_id, var_value)
elif action == "clear_custom_field":
clear_custom_field(pipeline_users, additional_id)
elif action == "unsubscribe_from_bot":
unsubscribe_from_bot(pipeline_users)
elif action == "export_numbers":
export_response = export_numbers(pipeline_users)
response["success"] = True
return HttpResponse(export_response)
метод export_numbers , который будет вызван
def export_numbers(pipeline_users):
"""
Выгрузка пользователей в Excel
"""
# export = AdsSourceExportView()
# export.queryset = pipeline_users
# export.serializer_class = PipelineUserExportSerializer
# export.renderer_classes = [XLSXRenderer]
# export.filename = 'users-{}.xlsx'.format(datetime.now())
# return export
users_queryset = pipeline_users
response = HttpResponse(
content_type='application/xlsx',
)
response['content-disposition'] = 'attachment; filename=users-{date}'.format(
date=datetime.now().strftime('%Y-%m-%d'),
)
workbook = Workbook()
# Get active worksheet/tab
worksheet = workbook.active
worksheet.title = 'Users'
# Define some styles and formatting that will be later used for cells
header_font = Font(name='Calibri', bold=True)
centered_alignment = Alignment(horizontal='center')
border_bottom = Border(
bottom=Side(border_style='medium', color='FF000000'),
)
wrapped_alignment = Alignment(
vertical='top',
wrap_text=True
)
# Define the column titles and widths
columns = [
('Full Name', 40),
('Phone', 40)
]
row_num = 1
# Assign the titles for each cell of the header
for col_num, (column_title, column_width) in enumerate(columns, 1):
cell = worksheet.cell(row=row_num, column=col_num)
cell.value = column_title
cell.font = header_font
cell.border = border_bottom
cell.alignment = centered_alignment
# set column width
column_letter = get_column_letter(col_num)
column_dimensions = worksheet.column_dimensions[column_letter]
column_dimensions.width = column_width
# Iterate through all users
for user in users_queryset:
row_num += 1
# Define the data for each cell in the row
row = [
(user.full_name, 'Normal'),
(user.phone, 'Normal')
]
# Assign the data for each cell of the row
for col_num, (cell_value, cell_format) in enumerate(row, 1):
cell = worksheet.cell(row=row_num, column=col_num)
cell.value = str(cell_value)
cell.style = cell_format
# if cell_format == 'String':
# cell.string_format = '#,##0'
cell.alignment = wrapped_alignment
worksheet.freeze_panes = worksheet['A2']
workbook.save(response)
return response