-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Hw19.2 #28
Open
vladspirin
wants to merge
2
commits into
main
Choose a base branch
from
HW19.2
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Hw19.2 #28
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
from flask import Flask, request, jsonify, send_from_directory | ||
import os | ||
|
||
app = Flask(__name__) | ||
|
||
upload_directory = './uploads' | ||
if not os.path.exists(upload_directory): | ||
os.makedirs(upload_directory) | ||
|
||
|
||
@app.route('/upload', methods=['POST']) | ||
def upload_image(): | ||
if 'image' not in request.files: | ||
return jsonify({'error': 'No image provided'}), 400 | ||
|
||
image = request.files['image'] | ||
if image.filename == '': | ||
return jsonify({'error': 'No selected file'}), 400 | ||
|
||
filename = os.path.join(upload_directory, image.filename) | ||
image.save(filename) | ||
|
||
return jsonify({'image_url': request.host_url + 'uploads/' + image.filename}), 201 | ||
|
||
|
||
@app.route('/image/<filename>', methods=['GET']) | ||
def get_image(filename): | ||
content_type = request.headers.get('Content-Type') | ||
filepath = os.path.join(upload_directory, filename) | ||
if os.path.exists(filepath): | ||
if content_type == 'text': | ||
return jsonify({'image_url': request.host_url + 'uploads/' + filename}), 200 | ||
elif content_type == 'image': | ||
return send_from_directory(upload_directory, filename) | ||
else: | ||
return jsonify({'error': 'Unsupported Content-Type'}), 400 | ||
else: | ||
return jsonify({'error': 'Image not found'}), 404 | ||
|
||
|
||
@app.route('/delete/<filename>', methods=['DELETE']) | ||
def delete_image(filename): | ||
filepath = os.path.join(upload_directory, filename) | ||
if not os.path.exists(filepath): | ||
return jsonify({'error': 'Image not found'}), 404 | ||
|
||
os.remove(filepath) | ||
return jsonify({'message': f'Image {filename} deleted'}), 200 | ||
|
||
|
||
if __name__ == '__main__': | ||
host = '127.0.0.1' | ||
port = 8080 | ||
app.run(host=host, port=port, debug=True) |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,107 @@ | ||
""" | ||
HW 19.2. POST/GET/DELETE. | ||
|
||
In the Python virtual environment (venv), | ||
install Flask using the command pip install flask. | ||
Create a file named app.py in a separate directory | ||
and copy the code for app.py provided in the initial data. | ||
Run the HTTP server using the command python app.py. | ||
The server will start at the base address http://127.0.0.1:8080. | ||
|
||
Using the documentation provided below, write code that: | ||
1. Uses the requests module to perform a POST request | ||
to upload an image to the server. | ||
2. Retrieves the link to this file using a GET request. | ||
3. Deletes the file from the server using a DELETE request. | ||
""" | ||
|
||
import logging | ||
|
||
import requests | ||
from requests.exceptions import HTTPError, Timeout | ||
|
||
# Configure logging | ||
logging.basicConfig( | ||
level=logging.INFO, | ||
format='%(asctime)s - %(levelname)s - %(message)s', | ||
) | ||
_log = logging.getLogger(__name__) | ||
|
||
|
||
def upload_to_server(base_url: str, file: str): | ||
"""Upload file to the server.""" | ||
try: | ||
with open(file, 'rb') as fh: | ||
files = {'image': (file, fh, 'image/png')} | ||
upload_url = f'{base_url}/upload' | ||
response = requests.post(upload_url, files=files, timeout=5) | ||
response.raise_for_status() | ||
_log.info(f'Server response: {response.json()}') | ||
return response | ||
|
||
except HTTPError as http_err: | ||
_log.error(f'HTTP error: {http_err}') | ||
except Timeout as time_err: | ||
_log.error(f'Timeout error: {time_err}') | ||
except FileNotFoundError as file_err: | ||
_log.error(f'File not found: - {file_err}') | ||
except Exception as err: | ||
_log.error(f'An unexpected error occurred: {err}') | ||
|
||
|
||
def get_file_info(base_url: str, file: str, content_type: str): | ||
"""Get file info from the server.""" | ||
try: | ||
full_url = f'{base_url}/image/{file}' | ||
headers = {'Content-Type': content_type} | ||
response = requests.get(full_url, headers=headers, timeout=5) | ||
response.raise_for_status() | ||
|
||
if content_type == 'text': | ||
_log.info(f'Server response: {response.json()}') | ||
return response.json() | ||
|
||
elif content_type == 'image': | ||
with open(file, 'wb') as img_fh: | ||
img_fh.write(response.content) | ||
_log.info(f'File downloaded: {file}') | ||
return file | ||
|
||
except HTTPError as http_err: | ||
_log.error(f'HTTP error: {http_err}') | ||
except Timeout as time_err: | ||
_log.error(f'Timeout error: {time_err}') | ||
except Exception as err: | ||
_log.error(f'An unexpected error occurred: {err}') | ||
|
||
|
||
def delete_from_server(base_url: str, file: str): | ||
"""Delete file from server.""" | ||
try: | ||
headers = {'Content-Type': 'image'} | ||
full_url = f'{base_url}/delete/{file}' | ||
response = requests.delete(full_url, headers=headers, timeout=5) | ||
response.raise_for_status() | ||
_log.info(f'Server response: {response.json()}') | ||
return response.json() | ||
|
||
except HTTPError as http_err: | ||
_log.error(f'HTTP error: {http_err}') | ||
except Timeout as time_err: | ||
_log.error(f'Timeout error: {time_err}') | ||
except Exception as err: | ||
_log.error(f'An unexpected error occurred: {err}') | ||
|
||
|
||
if __name__ == '__main__': | ||
base_addr = 'http://127.0.0.1:8080' | ||
filename = 'HLIT.png' | ||
|
||
_log.info('POST request') | ||
upload_to_server(base_addr, filename) | ||
|
||
_log.info('GET request') | ||
get_file_info(base_addr, filename, 'text') | ||
|
||
_log.info('DELETE request') | ||
delete_from_server(base_addr, filename) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Better to add helper function do_request and put all request error handling there. No sense to keep duplicate code for upload/get/delete operations
Other error handling like FileNotFound could be placed to main block