Лабораторная №3: сокеты, запросы и API

This commit is contained in:
Александр Мамаев 2026-05-23 23:55:22 +03:00
parent 338a87723e
commit 377fe851f8
8 changed files with 148 additions and 1 deletions

2
.gitignore vendored
View File

@ -1,4 +1,4 @@
venv/
__pycache__/
.env
*.pyc
*.pyc

View File

@ -0,0 +1,20 @@
# Лабораторная 3: socket и requests
## Подготовка окружения
- python -m venv venv
- venv\Scripts\activate (или source venv/bin/activate)
- pip install requests
## TCP/UDP серверы и клиенты
- tcp_server.py / tcp_client.py — обмен строками по TCP на порту 10000
- udp_server.py / udp_client.py — обмен строками по UDP на порту 10001
## HTTP через socket
- http_client_socket.py — GET / к vyatsu.ru через socket, порт 80
## HTTP через requests
- http_client_requests.py — GET к http://vyatsu.ru через библиотеку requests
## Git API
- git_api.py — запрос к https://git.vyatsu.ru/api/v1/user
- Требуется переменная окружения GIT_VYATSU_TOKEN с токеном (read-only)

View File

@ -0,0 +1,15 @@
import os
import requests
def main():
token = os.environ.get("GIT_VYATSU_TOKEN_READ")
if not token:
raise RuntimeError("Переменная окружения GIT_VYATSU_TOKEN_READ не установлена")
headers = {"Authorization": f"token {token}"}
response = requests.get("https://git.vyatsu.ru/api/v1/user", headers=headers)
print("Status code:", response.status_code)
print(response.json())
if __name__ == "__main__":
main()

31
git_create_repo.py Normal file
View File

@ -0,0 +1,31 @@
import os
import requests
def main():
token = os.environ.get("GIT_VYATSU_TOKEN_WRITE")
if not token:
raise RuntimeError("Переменная окружения GIT_VYATSU_TOKEN_WRITE не установлена")
headers = {
"Authorization": f"token {token}",
"Content-Type": "application/json"
}
data = {
"name": "practice03-api-mamaev",
"description": "Репозиторий создан через API Gitea для лабораторной работы",
"private": False,
"auto_init": True
}
response = requests.post(
"https://git.vyatsu.ru/api/v1/user/repos",
headers=headers,
json=data
)
print("Status code:", response.status_code)
print(response.json())
if __name__ == "__main__":
main()

View File

@ -0,0 +1,16 @@
import requests
def main():
url = "http://vyatsu.ru"
response = requests.get(url)
print("Status code:", response.status_code)
print("Headers:")
for k, v in response.headers.items():
print(f"{k}: {v}")
print("\nBody snippet:")
print(response.text[:500])
if __name__ == "__main__":
main()

View File

@ -0,0 +1,30 @@
import socket
HOST = "vyatsu.ru"
PORT = 80
def main():
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))
request = (
"GET / HTTP/1.1\r\n"
f"Host: {HOST}\r\n"
"Connection: close\r\n"
"\r\n"
)
client.sendall(request.encode())
response = b""
while True:
chunk = client.recv(4096)
if not chunk:
break
response += chunk
print(response.decode(errors="ignore"))
client.close()
if __name__ == "__main__":
main()

View File

@ -0,0 +1,18 @@
import socket
HOST = "127.0.0.1"
PORT = 10001
def main():
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
msg = input("Введите сообщение (EXIT для выхода): ")
client.sendto(msg.encode(), (HOST, PORT))
data, _ = client.recvfrom(1024)
print(f"Ответ от сервера: {data.decode()}")
if msg.upper() == "EXIT":
break
client.close()
if __name__ == "__main__":
main()

View File

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