Your Streamlit application is well-structured and covers essential functionalities for interacting with an API, processing data, and providing user-friendly features like progress bars and error handling. Below is a comprehensive review of your code, highlighting strengths, potential issues, and suggestions for improvements.
1. Imports and Dependencies
Strengths:
- Comprehensive Imports: You've included all necessary libraries for your application's functionalities, such as
streamlit for the web interface, requests for API interactions, pandas for data manipulation, and loguru for logging.
Suggestions:
-
Deprecation Warning:
-
Unused Imports:
- Check for Unused Imports: Ensure all imported modules are used. For instance, if
sys isn't being used, consider removing it to clean up the code.
2. Logging Setup
Strengths:
- Using
loguru: loguru is a powerful and user-friendly logging library. Setting up a log file with rotation ensures logs are manageable.
Suggestions:
- Sensitive Information Logging:
3. Configuration Handling (read_config Function)
Strengths:
- Robust Error Handling: Checks if the configuration file exists and validates the presence of essential keys.
Suggestions:
4. Utility Functions
get_headers Function
- Simplicity: Correctly constructs the authorization headers.
check_internet Function
- Effectiveness: Uses a reliable method to check internet connectivity by attempting a socket connection to Google's DNS.
Suggestions:
- Timeout Handling:
- Enhanced Feedback: Provide more detailed feedback or alternative messages based on different exceptions (e.g., DNS failure vs. timeout).
5. Data Fetching (get_all_borrowers Function)
Strengths:
- Caching with
@st.cache_data: Efficiently caches data to prevent redundant API calls.
- Progress Indicators: Utilizes Streamlit's progress bar and status text to inform users about the fetching process.
- Retry Mechanism: Implements retries with exponential backoff for handling transient API errors.
Issues & Suggestions:
-
@st.cache_data Usage:
- Potential Problem: Caching this function means that repeated runs with different parameters (like
limit, delay) won't reflect until cache is cleared.
- Recommendation: If the data can change frequently, consider adding a cache expiration time or using
st.cache_resource if applicable.
-
Progress Bar Calculation:
-
Paging Logic:
- Current Approach: Increments
offset by limit and breaks when fewer records than limit are returned.
- Potential Improvement: Confirm if the API provides total count or a next page URL, which can make the pagination more reliable.
-
Error Handling & Retries:
- Current Retry Count: Has a separate
max_retries logic alongside Retry in the adapter.
- Recommendation: Consolidate retry logic to avoid confusion. Either rely on
Retry from the adapter or manage retries manually, but not both.
-
Session Handling:
- Efficiency: Reusing a
requests.Session is good for performance. Ensure that session configurations (like retries) are correctly applied.
6. Data Cleaning and Saving (clean_value and save_to_csv Functions)
Strengths:
- Data Sanitization: The
clean_value function effectively removes unwanted characters and normalizes whitespace.
- Excluding Specific Fields: Ability to exclude certain fields from the CSV export, enhancing data privacy and relevance.
Issues & Suggestions:
-
save_to_csv Function:
-
CSV Writing Logic:
- Field Order: Using
sorted(set().union(*filtered_data)) can lead to unpredictable column ordering.
- Recommendation: Define a consistent column order, possibly based on a predefined schema or order them as they appear in the first record.
-
Error Handling:
- Empty Data: Already handled by checking
if not data, which is good.
- Potential Enhancements: Consider handling specific exceptions related to CSV writing, such as encoding issues.
7. Excel Data Processing (process_excel_data Function)
Strengths:
- Flexible INN Detection: Attempts to find the INN column by name and falls back to searching the first column if not found.
- Regular Expression Use: Employs regex to extract valid INN numbers (10-12 digits).
Issues & Suggestions:
-
INN Length Validation:
- Clarification: Ensure that the INN lengths (10 for organizations, 12 for individuals) are correctly validated based on your application's requirements.
-
Multiple INNs per Cell:
-
Performance Considerations:
- Large Files: For very large Excel files, reading the entire file into memory might be inefficient.
- Recommendation: Consider processing the file in chunks or using more efficient data structures if performance becomes an issue.
-
User Feedback:
- Enhanced Messaging: Inform users about the total number of rows processed, skipped, or any anomalies found during processing.
8. Data Posting (post_data Function)
Strengths:
- Comprehensive Error Handling: Differentiates between HTTP errors (like 405) and other request exceptions, providing specific feedback.
Suggestions:
9. Main Application Logic (main Function)
Strengths:
- User-Friendly Interface: Clear separation of functionalities via the sidebar, with appropriate headers and interactive elements.
- Progress Indicators: Provides real-time feedback to users during data fetching and posting operations.
- Session State Usage: Correctly uses
st.session_state to manage data persistence across interactions.
Issues & Suggestions:
-
Session State Initialization:
-
CSV Download Logic:
- Current Implementation: The CSV is generated on button click and then provided via
st.download_button.
- Potential Issue: The CSV generation might be unnecessarily repeated if not cached.
- Recommendation: Cache the CSV generation if it's computation-heavy or ensure it's only generated once per data fetch.
-
API Endpoint Consistency:
- Fetch URL:
url = f"{API_URL}/account/deals/borrowers?limit={limit}&offset={offset}"
- Post URL:
response = session.post(url, headers=headers, json=data, timeout=10)
Where url is:
f"{API_URL}/account/deals/borrowers"
- Verification: Ensure that the POST endpoint is correct and distinct from the GET endpoint. Some APIs use different endpoints for fetching vs. posting data.
-
Error Messaging:
- Enhancement: Provide users with actionable messages. For example, if saving to CSV fails due to data issues, inform them of specific corrections needed.
-
Concurrency and Performance:
- Large Data Sets: If users upload large Excel files, posting each INN sequentially can be time-consuming.
- Recommendation: Implement parallel processing with caution to enhance performance. Libraries like
concurrent.futures can help, but ensure it doesn't conflict with Streamlit's execution model.
-
Localization and Language:
- Current State: The application uses Russian for labels and messages.
- Suggestion: If your user base is multilingual, consider implementing language support to cater to a broader audience.
10. General Best Practices and Enhancements
Code Organization:
- Modularization: Break down the script into multiple modules or separate files (e.g.,
config.py, api.py, utils.py) for better maintainability.
- Docstrings and Comments: Add docstrings to functions explaining their purpose, parameters, and return values. This enhances readability and maintainability.
Security Considerations:
- Input Validation: Ensure that all user inputs, especially from uploaded files, are validated to prevent potential security vulnerabilities.
- API Token Protection: Besides not logging the token, consider restricting token permissions to the minimum required and rotating tokens regularly.
User Experience (UX):
- Responsive Design: Ensure the application is responsive and looks good on various screen sizes.
- Feedback Mechanisms: After long-running operations, provide users with options to cancel or pause the process if needed.
Testing:
- Unit Tests: Implement unit tests for critical functions to ensure reliability.
- Error Simulation: Test how the application behaves under different error scenarios, such as API downtime, invalid file uploads, etc.
Revised Code Snippets and Enhancements
Below are some revised code snippets addressing the issues and suggestions mentioned above.
1. Updating the Retry Import:
# from requests.packages.urllib3.util.retry import Retry # Remove this line
from urllib3.util import Retry # Add this line
2. Improving save_to_csv Function:
def save_to_csv(data):
if not data:
logger.error("Нет данных для сохранения в CSV.")
st.error("Нет данных для сохранения в CSV.")
return None
output = StringIO()
writer = csv.writer(output, quoting=csv.QUOTE_MINIMAL)
# Define fields to exclude
exclude_fields = {'type', 'level', 'title', 'checklist'}
# Determine the structure of data (list of dicts or list of lists)
if all(isinstance(item, dict) for item in data):
# Handle list of dictionaries
filtered_data = []
for item in data:
filtered_item = {k: v for k, v in item.items() if k not in exclude_fields}
if filtered_item:
filtered_data.append(filtered_item)
if filtered_data:
fieldnames = sorted(set().union(*filtered_data))
writer.writerow(fieldnames)
for record in filtered_data:
writer.writerow([clean_value(record.get(field, '')) for field in fieldnames])
elif all(isinstance(item, list) for item in data):
# Handle list of lists (if applicable)
# Assuming first row is header
headers = data[0]
filtered_headers = [h for h in headers if h not in exclude_fields]
writer.writerow(filtered_headers)
for row in data[1:]:
filtered_row = [clean_value(value) for value, header in zip(row, headers) if header not in exclude_fields]
writer.writerow(filtered_row)
else:
logger.error("Неизвестный формат данных для CSV сохранения.")
st.error("Неизвестный формат данных для CSV сохранения.")
return None
output.seek(0)
return output.getvalue()
Explanation of Changes:
- Set for Exclude Fields: Changed
exclude_fields to a set for faster lookup.
- Consistent Data Structure Handling: Checks if all items are dictionaries or lists and handles them accordingly.
- Header Handling for Lists: Assumes the first row is headers if the data is a list of lists.
- Error Messaging: Provides clear error messages if the data structure is unexpected.
3. Enhancing get_all_borrowers Function:
@st.cache_data(show_spinner=False)
def get_all_borrowers(limit=250, delay=5, max_retries=3):
all_data = []
offset = 0
retries = 0
progress_bar = st.progress(0)
status_text = st.empty()
session = requests.Session()
retry_strategy = Retry(
total=max_retries,
backoff_factor=1,
status_forcelist=[500, 502, 503, 504],
method_whitelist=["GET"]
)
adapter = HTTPAdapter(max_retries=retry_strategy)
session.mount('https://', adapter)
session.mount('http://', adapter)
while True:
try:
url = f"{API_URL}/account/deals/borrowers?limit={limit}&offset={offset}"
logger.info(f"Запрос к URL: {url}")
response = session.get(url, headers=get_headers(), timeout=30)
logger.info(f"Ответ API: {response.status_code}")
response.raise_for_status()
data = response.json()
logger.debug(f"Исходный ответ API: {data}")
# Extract data based on known structure
if isinstance(data, dict):
if 'results' in data:
data = data['results']
elif 'data' in data:
data = data['data']
else:
data = data # Use as is
if not data:
logger.info("Больше данных не получено.")
break
if isinstance(data, list):
all_data.extend(data)
elif isinstance(data, dict):
all_data.append(data)
else:
logger.error(f"Неожиданный формат данных: {type(data)}")
break
logger.info(f"Получено {len(data)} записей.")
status_text.text(f"Получено {len(all_data)} записей.")
progress = len(all_data) / 1000 # Adjust based on expected total
progress_bar.progress(min(progress, 1.0))
offset += limit
if len(data) < limit:
logger.info("Данные закончились.")
break
time.sleep(delay)
except requests.exceptions.RequestException as e:
logger.error(f"Ошибка запроса API: {e}")
retries += 1
if retries > max_retries:
logger.error("Превышено максимальное количество попыток.")
status_text.text("Превышено максимальное количество попыток.")
break
logger.info(f"Повтор после ошибки запроса. Попытка {retries}/{max_retries}")
status_text.text(f"Повтор... Попытка {retries}/{max_retries}")
time.sleep(delay * 2)
logger.info(f"Всего получено записей: {len(all_data)}")
status_text.text(f"Всего получено записей: {len(all_data)}")
return all_data
Explanation of Changes:
- Retry Strategy Adjustment: Increased
backoff_factor to 1 for a more reasonable delay between retries.
- Method Whitelist Update: Ensured that only
GET methods are retried since this function primarily performs GET requests.
- Progress Bar Labeling: Consider adjusting the progress bar to use dynamic progress based on total records if known.
- Error Handling Consistency: Ensured that all exceptions related to requests are caught and handled uniformly.
4. Implementing Asynchronous Requests for Posting Data
To improve the performance of the "Отправить данные в API" section, especially when dealing with a large number of INNs, you can implement asynchronous requests. Here's how you can modify the post_data function and the corresponding part in the main function using asyncio and aiohttp.
Note: Streamlit doesn't natively support asyncio, so integrating asynchronous code requires careful handling. Below is a synchronous alternative using concurrent.futures.ThreadPoolExecutor for simplicity.
from concurrent.futures import ThreadPoolExecutor, as_completed
def post_data(session, url, headers, inn):
data = {"inn": inn}
try:
response = session.post(url, headers=headers, json=data, timeout=10)
response.raise_for_status()
return True
except requests.exceptions.HTTPError as err:
if err.response.status_code == 405:
logger.error(f"Ошибка 405 Method Not Allowed для ИНН {inn}. Проверьте настройки API.")
st.error(f"Ошибка 405 Method Not Allowed для ИНН {inn}. Проверьте настройки API.")
else:
logger.error(f"Ошибка отправки данных для ИНН {inn}: {err}")
st.error(f"Ошибка отправки данных для ИНН {inn}: {err}")
return False
except requests.exceptions.RequestException as err:
logger.error(f"Ошибка отправки данных для ИНН {inn}: {err}")
st.error(f"Ошибка отправки данных для ИНН {inn}: {err}")
return False
def main():
# ... [existing code] ...
elif page == "Обработать Excel-данные":
st.header("Обработка Excel-данных")
uploaded_file = st.file_uploader("Выберите Excel-файл", type="xlsx")
if uploaded_file is not None:
st.info("Файл загружен. Обработка...")
data = process_excel_data(uploaded_file)
if data:
st.success(f"Excel-файл успешно обработан. Найдено {len(data)} ИНН.")
st.write(data[:10]) # Показываем первые 10 ИНН
if st.button("Отправить данные в API"):
progress_bar = st.progress(0)
status_text = st.empty()
session = requests.Session()
retry_strategy = Retry(
total=5,
backoff_factor=0.1,
status_forcelist=[500, 502, 503, 504],
method_whitelist=["POST"]
)
adapter = HTTPAdapter(max_retries=retry_strategy)
session.mount('https://', adapter)
session.mount('http://', adapter)
headers = get_headers()
successful_count = 0
failed_count = 0
with ThreadPoolExecutor(max_workers=10) as executor:
future_to_inn = {
executor.submit(post_data, session, f"{API_URL}/account/deals/borrowers", headers, inn): inn
for inn in data
if inn and inn.isdigit()
}
total = len(future_to_inn)
for i, future in enumerate(as_completed(future_to_inn), 1):
inn = future_to_inn[future]
try:
result = future.result()
if result:
successful_count += 1
else:
failed_count += 1
except Exception as exc:
logger.error(f"Исключение для ИНН {inn}: {exc}")
failed_count += 1
progress = i / total
progress_bar.progress(progress)
status_text.text(f"Обработано {i}/{total} ИНН")
st.success(f"Отправка данных завершена: {successful_count} успешных, {failed_count} неудачных")
else:
st.error("Не удалось обработать Excel-файл. Пожалуйста, проверьте формат и содержимое файла.")
Explanation of Changes:
- Thread Pool Executor: Utilizes a thread pool to perform multiple POST requests concurrently, significantly speeding up the process.
- Progress Tracking with
as_completed: Updates the progress bar as each future completes, providing real-time feedback.
- Error Handling Within Executor: Catches exceptions raised within threads and logs them appropriately.
Caution:
- API Rate Limits: Ensure that the API can handle concurrent requests. Adjust
max_workers accordingly to respect API rate limits and prevent being throttled or blocked.
- Thread Safety:
requests.Session is generally thread-safe, but confirm based on your specific use case and environment.
11. Additional Recommendations
Documentation:
- User Guide: Provide a brief user guide or tooltips within the application to help users understand how to use each feature.
- Code Documentation: Add docstrings to all functions explaining their purpose, parameters, and return values.
Testing and Validation:
- Unit Tests: Implement unit tests for critical functions like
get_all_borrowers, process_excel_data, and post_data to ensure they handle various scenarios correctly.
- Integration Tests: Test the entire flow from data fetching to posting to ensure seamless integration.
Deployment Considerations:
- Environment Variables: Use environment variables for configuration, especially for sensitive data like API tokens.
- Dockerization: Consider containerizing your application using Docker for consistent deployment environments.
- Performance Monitoring: Implement monitoring to track the application's performance and identify bottlenecks or issues in real-time.
User Interface Enhancements:
- Dynamic Column Selection: Allow users to select which columns to display or exclude in the data table.
- Search and Filtering: Implement search and filtering capabilities within the displayed data for easier navigation.
Conclusion
Your application demonstrates a solid foundation with clear functionalities and thoughtful error handling. By addressing the suggestions and potential issues highlighted above, you can enhance the robustness, performance, and user experience of your Streamlit app. Remember to continuously test and gather user feedback to iterate and improve the application further.
If you have specific questions or need assistance with particular parts of the code, feel free to ask!