This error occurs when you're trying to run asyncio code in an environment that already has an event loop running (like Jupyter notebooks, IPython, or some web frameworks). Here are several solutions:
Solution 1: Use await directly (for Jupyter/IPython)
If you're in a Jupyter notebook or IPython, you can run async code directly:
python
# Instead of asyncio.run(main()), just use:
await main()
Solution 2: Use nest_asyncio (Quick Fix)
Install and use nest_asyncio to allow nested event loops:
python
import nest_asyncio
nest_asyncio.apply()
# Now you can use asyncio.run()
asyncio.run(main())
Solution 3: Check for Existing Event Loop
python
import asyncio
async def main():
# Your async code here
pass
# Check if there's already an event loop running
try:
loop = asyncio.get_running_loop()
except RuntimeError: # No running loop
asyncio.run(main())
else:
# If loop exists, create a task
loop.create_task(main())
Solution 4: Use Threading Approach Instead
Since you're having issues with asyncio, the threading approach might be simpler and more suitable:
python
import math
import pandas as pd
from concurrent.futures import ThreadPoolExecutor, as_completed
from tqdm import tqdm
import time
import requests # or whatever library you're using for API calls
total_items_num = 100
count = 20
files_count = math.ceil(total_items_num / count)
def fetch_all_packages(total, offset, count):
# Your actual API call here
# Example with requests:
# response = requests.get(f"https://api.example.com/packages?offset={offset}&limit={count}")
# return response.json()
# Mock implementation
time.sleep(0.1)
return [(f"package_{i+offset}", f"version_{i+offset}") for i in range(count)]
def fetch_and_save(idx):
offset = idx * count
current_page_limit = min(count, total_items_num - offset)
try:
packages_chunk = fetch_all_packages(total=total_items_num, offset=offset, count=current_page_limit)
filename = f"all_packages_p{idx+1}.xlsx"
df = pd.DataFrame(packages_chunk)
df.rename(columns={0: 'packageName', 1: 'version'}, inplace=True)
df.to_excel(filename, index=False)
return filename
except Exception as e:
print(f"Error in chunk {idx}: {str(e)}")
return None
def main():
results = []
with ThreadPoolExecutor(max_workers=10) as executor:
futures = {executor.submit(fetch_and_save, idx): idx for idx in range(files_count)}
for future in tqdm(as_completed(futures), total=files_count):
result = future.result()
if result:
results.append(result)
print("Все файлы успешно созданы.")
print("Created files:", results)
if __name__ == "__main__":
main()
Solution 5: For Jupyter Notebooks Specifically
If you're in a Jupyter notebook and want to use asyncio, here's a complete working example:
python
import math
import pandas as pd
import asyncio
from tqdm.notebook import tqdm # Use notebook version of tqdm
import aiohttp
total_items_num = 100
count = 20
files_count = math.ceil(total_items_num / count)
async def fetch_all_packages(session, total, offset, count):
# Your actual async API call here
# async with session.get(f"https://api.example.com/packages?offset={offset}&limit={count}") as response:
# return await response.json()
# Mock implementation
await asyncio.sleep(0.1)
return [(f"package_{i+offset}", f"version_{i+offset}") for i in range(count)]
async def fetch_and_save(session, idx):
offset = idx * count
current_page_limit = min(count, total_items_num - offset)
try:
packages_chunk = await fetch_all_packages(session, total=total_items_num, offset=offset, count=current_page_limit)
filename = f"all_packages_p{idx+1}.xlsx"
df = pd.DataFrame(packages_chunk)
df.rename(columns={0: 'packageName', 1: 'version'}, inplace=True)
df.to_excel(filename, index=False)
return filename
except Exception as e:
print(f"Error in chunk {idx}: {str(e)}")
return None
async def main():
async with aiohttp.ClientSession() as session:
tasks = [fetch_and_save(session, idx) for idx in range(files_count)]
results = []
for future in tqdm(asyncio.as_completed(tasks), total=files_count):
result = await future
if result:
results.append(result)
print("Все файлы успешно созданы.")
print("Created files:", results)
# In Jupyter, just run:
await main()
Recommendation
Given the complexity of asyncio in certain environments, I'd recommend using the threading approach (Solution 4) for your use case. It's:
Simpler to implement
Works in all environments
Sufficient for most REST API scenarios
Easier to debug
Only use asyncio if you need to handle hundreds or thousands of concurrent requests. For typical API pagination scenarios with 10-20 concurrent requests, threading is perfectly adequate and much simpler to work with.
User
Here is an actual fetch_all_packages function, please implement it in code
all_packages = []
# Прогрессбар для визуализации загрузки
with tqdm(total=total, desc="Загрузка пакетов") as pbar:
for i in range(total):
# offset = i * count
request_params = {
"offset": offset,
"count": count,
"packageStatusId": 4 # Фильтр по статусу пакета
}
if params:
request_params.update(params)
response = requests.get(
base_url,
params=request_params,
headers=headers,
verify=False
)
# Проверка статуса HTTP-запроса
if response.status_code != 200:
raise Exception(f"Ошибка API: {response.text}")
response_json = response.json()
# Извлекаем данные по пакетам
for item in response_json.get('data', []):
properties = item.get('properties', {})
# Извлекаем название пакета и версию с защитой от отсутствия ключей
package_name = properties.get('packageName', '')
version = properties.get('version', '')
# Добавляем в множество уникальные пары (packageName, version)
if package_name or version:
all_packages.append((package_name, version))
# Обновляем прогрессбар
pbar.update(1)
return all_packages # Возвращаем множество уникальных пакетов
Assistant
Looking at your fetch_all_packages function, I see several issues that need to be fixed:
The function has a loop that runs total times, but it's using the same offset value each time
The progress bar is inside the function, which will conflict with the outer progress bar
The function should fetch only one chunk of data, not all packages
Here's the corrected implementation with the threading approach:
python
import math
import pandas as pd
from concurrent.futures import ThreadPoolExecutor, as_completed
from tqdm import tqdm
import requests
import warnings
# Suppress SSL warnings if you're using verify=False
warnings.filterwarnings('ignore', message='Unverified HTTPS request')
total_items_num = 100 # Adjust this to your actual total
count = 20 # Items per page
files_count = math.ceil(total_items_num / count)
def fetch_all_packages(total, offset, count=10, params=None):
"""Fetch a single chunk of packages from the API"""
base_url = "https://tip.sigma.sbrf.ru/api/entities/package"
headers = {
"Content-Type": "application/json",
"token": "cA"
}
request_params = {
"offset": offset,
"count": count,
"packageStatusId": 4 # Filter by package status
}
if params:
request_params.update(params)
try:
response = requests.get(
base_url,
params=request_params,
headers=headers,
verify=False
)
# Check HTTP status
if response.status_code != 200:
raise Exception(f"API Error: {response.text}")
response_json = response.json()
# Extract package data
packages = []
for item in response_json.get('data', []):
properties = item.get('properties', {})
# Extract package name and version with default values
package_name = properties.get('packageName', '')
version = properties.get('version', '')
# Add to list if at least one field is present
if package_name or version:
packages.append((package_name, version))
return packages
except requests.exceptions.RequestException as e:
print(f"Request error for offset {offset}: {str(e)}")
raise
except Exception as e:
print(f"Error processing response for offset {offset}: {str(e)}")
raise
def fetch_and_save(idx):
"""Fetch a chunk of packages and save to Excel file"""
offset = idx * count
current_page_limit = min(count, total_items_num - offset)
try:
# Fetch packages chunk
packages_chunk = fetch_all_packages(
total=total_items_num,
offset=offset,
count=current_page_limit
)
# Save to Excel file
filename = f"all_packages_p{idx+1}.xlsx"
df = pd.DataFrame(packages_chunk)
df.rename(columns={0: 'packageName', 1: 'version'}, inplace=True)
df.to_excel(filename, index=False)
return filename, len(packages_chunk)
except Exception as e:
print(f"Error in chunk {idx}: {str(e)}")
return None, 0
def main():
"""Main function to orchestrate parallel fetching"""
print(f"Starting to fetch {total_items_num} items in {files_count} chunks...")
successful_files = []
total_fetched = 0
# Use ThreadPoolExecutor for concurrent API requests
with ThreadPoolExecutor(max_workers=5) as executor: # Reduced workers to avoid overwhelming the API
# Submit all tasks
futures = {executor.submit(fetch_and_save, idx): idx for idx in range(files_count)}
# Process completed tasks with progress bar
for future in tqdm(as_completed(futures), total=files_count, desc="Processing chunks"):
result, items_count = future.result()
if result:
successful_files.append(result)
total_fetched += items_count
print(f"\nВсе файлы успешно созданы.")
print(f"Total items fetched: {total_fetched}")
print(f"Created files: {successful_files}")
# Optional: Combine all files into one
if len(successful_files) > 1:
combine_files(successful_files)
def combine_files(filenames):
"""Optional: Combine all Excel files into one"""
try:
all_dfs = []
for filename in filenames:
df = pd.read_excel(filename)
all_dfs.append(df)
combined_df = pd.concat(all_dfs, ignore_index=True)
combined_df.to_excel("all_packages_combined.xlsx", index=False)
print(f"Combined file created: all_packages_combined.xlsx")
except Exception as e:
print(f"Error combining files: {str(e)}")
if __name__ == "__main__":
main()
Key improvements made:
Fixed the fetch_all_packages function:
Removed the unnecessary loop that was fetching the same data multiple times
Removed the internal progress bar that would conflict with the outer one
Made it fetch only one chunk as intended
Added proper error handling:
Catches both network errors and API errors
Returns meaningful error messages
Reduced concurrent workers:
Changed from 10 to 5 workers to avoid overwhelming the API
You can adjust this based on the API's rate limits
Added SSL warning suppression:
Since you're using verify=False, this suppresses the warnings
Added optional file combination:
At the end, all files can be combined into one master file
Better progress tracking:
Shows how many items were actually fetched
Lists all successfully created files
Additional Recommendations:
Add retry logic for failed requests:
python
from tenacity import retry, stop_after_attempt, wait_exponential
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
def fetch_all_packages(...):
# your code here
Add rate limiting if needed:
python
import time
# In fetch_all_packages, add:
time.sleep(0.1) # 100ms delay between requests
Consider using sessions for better performance:
python
# Create a session that's reused across requests
session = requests.Session()
session.headers.update(headers)
session.verify = False
This implementation should work much better with your actual API and handle the concurrent requests properly.