Добавили все файлы

This commit is contained in:
Марина Лехмак 2026-05-07 16:21:53 +03:00
parent d2af5aef8e
commit 9eead39eec
9 changed files with 129 additions and 1 deletions

4
.gitignore vendored
View File

@ -159,4 +159,6 @@ cython_debug/
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
.idea
.venv
.env

62
3lb/gittea_api.py Normal file
View File

@ -0,0 +1,62 @@
import os
import requests
from dotenv import load_dotenv
# Подгружаем настройки
load_dotenv()
API_TOKEN = os.getenv("GITEA_TOKEN")
BASE_URL = "https://git.vyatsu.ru/api/v1"
if not API_TOKEN:
raise ValueError("Критическая ошибка: GITEA_TOKEN отсутствует в .env")
# Настраиваем сессию, чтобы не прописывать headers каждый раз
session = requests.Session()
session.headers.update({
"Authorization": f"token {API_TOKEN}",
"Accept": "application/json"
})
def get_profile_info():
"""Проверка подключения к серверу"""
print("[*] Соединение с сервером git.vyatsu.ru...")
try:
response = session.get(f"{BASE_URL}/user")
response.raise_for_status()
user_data = response.json()
print(f"[+] Авторизация пройдена: {user_data.get('full_name')} (@{user_data.get('login')})")
except requests.exceptions.RequestException as e:
print(f"[-] Сбой подключения: {e}")
def deploy_new_repository(name):
"""Регистрация нового проекта в Gitea"""
print(f"[*] Попытка регистрации проекта '{name}'...")
settings = {
"name": name,
"description": "Автоматически созданный репозиторий (Lab Net)",
"private": False,
"auto_init": True,
"readme": "Default"
}
resp = session.post(f"{BASE_URL}/user/repos", json=settings)
if resp.status_code == 201:
repo_url = resp.json().get('html_url')
print(f"[Успех] Проект доступен по адресу: {repo_url}")
elif resp.status_code == 422:
print("[!] Внимание: Имя уже занято, выберите другое.")
else:
print(f"[Ошибка] Код ответа: {resp.status_code} | {resp.text}")
if __name__ == "__main__":
# Запускаем диагностику и создание
get_profile_info()
# Можно добавить ввод имени через input для разнообразия
target_name = "lab_work_3_network"
deploy_new_repository(target_name)

5
3lb/http_requests.py Normal file
View File

@ -0,0 +1,5 @@
import requests
response = requests.get("http://vyatsu.ru")
print(response.status_code)
print(response.text[:500])

9
3lb/http_socket.py Normal file
View File

@ -0,0 +1,9 @@
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('vyatsu.ru', 80))
request = "GET / HTTP/1.1\r\nHost: vyatsu.ru\r\n\r\n"
client.sendall(request.encode())
response = client.recv(4096)
print(response.decode())
client.close()

8
3lb/tcp_client.py Normal file
View File

@ -0,0 +1,8 @@
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1', 10000))
client.sendall(b'hello server')
data = client.recv(1024)
print(f"Ответ от сервера: {data.decode()}")
client.close()

21
3lb/tsp_server.py Normal file
View File

@ -0,0 +1,21 @@
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("0.0.0.0", 10000))
server.listen(1)
print("TCP сервер запущен")
while True:
conn, addr = server.accept()
print(f"Подключение от {addr}")
data = conn.recv(1024)
if not data:
break
conn.sendall(data.upper())
conn.close()
if data.upper() == b'EXIT':
break

7
3lb/udp_client.py Normal file
View File

@ -0,0 +1,7 @@
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.sendto(b'hello server', ('127.0.0.1', 10001))
data, _ = client.recvfrom(1024)
print(f"Ответ от сервера: {data.decode()}")
client.close()

10
3lb/udp_server.py Normal file
View File

@ -0,0 +1,10 @@
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(('0.0.0.0', 10001))
print("UDP сервер запущен")
while True:
data, addr = server.recvfrom(1024)
print(f"Сообщение от {addr}: {data.decode()}")
server.sendto(data.upper(), addr)

View File

@ -1,2 +1,6 @@
# 3laba
Работа с сетевыми соединениями в Python