добавлены проверки проверки
This commit is contained in:
41
main.py
41
main.py
@@ -59,7 +59,7 @@ wp.create_table()
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["https://allowlgroup.ru","http://localhost:5173", "http://45.129.78.228:8000"], # или список разрешенных адресов, например [""]
|
||||
allow_origins=["*"], # или список разрешенных адресов, например ["https://allowlgroup.ru","http://localhost:5173", "http://45.129.78.228:8000"]
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
@@ -77,16 +77,32 @@ def download_proxies(url):
|
||||
|
||||
def fetch_with_proxy(url, proxy, verify, timeout):
|
||||
proxies = {
|
||||
'http': f'http://{proxy}', # или 'socks5://' если SOCKS5 и т.п.
|
||||
'http': f'http://{proxy}',
|
||||
'https': f'http://{proxy}',
|
||||
}
|
||||
try:
|
||||
response = requests.get(url, proxies=proxies, timeout=timeout, verify=verify)
|
||||
response.encoding = 'utf-8'
|
||||
response.raise_for_status()
|
||||
return response.text
|
||||
if response.status_code == 200:
|
||||
# Проверяем содержимое - если это ошибка от прокси
|
||||
if '"message":"Request failed' in response.text or '403' in response.text[:500]:
|
||||
# print(f"Proxy {proxy} - Site returned 403 (inside response)")
|
||||
return None
|
||||
# print(f"Proxy {proxy} - SUCCESS")
|
||||
return response.text
|
||||
elif response.status_code == 403:
|
||||
# print(f"Proxy {proxy} - 403 Forbidden")
|
||||
return None # Прокси работает, но сайт блокирует
|
||||
else:
|
||||
# print(f"Proxy {proxy} - Status {response.status_code}")
|
||||
return None
|
||||
except:
|
||||
return None
|
||||
# Перемешивает список прокси для случайного начала
|
||||
def get_shuffled_proxies(proxies_list):
|
||||
shuffled = proxies_list.copy()
|
||||
random.shuffle(shuffled)
|
||||
return shuffled
|
||||
|
||||
# Общие функции нахождения ссылок
|
||||
def extract_map_area_hrefs(url, verify=True, ist_number=1):
|
||||
@@ -119,6 +135,7 @@ def extract_map_area_hrefs(url, verify=True, ist_number=1):
|
||||
# функции парсера первого источника (газета)
|
||||
def extract_text_from_url_one(url, timeout=10, verify=True):
|
||||
proxies_list = download_proxies(PROXIES_URL)
|
||||
proxies_list = get_shuffled_proxies(proxies_list)
|
||||
|
||||
response = ""
|
||||
for proxy in proxies_list:
|
||||
@@ -155,7 +172,7 @@ def extract_text_from_url_one(url, timeout=10, verify=True):
|
||||
#Функции парсера второго источника (военного)
|
||||
def extract_text_from_url(url, timeout=10, verify=True):
|
||||
proxies_list = download_proxies(PROXIES_URL)
|
||||
|
||||
proxies_list = get_shuffled_proxies(proxies_list)
|
||||
response = ""
|
||||
for proxy in proxies_list:
|
||||
response = fetch_with_proxy(url, proxy=proxy, timeout=timeout, verify=verify)
|
||||
@@ -224,6 +241,7 @@ def gpt_response_message(content, ist_number=1):
|
||||
|
||||
retries += 1
|
||||
|
||||
# перезапуск сервиса GPT при неудачных попытках запроса
|
||||
def restart_service(service_name):
|
||||
try:
|
||||
subprocess.run(['sudo', 'systemctl', 'restart', service_name], check=True)
|
||||
@@ -257,7 +275,12 @@ def create_folder(num):
|
||||
# Функция формирования документа
|
||||
def update_bd_and_create_document(response_text, article_date, url, parsed_at, original_text, other):
|
||||
clean_response = ''
|
||||
|
||||
|
||||
if not response_text:
|
||||
print(f"Пустой ответ от GPT для URL: {url}")
|
||||
logger.info(f"Пустой ответ от GPT для URL: {url}")
|
||||
return
|
||||
|
||||
try:
|
||||
clean_response = response_text.strip().replace('```json', '').replace('```', '').strip()
|
||||
data = json.loads(clean_response)
|
||||
@@ -336,7 +359,8 @@ def start_pars_one_istochnik(data_init):
|
||||
if len(text) >= 100:
|
||||
response_text = gpt_response_message(text, ist_number=2)
|
||||
print(response_text)
|
||||
update_bd_and_create_document(response_text=response_text, article_date=f"{current_year}/{current_month}/{current_day}", url=link, parsed_at=str(dt.now()), original_text=text, other=url)
|
||||
if response_text:
|
||||
update_bd_and_create_document(response_text=response_text, article_date=f"{current_year}/{current_month}/{current_day}", url=link, parsed_at=str(dt.now()), original_text=text, other=url)
|
||||
|
||||
wp.update_task(task_id, status='completed', finished_at=datetime.utcnow())
|
||||
|
||||
@@ -363,7 +387,8 @@ def start_pars_two_istochnik():
|
||||
if len(text) >= 100:
|
||||
response_text = gpt_response_message(text)
|
||||
print(response_text)
|
||||
update_bd_and_create_document(response_text=response_text, article_date=time_text, url=hrefs, parsed_at=str(dt.now()), original_text=text, other=url)
|
||||
if response_text:
|
||||
update_bd_and_create_document(response_text=response_text, article_date=time_text, url=hrefs, parsed_at=str(dt.now()), original_text=text, other=url)
|
||||
except:
|
||||
continue
|
||||
|
||||
|
||||
@@ -6,8 +6,8 @@ conn = psycopg2.connect(
|
||||
dbname="parsed_url",
|
||||
user="postgres",
|
||||
password="qwertyqwerty123123",
|
||||
# host="45.129.78.228",
|
||||
host="127.0.0.1"
|
||||
host="45.129.78.228",
|
||||
# host="127.0.0.1"
|
||||
)
|
||||
conn.autocommit = True
|
||||
|
||||
|
||||
Reference in New Issue
Block a user