Created
September 8, 2023 17:41
-
-
Save mwestwood/3ce98e591b1357d6ec9d5a248accf6ba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
import os | |
import threading | |
from flask import Flask, jsonify | |
app = Flask(__name__) | |
# Create a lock to serialize access to the log file | |
log_file_lock = threading.Lock() | |
# Flag to track if a request is in progress | |
request_in_progress = False | |
@app.route('/') | |
def my_endpoint(): | |
global request_in_progress | |
# Check if a request is already in progress | |
if request_in_progress: | |
return jsonify({"message": "A request is already in progress. Please try again later."}) | |
# Set the request_in_progress flag to True | |
request_in_progress = True | |
try: | |
# Generate a unique log filename for this request, e.g., based on a timestamp or request ID | |
log_filename = f"my_log_{get_unique_id()}.log" | |
# Acquire the lock to prevent concurrent access to the log file | |
with log_file_lock: | |
# Check if the log file already exists | |
if os.path.exists(log_filename): | |
app.logger.warning("Log file already exists; skipping log creation.") | |
else: | |
# Create a new FileHandler for this request | |
file_handler = logging.FileHandler(log_filename) | |
# Configure the log format, level, and attach the handler to the logger | |
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s") | |
file_handler.setFormatter(formatter) | |
file_handler.setLevel(logging.DEBUG) | |
app.logger.addHandler(file_handler) | |
# Log a message | |
app.logger.info("This log message will be written to a new file.") | |
# Remove the handler from the logger to prevent further writing | |
app.logger.removeHandler(file_handler) | |
# Close the handler to release the log file | |
file_handler.close() | |
# Now, you can safely read the log file without further writing | |
with open(log_filename, 'r') as file: | |
log_contents = file.read() | |
return "Request processed successfully." | |
finally: | |
# Reset the request_in_progress flag to False when the request is completed | |
request_in_progress = False | |
if __name__ == '__main__': | |
app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment