Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions scripts/lesson_1/http_request.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import requests
from requests.exceptions import HTTPError
import json


class Http:

def __init__(self, host, protocol):
self.base_url = f'{protocol}://{host}'

def send_request(self, method, relative_url, headers=None, params=None, data=None, json=None):
url = ''.join([self.base_url, relative_url])
result = None
try:
if method is 'GET':
result = self.get_request(url, params, headers)
elif method is 'POST':
result = self.post_request(url, data, headers)
elif method is 'PUT':
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Добавлена развилка для PUT и DELETE запросов. Для каждого варианта необходимо вызвать соответствующую функцию. Например, для PUT должна быть вызвана функция self.put_request(url, data, headers). На данный момент в POST, PUT и DELETE запросах почему-то всегда вызывается одна и та же функция self.post_request(url, data, headers).

result = self.post_request(url, data, headers)
elif method is 'DELETE':
result = self.post_request(url, data, headers)
else:
raise Exception(f"Request type is not defined! Provided type: {method}")
result.raise_for_status()
except HTTPError as err:
print(f'HTTP error occurred: {err}')
return Http.parse_result(result.text)

def get_request(self, url, params, headers):
return requests.get(url, params=params, headers=headers)

def post_request(self, url, data, headers):
return requests.post(url, data=data, headers=headers)

def post_request(self, url, data, headers):
return requests.post(url, data=data, headers=headers)

def post_request(self, url, data, headers):
return requests.post(url, data=data, headers=headers)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Как следствие из предыдущего коммента - зачем-то созданы 3(!) функции с одинаковым именем.

@staticmethod
def parse_result(result):
return json.loads(result) if Http.is_json(result) else result

@staticmethod
def is_json(str):
try:
json.loads(str)
return True
except ValueError:
return False


if __name__ == '__main__':
http = Http('httpbin.org', 'https')
print(f'Sending HTTP requests to {http.base_url}...')
http.send_request('GET', '/get')
http.send_request('POST', '/post', data={'test_key': 'test_value'})
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Отсутствуют вызовы PUT и DELETE запросов.

print(f'HTTP requests to {http.base_url} are successful!')
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Поехала табуляция. В Python необходимо уделять особое внимание отступам, так как в данном языке они являются частью синтаксиса.

Empty file added scripts/lesson_2/__init__.py
Empty file.
91 changes: 91 additions & 0 deletions scripts/lesson_2/github.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
from http_request import Http

TEST_USER = 'smartiqa-test'
# GitHub restricts pushing Authentication Token to public repo
# That's why it's necessary to update it with valid token before running
AUTH_TOKEN = '<Please change me for b4a1d07f32....c5ca8594f>'
TEST_REPO = 'test_repository_2'
TEST_ISSUE_NUM = 3
TEST_COMMIT_SHA = '063b6dde79957b9f34a0a5f74f4febe0e34cbba5'


class API:

HOST = 'api.github.com'
PROTOCOL = 'https'

def __init__(self):
self.http = Http(self.HOST, self.PROTOCOL)

def call(self, method, relative_url, headers=None, json=None):
return self.http.send_request(method, relative_url, headers=headers, json=json)


class User:

def __init__(self, auth_token=None):
self.api = API()
# Majority of the API requests need Authentication Token but not all
if auth_token is not None:
self.headers = {'Authorization': f'token {auth_token}'}

# ------ Get User info without Authentication ------
def get(self, user_name):
return self.api.call('GET', f'/users/{user_name}')

def get_bio(self, user_name):
return self.get(user_name)['bio']

# -- Get additional User info with Authentication --
def get_authenticated(self):
return self.api.call('GET', f'/user', headers=self.headers)

# --------------- Update User info -----------------
def update_bio(self, new_bio):
return self.api.call('PATCH', f'/user', headers=self.headers, json={'bio': new_bio})


class Issue:

def __init__(self, auth_token):
self.api = API()
self.headers = {'Authorization': f'token {auth_token}'}

# ------- List Issues -------------
def list(self):
return self.api.call('GET', '/issues', headers=self.headers)

def list_for_repository(self, owner, repo):
return self.api.call('GET', f'/repos/{owner}/{repo}/issues', headers=self.headers)

# ------- Get Issue info ----------
def get(self, owner, repo, number):
return self.api.call('GET', f'/repos/{owner}/{repo}/issues/{number}', headers=self.headers)

# ------- Edit Issues -------------
def edit_title(self, owner, repo, number, new_title):
return self._edit(owner, repo, number, json={'title': new_title})

def edit_body(self, owner, repo, number, new_body):
return self._edit(owner, repo, number, json={'body': new_body})
# ---------------------------------

def _edit(self, owner, repo, number, json):
return self.api.call('PATCH', f'/repos/{owner}/{repo}/issues/{number}', headers=self.headers, json=json)


if __name__ == '__main__':
# Check GitHub User API functionality
user = User(AUTH_TOKEN)
user.get(TEST_USER)
user.get_bio(TEST_USER)
user.get_authenticated()
user.update_bio('New Test bio')

# Check GitHub Issue API functionality
issue = Issue(AUTH_TOKEN)
issue.list()
issue.list_for_repository(TEST_USER, TEST_REPO)
issue.get(TEST_USER, TEST_REPO, TEST_ISSUE_NUM)
issue.edit_title(TEST_USER, TEST_REPO, TEST_ISSUE_NUM, 'Smartiqa Test issue 3')
issue.edit_body(TEST_USER, TEST_REPO, TEST_ISSUE_NUM, 'Smartiqa Test body 3')
55 changes: 55 additions & 0 deletions scripts/lesson_2/http_request.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import requests
from requests.exceptions import HTTPError
import json


class Http:

def __init__(self, host, protocol):
self.base_url = f'{protocol}://{host}'

def send_request(self, method, relative_url, headers=None, params=None, data=None, json=None):
url = ''.join([self.base_url, relative_url])
result = None
try:
if method is 'GET':
result = self.get_request(url, params, headers)
elif method is 'POST':
result = self.post_request(url, data, headers)
elif method is 'PATCH':
result = self.patch_request(url, json, headers)
else:
raise Exception(f"Request type is not defined! Provided type: {method}")
result.raise_for_status()
except HTTPError as err:
print(f'HTTP error occurred: {err}')
return Http.parse_result(result.text)

def get_request(self, url, params, headers):
return requests.get(url, params=params, headers=headers)

def post_request(self, url, data, headers):
return requests.post(url, data=data, headers=headers)

def patch_request(self, url, json, headers):
return requests.patch(url, json=json, headers=headers)

@staticmethod
def parse_result(result):
return json.loads(result) if Http.is_json(result) else result

@staticmethod
def is_json(str):
try:
json.loads(str)
return True
except ValueError:
return False


if __name__ == '__main__':
http = Http('httpbin.org', 'https')
print(f'Sending HTTP requests to {http.base_url}...')
http.send_request('GET', '/get')
http.send_request('POST', '/post', data={'test_key': 'test_value'})
print(f'HTTP requests to {http.base_url} are successful!')
66 changes: 0 additions & 66 deletions scripts/net_http.py

This file was deleted.