Skip to content

Instantly share code, notes, and snippets.

@Mec-iS
Last active December 23, 2015 16:22
Show Gist options
  • Save Mec-iS/735e6c85c4b3e94bb495 to your computer and use it in GitHub Desktop.
Save Mec-iS/735e6c85c4b3e94bb495 to your computer and use it in GitHub Desktop.
# coding=utf-8
__author__ = 'Lorenzo'
from secret import _KEY
def post_curling(url, params, file=None, display=False):
"""
POST to a remote url and print the response in a file or on screen or return the body of the response
:param url: target url
:param params: parameters in the request
:param file: name of the output file
:param display: true if you want to print output on console/command line
:return: file > None, body of the response
"""
import pycurl
from urllib.parse import urlencode
from io import BytesIO
c = pycurl.Curl()
c.setopt(c.URL, url)
# if request is GET
#if params: c.setopt(c.URL, url + '?' + urlencode(params))
# if request is POST
post_data = params
# Form data must be provided already urlencoded.
postfields = urlencode(post_data)
print("Encoded post_fields: " + postfields)
# Sets request method to POST,
# Content-Type header to application/x-www-form-urlencoded
# and data to send in request body.
c.setopt(c.POSTFIELDS, postfields)
c.setopt(pycurl.HTTPHEADER, ["X-Starfighter-Authorization: " + _KEY,
"accept-encoding: gzip",
"content-type: application/json"])
c.setopt(c.FOLLOWLOCATION, True)
c.setopt(c.SSL_VERIFYPEER, 0)
if file and not display:
# if a path is specified, it prints on file
c.setopt(c.WRITEDATA, file)
c.perform()
c.close()
return None
if display:
storage = BytesIO()
c.setopt(c.WRITEFUNCTION, storage.write)
c.perform()
c.close()
print(storage.getvalue())
return None
# else it returns a string
storage = BytesIO()
c.setopt(c.WRITEFUNCTION, storage.write)
c.perform()
c.close()
return storage.getvalue()
def _request(url, data=None):
"""
Build the Request object to send to API.
:param str url: complete endpoint
:param dict data: data for the POST form
:return: Request object
"""
if data:
req = urllib.request.Request(
url,
urllib.parse.urlencode(data).encode("utf-8"),
{
"X-Starfighter-Authorization": _KEY,
"accept-encoding": "gzip",
"content-type": "application/json"
}
)
else:
req = urllib.request.Request(url)
return req
def _response(request):
"""
Open the URL in the Request object.
:param Request request: a urllib Request object
:return tuple: (content, http_code)
"""
with urllib.request.urlopen(request) as response:
status = response.getcode()
print(status, response.info(), )
data = json.loads(
response.read().decode('utf-8')
)
print(data)
import time
time.sleep(0.5)
if status == 200:
return data, status
else:
raise ConnectionFault('client._response() - Connection Error: ' + str(response.getcode()))
req = _request(
self.url_to_order,
post_data
)
response, _ = _response(req)
# POST data:
# {'qty': 100, 'orderType': 'limit', 'price': 7919, 'account': 'BAG26160395', 'direction': 'buy'}
# URL
# https://api.stockfighter.io/ob/api/venues/EOVHEX/stocks/WLI/orders
post_curling(self.url_to_order, post_data, display=True)
# Encoded post_fields:
# qty=100&orderType=limit&price=7919&account=BAG26160395&direction=buy
# Response body:
# b'{"ok":false,"error":"invalid character \'q\' looking for beginning of value"}'
# {'qty': 100, 'account': 'NS82906148', 'orderType': 'limit', 'price': 3070, 'direction': 'buy'}
# https://api.stockfighter.io/ob/api/venues/WESNEX/stocks/FSIM/orders
# b'qty=100&account=NS82906148&orderType=limit&price=3070&direction=buy'
# Response Header
"""
200 Server: nginx/1.8.0
Date: Wed, 23 Dec 2015 16:20:40 GMT
Content-Type: application/json
Content-Length: 75
Connection: close
Strict-Transport-Security: max-age=31536000; includeSubdomains
"""
# Response body:
# {'error': "invalid character 'q' looking for beginning of value", 'ok': False}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment