Skip to content
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

Доп. задача #1

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
# created by virtualenv automatically
env/
.idea/
Pipfile
.pytest_cache
.coverage
5 changes: 5 additions & 0 deletions enums/client_messages_response.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import enum


class ClientMessagesResponse(enum.Enum):
incorrect_url_or_port = 'Incorrect URL-address or port'
9 changes: 9 additions & 0 deletions enums/requests_names.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import enum


class RequestsNames(enum.Enum):
get = 'get'
post = 'post'
patch = 'patch'
delete = 'delete'
put = 'put'
10 changes: 10 additions & 0 deletions enums/server_validating_messages.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import enum


class ServerValidatingMessages(enum.Enum):
incorrect_url = 'You did not write URL-address'
incorrect_type_request = 'You did not write type of request'
incorrect_format_cookie = 'Incorrect format cookie: type of object which takes cookie must be dictionary'
incorrect_format_headers = 'Incorrect format headers: type of object which takes headers must be dictionary'
incorrect_body_type = 'Incorrect format of body: type of object which takes body is string'
is_validated = 'All parameters is valid'
24 changes: 15 additions & 9 deletions client/http_client.py → http_client.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import socket

from enums.client_messages_response import ClientMessagesResponse


class HttpClient:
def __init__(self, settings: dict):
self.__settings = settings
self._settings = settings

self.__HOST = self.__settings.get("url")
self.__PORT = int(self.__settings.get("port"))
self._HOST = self._settings.get("url")
self._PORT = self._settings.get("port")

def get_data(self) -> str:
"""
Expand All @@ -17,13 +19,17 @@ def get_data(self) -> str:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
timeout = 10

if self.__settings.get("timeout") is not None:
timeout = self.__settings.get("timeout")
if self._settings.get("timeout") is not None:
timeout = self._settings.get("timeout")

s.settimeout(timeout)
s.connect((self.__HOST, self.__PORT))

request = self.create_http_request(self.__settings).encode()
try:
s.connect((self._HOST, int(self._PORT)))
except ValueError:
return str(ClientMessagesResponse.incorrect_url_or_port.value)

request = self.create_http_request(self._settings).encode()

try:
s.sendall(request)
Expand All @@ -45,7 +51,7 @@ def get_data(self) -> str:
except Exception as e:
print('log: ' + str(e))

close_request = self.create_http_close_request(self.__settings).encode()
close_request = self.create_http_close_request(self._settings).encode()

try:
s.sendall(close_request)
Expand Down Expand Up @@ -75,7 +81,7 @@ def get_headers(settings: dict) -> str:
cookies.append(f'{key}={value};')

if len(cookies) != 0:
cookies = 'Cookie: ' + ' '.join(cookies)
cookies = 'Cookie: ' + ' '.join(cookies)
cookies = cookies[:-1]
cookies += '\r\n'
headers.append(cookies)
Expand Down
3 changes: 1 addition & 2 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@

from server.server import HttpServer
from server import HttpServer

if __name__ == '__main__':
server = HttpServer()
server.start()

140 changes: 75 additions & 65 deletions resources/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -20,25 +20,26 @@
</head>

<body>
<div class="form_wrapper">
<h1 class="form-title">HTTP-Client</h1>
<p class="error-message">Ошибка! Вы не ввели либо url, либо port, либо тип запроса!</p>
<div class="container form-container">
<form class="form">
<div class="wrapper url_wrapper">
<label id="url_label" for="url">Url-адрес: </label>
<input id="url" class="url" type="text" name="url" placeholder="Введите url...">
</div>
<div class="wrapper port_wrapper">
<label id="port_label" for="port">Порт: </label>
<input id="port" class="port" type="text" name="port" placeholder="Введите port...">
</div>
<div class="wrapper timeout_wrapper">
<label id="timeout_label" for="timeout">Таймаут: </label>
<input id="timeout" class="timeout" type="text" name="timeout" placeholder="Введите таймаут ожидания запроса...">
</div>
<div class="wrapper request_wrapper">
<div class="request-title">Тип запроса: </div>
<div class="form_wrapper">
<h1 class="form-title">HTTP-Client</h1>
<p class="error-message">Ошибка! Вы не ввели либо url, либо port, либо тип запроса!</p>
<div class="container form-container">
<form class="form">
<div class="wrapper url_wrapper">
<label id="url_label" for="url">Url-адрес: </label>
<input id="url" class="url" type="text" name="url" placeholder="Введите url...">
</div>
<div class="wrapper port_wrapper">
<label id="port_label" for="port">Порт: </label>
<input id="port" class="port" type="text" name="port" placeholder="Введите port...">
</div>
<div class="wrapper timeout_wrapper">
<label id="timeout_label" for="timeout">Таймаут: </label>
<input id="timeout" class="timeout" type="text" name="timeout" placeholder="Введите таймаут ожидания запроса...">
</div>
<div class="wrapper request_wrapper">
<div class="request-title">Тип запроса: </div>
<div class="request_btns">
<div class="request-btn_container">
<div class="request-container">
<div class="request-btn_wrapper">
Expand Down Expand Up @@ -67,59 +68,68 @@ <h1 class="form-title">HTTP-Client</h1>
</div>
</div>
</div>
</div>
<div class="wrapper headers_wrapper">
<div class="label-container">
<label for="headers" id="headers_label">Заголовки:</label>
<p class="warning_wrapper">
<span class="warning_important">*</span>
Заголовки должны быть записаны в формате:<br>
<span class="warning_ex">Заголовок: значение;</span>
<span class="warning_note">И обязательно должны быть разделены точкой с запятой</span>
</p>
</div>
<textarea
name="headers"
id="headers"
class="headers-textarea"
placeholder="Впишите суда заголовки..."
name="get_form"
id="get_form"
cols="30"
rows="10"
class="get_form"
placeholder="Введите строку, вхождения которой вы хотите найти..."
></textarea>
</div>
<div class="wrapper cookie_wrapper">
<div class="label-container">
<label for="cookie" id="cookie_label">Cookie:</label>
<p class="warning_wrapper">
<span class="warning_important">*</span>
Cookie должны быть записаны в формате:<br>
<span class="warning_ex">Название: значение;</span>
<span class="warning_note">И обязательно должны быть разделены точкой с запятой</span>
</p>
</div>
<textarea
name="cookie"
id="cookie"
class="cookie-textarea"
placeholder="Впишите суда Cookie..."
></textarea>
</div>
<div class="wrapper headers_wrapper">
<div class="label-container">
<label for="headers" id="headers_label">Заголовки:</label>
<p class="warning_wrapper">
<span class="warning_important">*</span>
Заголовки должны быть записаны в формате:<br>
<span class="warning_ex">Заголовок: значение;</span>
<span class="warning_note">И обязательно должны быть разделены точкой с запятой</span>
</p>
</div>
<div class="wrapper body_wrapper">
<label for="body" id="body_label">Тело запроса:</label>
<textarea
name="body"
id="body"
class="body-textarea"
placeholder="Впишите суда тело запроса..."
></textarea>
<textarea
name="headers"
id="headers"
class="headers-textarea"
placeholder="Впишите суда заголовки..."
></textarea>
</div>
<div class="wrapper cookie_wrapper">
<div class="label-container">
<label for="cookie" id="cookie_label">Cookie:</label>
<p class="warning_wrapper">
<span class="warning_important">*</span>
Cookie должны быть записаны в формате:<br>
<span class="warning_ex">Название: значение;</span>
<span class="warning_note">И обязательно должны быть разделены точкой с запятой</span>
</p>
</div>
<button class="submit-btn" type="submit">Сделать запрос</button>
</form>
</div>
<div class="result">
<div class="container result-container">
<h1 class="result__title">Результат запроса:</h1>
<p class="result__text"></p>
<textarea
name="cookie"
id="cookie"
class="cookie-textarea"
placeholder="Впишите суда Cookie..."
></textarea>
</div>
<div class="wrapper body_wrapper">
<label for="body" id="body_label">Тело запроса:</label>
<textarea
name="body"
id="body"
class="body-textarea"
placeholder="Впишите суда тело запроса..."
></textarea>
</div>
<button class="submit-btn" type="submit">Сделать запрос</button>
</form>
</div>
<div class="result">
<div class="container result-container">
<h1 class="result__title">Результат запроса:</h1>
<p class="result__text"></p>
</div>
</div>
</div>
</body>
</html>
37 changes: 27 additions & 10 deletions resources/main.css
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,24 @@ textarea::placeholder {
width: 35%;
}

.request_btns {
display: flex;
align-items: flex-start;
justify-content: space-between;

width: 100%;
}

.get_form {
display: none;

margin-left: 15px;
}

.get_form__active {
display: block;
}

/* Wrappers styles */

.form_wrapper {
Expand Down Expand Up @@ -255,13 +273,7 @@ textarea::placeholder {
/* Result styles */

.result-container {
flex-direction: column;
}

.result__text {
font-size: 15px;
color: #333;
font-weight: 400;
flex-direction: column;
}

.result {
Expand All @@ -281,8 +293,13 @@ textarea::placeholder {
}

.result__text {
width: 100%;
font-size: 15px;
color: #333;
font-weight: 400;

width: 100%;

hyphens: auto;
white-space: pre-wrap;
hyphens: auto;
white-space: pre-wrap;
word-wrap: break-word;
}
37 changes: 28 additions & 9 deletions resources/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ const onSubmit = (event) => {

const body = JSON.stringify(fields)

if (fields.request !== 'get') {
fields.get_form = ''
}

fetch('http://127.0.0.1:8080/', {
method: 'post',
headers: {
Expand All @@ -58,16 +62,19 @@ const onSubmit = (event) => {
})
.then(response => response.text())
.then(data => {
const result_text = document.querySelector('.result__text');
result_text.textContent = data;
const result_text = document.querySelector('.result__text');

const jsonResponse = JSON.parse(data)

const result = document.querySelector('.result');
result_text.textContent = JSON.stringify(jsonResponse)

if (!result.classList.contains('result-active')) {
result.classList.add('result-active')
const result = document.querySelector('.result');

if (!result.classList.contains('result-active')) {
result.classList.add('result-active')
}
}
}
);
);

return true
}
Expand Down Expand Up @@ -117,6 +124,18 @@ const parse = (headers) => {
return response.length === 0 ? {} : response
}

window.addEventListener('load', () => {
const radioBtnChecker = e => {
if (e.target.tagName.toLowerCase() === 'input' && e.target.id.toLowerCase() === 'get-request') {
document.querySelector('#get_form').classList.add('get_form__active');
return null
}

document.querySelector('#get_form').classList.remove('get_form__active');
}

const main = () => {
document.querySelector('.form').addEventListener('submit', onSubmit)
})
document.querySelector('.request-btn_container').addEventListener('click', radioBtnChecker)
}

window.addEventListener('load', main)
Loading