Skip to content

Instantly share code, notes, and snippets.

@mwestwood
Created September 10, 2023 15:34
Show Gist options
  • Save mwestwood/04e6487024aecb6ecf2aae5a23919b5f to your computer and use it in GitHub Desktop.
Save mwestwood/04e6487024aecb6ecf2aae5a23919b5f to your computer and use it in GitHub Desktop.
import logging
import os
from flask import Flask, jsonify
app = Flask(__name__)
# Create a lock file to indicate whether a request is in progress
lock_file_path = "request_lock.lock"
@app.route('/')
def my_endpoint():
# Check if the lock file exists, indicating a request is in progress
if os.path.exists(lock_file_path):
return jsonify({"message": "A request is already in progress. Please try again later."})
# Create the lock file to indicate that a request is in progress
with open(lock_file_path, "w") as lock_file:
lock_file.write("Request in progress")
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 open(log_filename, "w") as log_file:
# 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()
finally:
# Remove the lock file to indicate that the request has completed
os.remove(lock_file_path)
return "Request processed successfully."
if __name__ == '__main__':
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment