Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Rory committed Aug 7, 2019
0 parents commit 3e3ed0b
Show file tree
Hide file tree
Showing 9 changed files with 277 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
build/
dist/
reqREST.egg-info/
*.pyc
37 changes: 37 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
language: python
python:
- '3.6'
jobs:
include:
- stage: Test
install:
- python -m pip install -r requirements.txt
- python -m pip install pytest-cov coveralls
script:
- python -m pytest reqREST/Tests/ --cov=./ -v
after_success:
- coveralls
- stage: Deploy to PyPI
env:
secure: RxvIhfUEBfTgmsOyFgvaQFBjcANEVyIZqJxqLoBgXmKjEVMXR8fe/nZFmXfzvWFZWrpgsO7AsEuT4ngjUVMlb9/ab3IAL0fjVzcJeZZAoUA6KtWNkfZYqiZHh1wr8uo4sNxWvywKyIbbbpKLPQz7G0jI0QMWyqxOqHF4OQKrZW0wFg36mtyS6IsPjq00zppR6JNn/QtyNnFFxx6caEQmUAESgf6Lwm+ytu4w2oDKLbFqiHxMteyUlGrVZVwwNcwYLhIHKg5mccHqkjltgJ/aIaV7O4gJ2nzUAz+EefOu4BYuaYTXwkJ+HSDKZOoN/aK4uKctTDb4KBtFBSYCNibWE8hByIiCJmFQSA07n1BWqwLcG/mYzjqOlqxWVtvvV71iCzua17ua9ukuAWoFYNyu1hRu1VvX1IWgeIIHQ4Kf1qZXYePNRfpwu0qjMx4g/6MGR8O46JLefJZKU11GltrQ+oTU6FhanZrWVeca+UgnsAZDSWmTb8Id09v9XUYJ1yrnVgtIc+/jIfKVgfcfO2Bpiuv8o0CUbpBEFh+0uc4ostGV6rnL5q6J2ZoZm32i8b6+56Wlay0JwfSX1BTBYIQ57b2E+3Qf1QGlM+m4RlX9iWxbFR1xe6fVudNIpx6oTgI8iqhvfJEkZMQc5Wvnvw6k6m6kjVRDQPWfhdKqFclDxs4=
language: python
python: 3.6
script:
- git remote rm origin
- git remote add origin https://${GITHUB_TOKEN}@github.com/rorymurdock/reqREST.git >/dev/null 2>&1
- git fetch
- git checkout master
- python3 increment_version.py
- git add -u
- git commit -m "[ci skip] version changed"
- git push --set-upstream origin master >/dev/null 2>&1
deploy:
provider: pypi
user: rorymurdock
password:
secure: "wX8IKmjBW2kpalwpHoEEJKqok6xVb5JdvphsTD33oOiRlPNPxI/leK10LkoM3kSxXW9/SvchpGMGbF7a74qudfIpAp3d2wEx9UpY4Fv9rZ7GYUPa+LDV14G8nUOmsKNbyD7U3w2AmzI+AkjVmJ2GEaB/LTav1wz9FJBU/EnQcRrp5ql8s9S5hyTlwjkRKgtNPykg4axUk79lsqDh3SPUhiFcsqb7zHUZJ+wawebmSwnREchmff089DWD57wYfo2nEaW0IxUSvrRe6oOHN/677Ggk03GwALDHibB11yUebKlrH2cCsljRE6yhjXDOvWb7jxGKjkK6b0WFjf2+W8J3FhcuJjkuCf2drOMAt2dJjJzoAV1uOelDVAkS5bFw1Tl0M0b1s/YGVNRN7RBBe4/HIDM9u+3t5ZGx90UY7n1ewCIn/039PxikBxAOSJRd9nNZMsPq6smOWUbiMzQOec7NA1IzYW4umdkoI3pZpafwLOo1JoXUzGhV355lr1lO7vEZvVLshC94s/Oa9cNwmo8V2hy6hAi/1F1MbEjI/s7YFvtWEZS2doqH/bPLtm+SBLi8UAvim7oW2YU26xVsyv+xeJd248aCFqC3ab4yEon62QPu9k12QqkDlDWc6aPYrsxrsPZusSFQPUAOUTJk+4RFTD6Y0oFZmN1EfRLUKXqLpqI="

stages:
- test
- name: Deploy to PyPI
if: "(branch = master)"
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#reqREST
[![Build Status](https://travis-ci.org/rorymurdock/reqREST.svg?branch=master)](https://travis-ci.org/rorymurdock/reqREST)
[![Maintainability](https://api.codeclimate.com/v1/badges/ae2db247ebaa2ed83ea3/maintainability)](https://codeclimate.com/github/rorymurdock/reqREST/maintainability)
[![Coverage Status](https://coveralls.io/repos/github/rorymurdock/reqREST/badge.svg?branch=master)](https://coveralls.io/github/rorymurdock/reqREST?branch=master)
[![Requirements Status](https://requires.io/github/rorymurdock/reqREST/requirements.svg?branch=master)](https://requires.io/github/rorymurdock/reqREST/requirements/?branch=master)
27 changes: 27 additions & 0 deletions increment_version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import re
import os

# Open setup fule
f = open("setup.py", "r")

for line in f:
# Find the version line
if "version=" in line:

# Regex the old version out
version = re.match(r'(.*)version=\"(\d).(\d).(\d)\"',line,re.M|re.I)

# Assign individually so we can increment the micro
major = int(version.group(2))
minor = int(version.group(3))
micro = int(version.group(4))

old_version = "%i.%i.%i" % (major, minor, micro)
new_version = "%i.%i.%i" % (major, minor, micro+1)

print("Old version: %s" % old_version)
print("Incrementing to %s" % new_version)

# Sed / replace any instances of old version with the new version
if os.system("sed -i 's/%s/%s/g' setup.py" % (old_version, new_version)):
print("Version update successfully")
106 changes: 106 additions & 0 deletions reqREST/Tests/reqREST_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
"""Test for reqREST"""
import json
import random
import string
from reqREST import REST as RESTAPI

# Thanks to https://postman-echo.com
# For the demo REST API

REST = RESTAPI(url='postman-echo.com', debug=True)

# Generate random data for testing
def random_string(string_length=15):
"""Generate a random string of fixed length """
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(string_length))

def test_rest_get():
"""Test GET"""
test_param1 = random_string()
test_param1_value = random_string()
test_param2 = random_string()
test_param2_value = random_string()

query_string = {}
query_string[test_param1] = test_param1_value
query_string[test_param2] = test_param2_value

response = REST.get('/get', query_string)

assert response.status_code == 200

response = json.loads(response.text)['args']

assert response[test_param1] == test_param1_value
assert response[test_param2] == test_param2_value

def test_rest_post():
"""Test POST"""
test_title = random_string()
test_body = random_string()
test_user_id = random_string()

payload = {}
payload['title'] = test_title
payload['body'] = test_body
payload['userId'] = test_user_id

response = REST.post("/post", payload)

assert response.status_code == 200

response = json.loads(response.text)['data']

assert response['userId'] == test_user_id
assert response['title'] == test_title
assert response['body'] == test_body

def test_rest_put():
"""Test PUT"""
test_title = random_string()
test_body = random_string()
test_user_id = random_string()

payload = {}
payload['title'] = test_title
payload['body'] = test_body
payload['userId'] = test_user_id

response = REST.put("/put", payload)

assert response.status_code == 200

response = json.loads(response.text)['form']

print(response)

assert response['userId'] == test_user_id
assert response['title'] == test_title
assert response['body'] == test_body

def test_rest_delete():
"""Test DELETE"""
response = REST.delete('/delete')
assert response.status_code == 200

def test_response_headers():
"""Test getting response headers"""
response = REST.response_headers('/get')

assert response['Content-Type'] == 'application/json; charset=utf-8'
assert response['Connection'] == 'keep-alive'
assert response['Server'] == 'nginx'

def test_custom_header():
"""Test header override"""
header_content = random_string()
header_key = random_string()

headers = {header_key: header_content}

crest = RESTAPI(url='postman-echo.com', headers=headers, debug=True)

response = json.loads(crest.get('/headers').text)

assert response['headers'][header_key] == header_content
2 changes: 2 additions & 0 deletions reqREST/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
name = 'reqREST'
from .reqREST import REST
70 changes: 70 additions & 0 deletions reqREST/reqREST.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import logging
import requests
from requests.adapters import HTTPAdapter
from urllib3.util import Retry

# Used for all AW REST API queries
class REST():
"""REST API Framework"""

# Add the varibles as self.
def __init__(self, url='', protocol='https', timeout=10, retries=5, headers=None, proxy=None, debug=False):
# Import Proxy Server settings
self.proxies = proxy
self.url = url
self.debug = debug
self.timeout = timeout
self.retries = retries
self.protocol = protocol

# Start the session
self.sessions = requests.Session()
if isinstance(headers, dict):
self.sessions.headers.update(headers)

retries = Retry(total=self.retries, backoff_factor=1, status_forcelist=[502, 503, 504])
self.sessions.mount('%s://' % protocol, HTTPAdapter(max_retries=retries))

# Debugging
if self.debug:
print('API URL: %s' % self.url)
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

# HTTP GET, returns HTTP response object
def get(self, path, queries=""):
"HTTP GET"
connection = self.sessions.get(
self.protocol+'://'+self.url+path, proxies=self.proxies, timeout=self.timeout, params=queries)
return connection

# HTTP POST, returns HTTP response object
def post(self, path, payload=None, queries=""):
"""HTTP POST"""
connection = self.sessions.post(
self.protocol+'://'+self.url+path, json=payload, proxies=self.proxies, timeout=self.timeout, params=queries)
return connection

# HTTP PUT, returns HTTP response object
def put(self, path, payload, queries=""):
"""HTTP PUT"""
connection = self.sessions.put(
self.protocol+'://'+self.url+path, data=payload, proxies=self.proxies, timeout=self.timeout, params=queries)
return connection

# HTTP DELETE, returns HTTP response object
def delete(self, path, queries=""):
"""HTTP DELETE"""
connection = self.sessions.delete(
self.protocol+'://'+self.url+path, proxies=self.proxies, timeout=self.timeout, params=queries)
return connection

# HTTP GET, returns response headers json
def response_headers(self, path, queries=""):
"""Gets response headers"""
connection = self.sessions.get(
self.protocol+'://'+self.url+path, proxies=self.proxies, timeout=self.timeout, params=queries)
return connection.headers
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
requests>=2.21.0
25 changes: 25 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import setuptools

with open("README.md", "r") as fh:
long_description = fh.read()

setuptools.setup(
name="reqREST",
version="0.0.4",
author="Rory Murdock",
author_email="rory@itmatic.com.au",
description="A REST API wrapper for requests",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/rorymurdock/reqREST",
packages=setuptools.find_packages(),
classifiers=[
"Development Status :: 5 - Production/Stable",
"Programming Language :: Python :: 3",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
],
install_requires=[
'requests',
],
)

0 comments on commit 3e3ed0b

Please sign in to comment.