На ПК приложение на Flask отрабатывает, а на сервере pythonenywhere всё работает кроме экспорта csv-файла на ПК. Почему?
это Python-файл:
from flask import Flask, request, render_template, send_file
import requests
import csv
import os
import logging
import json
import pandas as pd
from io import BytesIO
logging.basicConfig(level=logging.DEBUG)
app = Flask(__name__)
# Функция для поиска вакансий
def search_vacancies(keyword):
BASE_URL = "https://api.hh.ru/vacancies"
vacancies_found = [] # Список для хранения найденных вакансий
per_page = 100
page = 0
while True:
params = {
'text': keyword,
'page': page,
'per_page': per_page,
'only_with_salary': True # Только вакансии с зарплатой
}
response = requests.get(BASE_URL, params=params)
if response.status_code != 200:
print("Ошибка при обращении к API")
break
lan = response.json()
if not lan['items']:
break
for item in lan['items']:
# vacancy_name = item['name']
vacancy_name = item['name'].lower() # Приводим название вакансии к нижнему регистру для сравнения
# Проверяем, содержит ли название вакансии ключевое слово
if keyword in vacancy_name:
salary_from = item['salary']['from'] if item['salary'] else None
salary_to = item['salary']['to'] if item['salary'] else None
currency = item['salary']['currency'] if item['salary'] else None
city = item['area']['name'] if 'area' in item else None
link = item['alternate_url'] if 'alternate_url' in item else None
discription = item['snippet']['responsibility'] if 'snippet' in item else None
vacancies_found.append({
'name': vacancy_name,
'salary_from': salary_from,
'salary_to': salary_to,
'currency': currency,
'city': city,
'link': link,
'discription': discription
})
page += 1
return vacancies_found
# Функция для сохранения вакансий в CSV
def save_to_csv(vacancies, filename='vacancies.csv'):
# Если имя файла не передано, создаем его на основе ключевого слова
keys = vacancies[0].keys()
with open(filename, 'w', newline='', encoding='utf-16') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=keys)
writer.writeheader()
writer.writerows(vacancies)
return filename # Возвращаем имя файла
@app.route('/download')
def download_file():
return send_file('vacancies.csv', as_attachment=True)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
keyword = request.form['keyword']
vacancies = search_vacancies(keyword)
if vacancies:
filename = save_to_csv(vacancies)
return render_template('index.html', vacancies=vacancies, filename=filename, download=True)
else:
return render_template('index.html', message='Нет найденных вакансий')
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
это html-файл:
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Парсер вакансий</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<h1>Парсер вакансий</h1>
<form method="POST">
<label for="keyword">Введите вакансию для поиска:</label>
<input type="text" id="keyword" style="margin-left: -2%;" name="keyword" required>
<button type="submit">Искать</button>
</form>
{% if vacancies %}
<h2>Найденные вакансии: </h2>
{% if download %}
<a href="/download" class="form-control">Скачать вакансии в CSV</a>
{% endif %}
<table>
<tr>
<th>Название</th>
<th>Зарплата от</th>
<th>Зарплата до</th>
<th>Валюта</th>
<th>Город</th>
<th>Описание</th>
<th>Ссылка</th>
</tr>
{% for vacancy in vacancies %}
<tr>
<td>{{ vacancy.name }}</td>
<td>{{ vacancy.salary_from }}</td>
<td>{{ vacancy.salary_to }}</td>
<td>{{ vacancy.currency }}</td>
<td>{{ vacancy.city }}</td>
<td>{{ vacancy.discription }}</td>
<td><a href="{{ vacancy.link }}" class="vacancy-link">{{ vacancy.link }}</a></td>
</tr>
{% endfor %}
</table>
{% elif message %}
<p>{{ message }}</p>
{% endif %}
{% if download %}
<a href="/download" class="form-control">Скачать вакансии в CSV</a>
{% endif %}
</table>
</body>
</html>
Это парсер вакансий hh.ru по API. На ПК всё отрабатывает нормально, загружаю на сервер pythonenywhere всё работает кроме скачивания csv-файла на ПК. Выдаёт такую ошибку:
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
И ещё:
Could not edit /home/gloone/vacancies.csv. PythonAnywhere's editor only recognises ASCII or UTF8-encoded text
Если кто знает подскажите в чём ошибка?
Ссылка на приложение: https://gloone.pythonanywhere.com/