Skip to content

Commit

Permalink
Initial Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
lewiswatson55 committed Oct 5, 2023
0 parents commit 472213a
Show file tree
Hide file tree
Showing 8 changed files with 335 additions and 0 deletions.
8 changes: 8 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

123 changes: 123 additions & 0 deletions docs.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
# Code Documentation

This is a Python Flask application that logs incoming HTTP requests to files. It provides several routes for different purposes.

## Routes

### Index Route

```python
@app.route('/', methods=['GET', 'POST'])
@app.route('/log', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
save_request(request.data, subdirectory='request_logs')
return "Logged request data successfully"
else:
return "Hello, World!", 200
```

- The index route ("/" or "/log") accepts both GET and POST requests.
- If a POST request is received, it calls the `save_request` function to save the request data to a file in the "request_logs" subdirectory.
- If a GET request is received, it returns the message "Hello, World!" with a status code 200.

### Log Route

```python
@app.route('/log/<log_name>', methods=['GET', 'POST'])
def log(log_name):
if request.method == 'POST':
save_request(request.data, subdirectory=str(log_name))
return "Logged request data successfully into {}".format(log_name)
else:
return "womp womp, not a post request.", 418
```

- The log route ("/log/<log_name>") accepts both GET and POST requests.
- The `<log_name>` parameter in the route is a placeholder for the name of the log.
- If a POST request is received, it calls the `save_request` function to save the request data to a file in a subdirectory with the name of `<log_name>`.
- If a GET request is received, it returns the message "womp womp, not a post request." with a status code 418 (I'm a teapot).

### Dummy Route

```python
@app.route('/dummy', methods=['GET', 'POST'])
def dummy():
if request.method == 'POST':
save_request(request.data, subdirectory='dummy')
return "ko", 200
else:
return render_template('dummy.html')
```

- The dummy route ("/dummy") accepts both GET and POST requests.
- If a POST request is received, it calls the `save_request` function to save the request data to a file in the "dummy" subdirectory.
- If a GET request is received, it renders a template called "dummy.html".

### Complete Route

```python
@app.route('/complete')
def complete():
return render_template('complete.html')
```

- The complete route ("/complete") only accepts GET requests.
- It renders a template called "complete.html".

## Helper Function

### save_request

```python
def save_request(request_data, subdirectory='request_logs'):
print("Received request data:", request_data)

# Generate a unique ID for the file name
id = str(datetime.datetime.now().strftime("%Y%m%d%H%M%S%f"))

# Get current month and year
current_month = datetime.datetime.now().strftime("%B")
current_year = datetime.datetime.now().strftime("%Y")

# Create subdirectory if it doesn't exist under the base directory
base_directory = 'requests'
subdirectory_path = os.path.join(base_directory, subdirectory)
if not os.path.exists(subdirectory_path):
os.makedirs(subdirectory_path)

# Create year directory if it doesn't exist under the subdirectory
year_directory = os.path.join(subdirectory_path, current_year)
if not os.path.exists(year_directory):
os.makedirs(year_directory)

# Create month directory if it doesn't exist under the year directory
month_directory = os.path.join(year_directory, current_month)
if not os.path.exists(month_directory):
os.makedirs(month_directory)

# Save the request data to a file
file_path = os.path.join(month_directory, "{}.txt".format(id))
with open(file_path, 'w') as f:
f.write(str(request_data))

return 0
```

- The `save_request` function is responsible for saving the incoming request data to a file in a specified subdirectory.
- It takes the request data as input and an optional `subdirectory` parameter (default value is 'request_logs').
- It generates a unique ID for the file name using the current timestamp.
- It gets the current month and year.
- It creates the subdirectory, year directory, and month directory if they don't exist under the base directory.
- It saves the request data to a file in the month directory with the generated ID as the file name.
- It returns 0 as a placeholder value.

## Running the Application

```python
if __name__ == '__main__':
app.run(debug=True)
```

- This block of code is the entry point for running the Flask application.
- It runs the application in debug mode if the script is executed directly and not imported as a module.
79 changes: 79 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
from flask import Flask, render_template, request, redirect, url_for
import os
import datetime

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
@app.route('/log', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
save_request(request.data, subdirectory='request_logs')
return "Logged request data successfully"
else:
return "Hello, World!", 200


# Path for specific logging i.e log/<log_name> will save the request data to a file with the name <log_name>
@app.route('/log/<log_name>', methods=['GET', 'POST'])
def log(log_name):
if request.method == 'POST':
save_request(request.data, subdirectory=str(log_name))
return "Logged request data successfully into {}".format(log_name)
else:
#save_request(request.data, subdirectory=str(log_name)) # testinf get requests
return "womp womp, not a post request.", 418


# Render dummy form for testing
@app.route('/dummy', methods=['GET', 'POST'])
def dummy():
if request.method == 'POST':
# dump
save_request(request.data, subdirectory='dummy')
return "ko", 200 # redirect to complete page
else:
return render_template('dummy.html')

# Completion page after dummy form submission
@app.route('/complete')
def complete():
return render_template('complete.html')

# Function to save incoming request data to a file for logs
def save_request(request_data, subdirectory='request_logs'):
print("Received request data:", request_data)

id = str(datetime.datetime.now().strftime("%Y%m%d%H%M%S%f"))

# Get current month and year
current_month = datetime.datetime.now().strftime("%B")
current_year = datetime.datetime.now().strftime("%Y")

# Create subdirectory if it doesn't exist under the base directory
base_directory = 'requests'
subdirectory_path = os.path.join(base_directory, subdirectory)
if not os.path.exists(subdirectory_path):
os.makedirs(subdirectory_path)

# Create year directory if it doesn't exist under the subdirectory
year_directory = os.path.join(subdirectory_path, current_year)
if not os.path.exists(year_directory):
os.makedirs(year_directory)

# Create month directory if it doesn't exist under the year directory
month_directory = os.path.join(year_directory, current_month)
if not os.path.exists(month_directory):
os.makedirs(month_directory)

# Save the request data to a file
file_path = os.path.join(month_directory, "{}.txt".format(id))
with open(file_path, 'w') as f:
f.write(str(request_data))

return 0


if __name__ == '__main__':
app.run(debug=True)

37 changes: 37 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Flask Request Logger

This is a simple Flask application that logs incoming HTTP requests to files. It allows you to specify different subdirectories for organizing the logged requests.

## Documentation

Please refer to the [Documentation](https://github.com/lewiswatson55/flask-request-logger/docs.md) for detailed information about the code and its usage.

## Installation

1. Clone the repository:

```shell
git clone https://github.com/lewiswatson55/flask-request-logger.git
```

2. Install the required dependencies:

```shell
pip install -r requirements.txt
```

## Usage

1. Start the Flask application:

```shell
python app.py
```

2. Access the application in your web browser at `http://localhost:5000`.

3. Use the provided routes to log requests or test the dummy form.

## Contributions

Contributions are welcome! If you find any issues or would like to suggest new features, please open an issue or submit a pull request.
1 change: 1 addition & 0 deletions requests/dummy/2023/October/20231005143851815370.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
b'{"name":"Test","email":"Test@test.com","age":69}'
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
flask
19 changes: 19 additions & 0 deletions templates/complete.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html>
<head>
<title>Submission Complete</title>
<!-- Add Bootstrap CSS link -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-5">
<h1>Submission Complete</h1>
<p>Your data has been successfully submitted.</p>
<p><a href="/" class="btn btn-primary">Go Back</a></p>
</div>

<!-- Add Bootstrap JS and jQuery scripts -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
67 changes: 67 additions & 0 deletions templates/dummy.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<!DOCTYPE html>
<html>
<head>
<title>JSON Form with Bootstrap</title>
<!-- Add Bootstrap CSS link -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-5">
<h1>Enter Data</h1>
<form id="dataForm">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name">
</div>

<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" id="email" name="email">
</div>

<div class="form-group">
<label for="age">Age:</label>
<input type="number" class="form-control" id="age" name="age">
</div>

<button type="button" class="btn btn-primary" onclick="submitData()">Submit</button>
</form>

<div id="result" class="mt-3"></div>
</div>

<!-- Add Bootstrap JS and jQuery scripts -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<script>
function submitData() {
const formData = {
name: document.getElementById('name').value,
email: document.getElementById('email').value,
age: parseInt(document.getElementById('age').value),
};

fetch(window.location.href, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(response => {
if (response.status === 200) {
// Redirect to 'complete.html' after successful POST
window.location.href = '/complete'; // Update the URL as needed
} else {
// Handle other responses or errors here
}
})
.catch(error => {
// Handle fetch errors here
});
}
</script>

</body>
</html>

0 comments on commit 472213a

Please sign in to comment.