index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
13,095
|
rti/poodle-backend-django
|
refs/heads/main
|
/app/migrations/0003_auto_20201230_2156.py
|
# Generated by Django 3.1.4 on 2020-12-30 21:56
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app', '0002_auto_20201230_1944'),
]
operations = [
migrations.AlterField(
model_name='choice',
name='attendee',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='choices', to='app.attendee'),
),
migrations.AlterField(
model_name='choice',
name='option',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='choices', to='app.option'),
),
migrations.AlterField(
model_name='option',
name='query',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='options', to='app.query'),
),
]
|
{"/app/tests.py": ["/app/models.py"], "/app/views.py": ["/app/serializers.py", "/app/models.py"], "/app/admin.py": ["/app/models.py"], "/app/serializers.py": ["/app/models.py"]}
|
13,096
|
rti/poodle-backend-django
|
refs/heads/main
|
/app/migrations/0004_auto_20201231_1433.py
|
# Generated by Django 3.1.4 on 2020-12-31 14:33
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('app', '0003_auto_20201230_2156'),
]
operations = [
migrations.DeleteModel(
name='Item',
),
migrations.AlterModelOptions(
name='option',
options={},
),
]
|
{"/app/tests.py": ["/app/models.py"], "/app/views.py": ["/app/serializers.py", "/app/models.py"], "/app/admin.py": ["/app/models.py"], "/app/serializers.py": ["/app/models.py"]}
|
13,097
|
rti/poodle-backend-django
|
refs/heads/main
|
/app/serializers.py
|
from rest_framework import serializers
from .models import Query, Option, Choice, Attendee
class EmbeddedChoiceSerializer(serializers.ModelSerializer):
attendee = serializers.SlugRelatedField(read_only=True, slug_field='name')
status = serializers.CharField(read_only=True)
class Meta:
model = Choice
fields = ['id', 'attendee', 'attendee_id', 'status']
class EmbeddedOptionSerializer(serializers.ModelSerializer):
choices = EmbeddedChoiceSerializer(many=True, read_only=True)
begin_date = serializers.DateField(read_only=True)
begin_time = serializers.TimeField(read_only=True)
end_date = serializers.DateField(read_only=True)
end_time = serializers.TimeField(read_only=True)
class Meta:
model = Option
fields = ['id', 'begin_date', 'begin_time',
'end_date', 'end_time', 'choices']
class QuerySerializer(serializers.ModelSerializer):
options = EmbeddedOptionSerializer(many=True, read_only=True)
# choices = ChoiceSerializer(many=True, read_only=True)
class Meta:
model = Query
fields = ('id', 'name', 'options')
# fields = ('id', 'name', 'options', 'choices')
class OptionSerializer(serializers.ModelSerializer):
query_id = serializers.IntegerField()
class Meta:
model = Option
fields = ['id', 'begin_date', 'begin_time', 'end_date', 'end_time', 'query_id']
class ChoiceSerializer(serializers.ModelSerializer):
attendee = serializers.SlugRelatedField(read_only=True, slug_field='name')
attendee_id = serializers.IntegerField()
option_id = serializers.IntegerField()
class Meta:
model = Choice
fields = ['id', 'attendee', 'attendee_id', 'option_id', 'status']
class AttendeeSerializer(serializers.ModelSerializer):
class Meta:
model = Attendee
fields = ['id', 'name']
|
{"/app/tests.py": ["/app/models.py"], "/app/views.py": ["/app/serializers.py", "/app/models.py"], "/app/admin.py": ["/app/models.py"], "/app/serializers.py": ["/app/models.py"]}
|
13,098
|
rti/poodle-backend-django
|
refs/heads/main
|
/app/migrations/0002_auto_20201230_1944.py
|
# Generated by Django 3.1.4 on 2020-12-30 19:44
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Attendee',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=64)),
],
),
migrations.CreateModel(
name='Query',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=512)),
],
options={
'verbose_name_plural': 'Queries',
},
),
migrations.CreateModel(
name='Option',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('begin_date', models.DateField()),
('begin_time', models.TimeField(blank=True, null=True)),
('end_date', models.DateField(blank=True, null=True)),
('end_time', models.TimeField(blank=True, null=True)),
('query', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app.query')),
],
options={
'ordering': ['id'],
},
),
migrations.CreateModel(
name='Choice',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('status', models.CharField(choices=[('Y', 'Yes'), ('N', 'No'), ('M', 'Maybe')], max_length=1)),
('attendee', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app.attendee')),
('option', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app.option')),
],
),
migrations.AddConstraint(
model_name='choice',
constraint=models.UniqueConstraint(fields=('attendee', 'option'), name='unique_choice'),
),
]
|
{"/app/tests.py": ["/app/models.py"], "/app/views.py": ["/app/serializers.py", "/app/models.py"], "/app/admin.py": ["/app/models.py"], "/app/serializers.py": ["/app/models.py"]}
|
13,100
|
kechankrisna/python-test
|
refs/heads/master
|
/python_test/python_test/migrations/0002_auto_20200803_0744.py
|
# Generated by Django 3.0.8 on 2020-08-03 07:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('python_test', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='client',
name='contact_name',
field=models.CharField(blank=True, max_length=50, verbose_name='Contact Name'),
),
migrations.AlterField(
model_name='client',
name='email',
field=models.CharField(blank=True, max_length=100, unique=True, verbose_name='Email'),
),
migrations.AlterField(
model_name='client',
name='phone_number',
field=models.CharField(blank=True, max_length=30, verbose_name='Phone number'),
),
migrations.AlterField(
model_name='client',
name='postcode',
field=models.CharField(blank=True, max_length=10, verbose_name='Postcode'),
),
migrations.AlterField(
model_name='client',
name='state',
field=models.CharField(blank=True, max_length=50, verbose_name='State'),
),
migrations.AlterField(
model_name='client',
name='street_name',
field=models.CharField(blank=True, max_length=50, verbose_name='Street name'),
),
migrations.AlterField(
model_name='client',
name='suburb',
field=models.CharField(blank=True, max_length=50, unique=True, verbose_name='Suburb'),
),
migrations.AlterField(
model_name='client',
name='username',
field=models.CharField(blank=True, max_length=30, unique=True, verbose_name='Name'),
),
]
|
{"/python_test/python_test/filters.py": ["/python_test/python_test/models.py"], "/python_test/python_test/views.py": ["/python_test/python_test/models.py", "/python_test/python_test/filters.py"]}
|
13,101
|
kechankrisna/python-test
|
refs/heads/master
|
/python_test/python_test/filters.py
|
import django_filters as filters
from .models import Client
class ClientFilter(filters.FilterSet):
username = filters.CharFilter(lookup_expr='icontains')
email = filters.CharFilter(lookup_expr='icontains')
phone_number = filters.CharFilter(lookup_expr='icontains')
suburb = filters.CharFilter(lookup_expr='icontains')
class Meta:
model = Client
fields = []
|
{"/python_test/python_test/filters.py": ["/python_test/python_test/models.py"], "/python_test/python_test/views.py": ["/python_test/python_test/models.py", "/python_test/python_test/filters.py"]}
|
13,102
|
kechankrisna/python-test
|
refs/heads/master
|
/python_test/python_test/views.py
|
from django.http import JsonResponse
from django.views.generic import ListView
from django.views.generic.edit import CreateView, UpdateView
from django.urls import reverse_lazy
from django.core import serializers
from .models import Client
from .filters import ClientFilter
class ClientList(ListView):
model = Client
template_name = "list.html"
class ClientCreate(CreateView):
model = Client
fields = [
"username",
"contact_name",
"email",
"phone_number",
"street_name",
"suburb",
"postcode",
"state",
]
template_name = "create.html"
success_url = reverse_lazy("client_list")
class ClientUpdate(UpdateView):
model = Client
fields = [
"username",
"contact_name",
"email",
"phone_number",
"street_name",
"suburb",
"postcode",
"state",
]
template_name = "create.html"
success_url = reverse_lazy("client_list")
def clientFilter(request):
client_filter = ClientFilter(request.GET, queryset=Client.objects.all())
return JsonResponse(serializers.serialize('json', client_filter.qs), safe=False)
|
{"/python_test/python_test/filters.py": ["/python_test/python_test/models.py"], "/python_test/python_test/views.py": ["/python_test/python_test/models.py", "/python_test/python_test/filters.py"]}
|
13,103
|
kechankrisna/python-test
|
refs/heads/master
|
/python_test/python_test/models.py
|
# Insert models here
from django.db import models
class Client(models.Model):
username = models.CharField("Name", max_length=30, unique=True, blank=True)
contact_name = models.CharField("Contact Name", max_length=50, blank=True)
email = models.CharField("Email", max_length=100, unique=True, blank=True)
phone_number = models.CharField("Phone number", max_length=30, blank=True)
street_name = models.CharField("Street name", max_length=50, blank=True)
suburb = models.CharField("Suburb", max_length=50, unique=True, blank=True)
postcode = models.CharField("Postcode", max_length=10, blank=True)
state = models.CharField("State", max_length=50, blank=True)
def __str__(self):
return self.username
|
{"/python_test/python_test/filters.py": ["/python_test/python_test/models.py"], "/python_test/python_test/views.py": ["/python_test/python_test/models.py", "/python_test/python_test/filters.py"]}
|
13,116
|
wpharris92/panorama
|
refs/heads/master
|
/InteractivePanoramaClient.py
|
import zmq.auth as auth
import ssl
from threading import Thread
import cmd
from panorama import PanoramaClient
DEFAULT_MATCH_PERCENT = .5
DEFAULT_NUM_REPLIES = 5
class ClientOptions(cmd.Cmd):
def __init__(self, client):
cmd.Cmd.__init__(self)
self.client = client
prompt = '>> '
def do_request(self, line):
args = line.split(' ')
if not len(args):
print 'Must make request for url'
url = args[0]
num_replies = DEFAULT_NUM_REPLIES
if len(args) > 1:
num_replies = int(args[1])
min_match_percent = DEFAULT_MATCH_PERCENT
if len(args) > 2:
min_match_percent = float(args[2])
try:
i_saw, they_saw = self.client.request(url, num_replies=num_replies)
except Exception as ex:
print 'Failed to make request for %s: %r' % (url, ex)
return False
print 'From this client, saw %r' % i_saw
print 'Other clients saw %r' % they_saw
percent_match = 0
if i_saw in they_saw:
percent_match = float(they_saw[i_saw]) / sum(they_saw.values())
if percent_match >= min_match_percent:
print 'I WOULD trust this connection'
else:
print 'I would NOT trust this connection'
def do_stop(self, line):
self.client.stop()
def do_start(self, line):
self.client.start()
def do_EOF(self, line):
return True
if __name__ == '__main__':
client = PanoramaClient('tcp://127.0.0.1:12345',
auth.load_certificate('server.key')[0],
'client')
client.start()
ClientOptions(client).cmdloop()
|
{"/PanoramaClientGroup.py": ["/panorama.py"]}
|
13,117
|
wpharris92/panorama
|
refs/heads/master
|
/EvilPanoramaClients.py
|
import zmq.auth as auth
from time import sleep
from common import Reply
from traceback import print_exc
from panorama import PanoramaClient
# Potential names:
# Panorama
# Peerspectives (lol)
# Periphrials
DEFAULT_NUM_REPLIES = 5
DEFAULT_TIMEOUT = 5
STATE_READY = 'READY'
STATE_RUNNING = 'RUNNING'
STATE_STOPPED = 'STOPPED'
class EvilPanoramaClient(PanoramaClient):
def reply_to_requests(self, request_queue, reply_socket):
while True:
request_msg = request_queue.get(block=True)
try:
reply = Reply.from_request_msg(request_msg)
except:
# Invalid request
print_exc()
continue
print 'Got request for url:', reply.url
try:
# EVIL CLIENT SENDS BAD CERTIFICATE INFO
reply.reply = 'BAD_CERTIFICATE_INFO'
except:
print 'Failed to get server certificate:'
print_exc()
continue
reply_socket.send_multipart(reply.to_message())
try:
clients = []
for _ in range(10):
client = EvilPanoramaClient('tcp://127.0.0.1:12345',
auth.load_certificate('server.key')[0],
'client')
client.start()
clients.append(client)
while True:
# Just stick around to reply to requests
sleep(1)
except:
print_exc()
for client in clients:
client.stop
|
{"/PanoramaClientGroup.py": ["/panorama.py"]}
|
13,118
|
wpharris92/panorama
|
refs/heads/master
|
/PanoramaServer.py
|
import zmq
import common
from common import Request, Reply
import zmq.auth
from zmq.auth.thread import ThreadAuthenticator
import ssl
from traceback import print_exc
from random import SystemRandom
from time import time, sleep
import threading
from threading import Thread
from base64 import b64encode, b64decode
import peewee
from peewee import *
MYSQL_USER = 'WillHarris'
MYSQL_DATABASE = 'test'
SECONDS_BEFORE_PING = 5
SECONDS_BEFORE_DISCONNECT = 15
PING_FREQUENCY = 5 # Ping every 5 seconds
DEFAULT_WINDOW_MINS = .5 # 60 * 7 # 1 week
active_clients = {}
active_requests = {}
rand = SystemRandom()
socket_lock = threading.Lock()
class ClientInfo:
def __init__(self, client_id):
self.id = client_id
# replies_requested is a map (request_id -> number remaining), to support concurrent requests
self.replies_requested = {}
# last_action_time, so we can check if a client is still connected
self.last_action_time = time()
def client_action(self):
self.last_action_time = time()
def add_request(self, request_id, num_replies_requested):
self.replies_requested[request_id] = num_replies_requested
active_requests[request_id] = self
def load_database(database_name, user, password=None):
return MySQLDatabase(database_name, user=user, password=password)
def save_request(client_id, request):
save_access(client_id, request.url, request.this_view)
def save_reply(client_id, reply):
save_access(client_id, reply.url, reply.reply)
def save_access(client_id, url, cert_data):
access = Access(
client_id=client_id,
url=url,
cert_hash=cert_data,
access_time=time())
try:
access.save()
except peewee.IntegrityError:
print 'Updating existing database entry'
access = Access.get(Access.client_id == client_id,
Access.url == url)
access.cert_hash = cert_data
access.access_time = time()
access.save()
def access_to_reply(access):
return Reply('',
access.url,
access.cert_hash)
def load_accesses(client_id, url, window=DEFAULT_WINDOW_MINS):
return Access.select().where(
Access.client_id != client_id,
Access.url == url,
Access.access_time > time() - (DEFAULT_WINDOW_MINS * 60))
def get_database_replies(client_id, url, window=DEFAULT_WINDOW_MINS):
accesses = load_accesses(client_id, url, window)
return [(access.client_id, access_to_reply(access)) for access in accesses]
# Iterate through the clients and check how long it's been since they were active.
# If it's been longer than SECONDS_BEFORE_PING, ping them.
# If it's been longer than SECONDS_BEFORE_DISCONNECT, disconnect them.
def run_heartbeats(socket, client_map):
while True:
print 'There are %d clients connected' % len(client_map)
# Copy client_set so we're not iterating over it directly (threading issues)
for client in set(client_map.values()):
if time() - client.last_action_time > SECONDS_BEFORE_DISCONNECT:
print 'Disconnecting', client.id
try:
with socket_lock:
socket.send_multipart([client.id, common.GOODBYE_MSG])
except:
# Client isn't there! Don't do anything special.
print_exc()
pass
# Disconnect client
for request in client.replies_requested:
if request in active_requests:
del active_requests[request]
if client.id in client_map:
del client_map[client.id]
elif time() - client.last_action_time > SECONDS_BEFORE_PING:
# Ping the client
try:
with socket_lock:
socket.send_multipart([b64decode(client.id), common.PING])
except:
# Couldn't talk to the client. We'll try again later
print_exc()
pass
sleep(PING_FREQUENCY)
def run_server():
# Prepare the database
Access.create_table(fail_silently=True)
# Set up the ZMQ socket
pub, sec = common.get_keys('server')
socket = common.create_socket(zmq.Context.instance(),
zmq.ROUTER,
sec,
pub);
socket.bind('tcp://127.0.0.1:12345')
poller = zmq.Poller()
poller.register(socket, zmq.POLLIN)
# Start the heartbeat thread
heartbeat_thread = Thread(target=run_heartbeats, args=(socket, active_clients))
heartbeat_thread.daemon = True
heartbeat_thread.start()
try:
active = True
while active:
if (poller.poll()):
pass
# Now there should be a message ready
with socket_lock:
message = socket.recv_multipart()
client_id = b64encode(message[0])
msg_type = message[1]
if msg_type == common.HELLO_MSG:
if client_id not in active_clients:
active_clients[client_id] = ClientInfo(client_id)
elif msg_type == common.REPLY_MSG:
reply = Reply.from_message(message[1:])
if reply.request_id not in active_requests:
continue
save_reply(client_id, reply)
request_info = active_requests[reply.request_id]
reply.request_id = None # Don't need when replying to client
with socket_lock:
socket.send_multipart([b64decode(request_info[0])] + reply.to_message())
request_info[1] -= 1
if not request_info[1]:
# We've sent all the requested responses
del active_requests[request_id]
elif msg_type == common.REQUEST_MSG:
request_id = None
while not request_id or request_id in active_requests:
request_id = hex(rand.getrandbits(128))
forwarded_request = Request.from_message(message[1:])
forwarded_request.request_id = request_id
save_request(client_id, forwarded_request)
num_replies_requested = forwarded_request.num_replies
active_requests[request_id] = [client_id, forwarded_request.num_replies]
forwarded_request.num_replies = '' # Clear since we're sending to other clients
do_not_ask = set((client_id,))
# Return replies from the database
for client_asked, reply in get_database_replies(client_id, forwarded_request.url):
print 'Sending reply from database'
do_not_ask.add(client_asked)
with socket_lock:
socket.send_multipart([b64decode(client_id)] + reply.to_message())
num_replies_requested -= 1
num_requests_sent = 0
for client in active_clients.values():
if num_requests_sent >= num_replies_requested:
break
if client.id not in do_not_ask:
do_not_ask.add(client.id)
message_to_send = [b64decode(client.id)]
message_to_send.extend(forwarded_request.to_message())
try:
print 'Making request to another client'
with socket_lock:
socket.send_multipart(message_to_send)
except:
print_exc()
continue
num_requests_sent += 1
elif msg_type == common.GOODBYE_MSG:
print 'Client id', client_id, 'is leaving'
if client_id in active_clients:
del active_clients[client_id]
# Don't update last action time
continue
elif msg_type == common.PING:
# Don't do anything, last action time will be updated
pass
else:
print 'Got unknown message type:', message[1]
active_clients[client_id].last_action_time = time()
except:
print_exc()
pass
auth = ThreadAuthenticator(zmq.Context.instance())
auth.start()
auth.configure_curve(domain='*', location=zmq.auth.CURVE_ALLOW_ANY)
database_name = MYSQL_DATABASE
username = MYSQL_USER
db = load_database(database_name, username)
# Ew ew ew I don't know how to define these before having an instance of the database,
# So for now their definitions live here
class Access(Model):
client_id = peewee.CharField()
url = peewee.CharField()
cert_hash = peewee.CharField()
access_time = peewee.IntegerField()
class Meta:
database = db
# Set up unique constraints
indexes = (
# Each client may have one entry per url
(('client_id', 'url'), True),
)
try:
run_server()
except:
print_exc()
finally:
auth.stop()
|
{"/PanoramaClientGroup.py": ["/panorama.py"]}
|
13,119
|
wpharris92/panorama
|
refs/heads/master
|
/panorama.py
|
import zmq
import common
from common import Request, Reply
from threading import Thread
from time import time
from traceback import print_exc
from Queue import Queue, Empty, Full
DEFAULT_NUM_REPLIES = 5
DEFAULT_TIMEOUT = 5
STATE_READY = 'READY'
STATE_RUNNING = 'RUNNING'
STATE_STOPPED = 'STOPPED'
class PanoramaClient():
def __init__(self, server_address, server_key, client_cert_prefix):
self.context = zmq.Context.instance()
# Load client private & public keys
pub, sec = common.get_keys(client_cert_prefix)
# Set up socket and connect to server
self.server_socket = common.create_socket(self.context,
zmq.DEALER,
sec,
pub,
server_key);
self.server_socket.connect(server_address)
# Set up queue to push requests to
request_queue = Queue()
# List of reply listeners
self.reply_listeners = []
# Set up thread to delegate messages
message_delegate = Thread(target=self.delegate_messages,\
args=(self.server_socket, request_queue, self.reply_listeners))
message_delegate.daemon = True
message_delegate.start()
# Set up thread to handle requests
request_handler = Thread(target=self.reply_to_requests,\
args=(request_queue, self.server_socket))
request_handler.daemon = True
request_handler.start()
self.state = STATE_READY
# Start up the server
def start(self):
self.server_socket.send_multipart([common.HELLO_MSG])
self.state = STATE_RUNNING
# Stop the server
def stop(self):
self.server_socket.send_multipart([common.GOODBYE_MSG])
self.state = STATE_STOPPED
# Take a reply and publish it to all self.reply_listeners
def publish_reply(self, message):
for reply_listener in self.reply_listeners:
try:
reply_listener.put(message, block=True, timeout=.25)
except Full:
print 'Queue was full'
pass
# Grab a reply listener, so we can listen for replies to a request
def get_reply_listener(self):
listener = Queue()
self.reply_listeners.append(listener)
return listener
# Get rid of the reply listener
def del_reply_listener(self, listener):
self.reply_listeners.remove(listener)
# Method to be run in background thread to reply to requests
def reply_to_requests(self, request_queue, reply_socket):
while True:
request_msg = request_queue.get(block=True)
try:
reply = Reply.from_request_msg(request_msg)
except:
# Invalid request
print_exc()
continue
print 'Got request for url:', reply.url
try:
reply.reply = common.get_server_data(reply.url)
except:
print 'Failed to get server certificate:'
print_exc()
continue
reply_socket.send_multipart(reply.to_message())
# Method to be run in background to:
# Listen for and delegate messages
# Respond to pings
# React appropriately when the server disconnects us
def delegate_messages(self, incoming_socket, request_queue, reply_listeners):
while True:
msg = incoming_socket.recv_multipart()
# First frame is message type
msg_type = msg[0]
if msg_type == common.REQUEST_MSG:
# Pass to the request queue
request_queue.put(msg, block=True, timeout=.25)
elif msg_type == common.REPLY_MSG:
print 'Got reply for', msg[1]
# Publish the reply
self.publish_reply(msg)
elif msg_type == common.GOODBYE_MSG:
print 'Disconnected by server'
self.stop()
elif msg_type == common.PING:
# Don't delegate, just reply here
incoming_socket.send_multipart([common.PING])
else:
print 'Got unknown message type: %s, ignoring it' % msg_type
# Make a request for other views of a certificate
def request(self, url, timeout=DEFAULT_TIMEOUT, num_replies=DEFAULT_NUM_REPLIES):
assert self.state == STATE_RUNNING, 'Must make requests on running client'
reply_listener = self.get_reply_listener()
# Try to get the certificate to send to the server to be added to the database
# Also, some good error checking so we're not sending requests for bogus urls
this_view = common.get_server_data(url)
request = Request(
url,
this_view,
num_replies=num_replies)
# Send the request
self.server_socket.send_multipart(request.to_message())
start = time()
replies = []
while len(replies) < num_replies:
if time() - start >= timeout:
break
try:
reply_msg = reply_listener.get(block=True, timeout=.1)
except Empty:
continue
try:
rep = Reply.from_message(reply_msg)
except:
# Malformed reply
print_exc()
continue
if rep.url == url:
replies.append(rep.reply)
self.del_reply_listener(reply_listener)
reply_counts = {}
for reply in replies:
if reply not in reply_counts:
reply_counts[reply] = 1
else:
reply_counts[reply] += 1
return this_view, reply_counts
|
{"/PanoramaClientGroup.py": ["/panorama.py"]}
|
13,120
|
wpharris92/panorama
|
refs/heads/master
|
/PanoramaClientGroup.py
|
import zmq.auth as auth
from time import sleep
from traceback import print_exc
from panorama import PanoramaClient
if __name__ == '__main__':
try:
clients = []
for _ in range(10):
client = PanoramaClient('tcp://127.0.0.1:12345',
auth.load_certificate('server.key')[0],
'client')
client.start()
clients.append(client)
while True:
# Just stick around to reply to requests
sleep(1)
except:
print_exc()
for client in clients:
client.stop
|
{"/PanoramaClientGroup.py": ["/panorama.py"]}
|
13,121
|
wpharris92/panorama
|
refs/heads/master
|
/common.py
|
import zmq.auth
import json
import hashlib
import ssl
# Format: [HELLO_MSG]
HELLO_MSG = 'HELLO'
# Format: [PING]
PING = 'PING'
# Format: [GOODBYE_MSG]
GOODBYE_MSG = 'GOODBYE'
# Format: [REQUEST_MSG, <url>, <num_replies>, <request id>, <this_view>]
REQUEST_MSG = 'REQUEST'
# Format: [REPLY_MSG, <url>, <request id>, <reply>]
# When receiving replys, request id will be dropped. It should be echoed back by
# clients so that the server can route the reply to the correct location
REPLY_MSG = 'REPLY'
SSL_PORT = 443
def hash_of(certificate):
return hashlib.sha256(certificate).hexdigest()
def get_server_data(url):
addr = (url, SSL_PORT)
return hash_of(ssl.get_server_certificate(addr))
def get_keys(cert_prefix):
try:
return zmq.auth.load_certificate(cert_prefix + '.key_secret')
except:
files = zmq.auth.create_certificates('.', cert_prefix)
for f in files:
if 'secret' in f:
return zmq.auth.load_certificate(f)
def create_socket(context, sock_type, secret_key, public_key, server_key=None, socket_id=None):
socket = context.socket(sock_type)
if sock_type == zmq.ROUTER:
socket.router_mandatory = 1
socket.curve_secretkey = secret_key
socket.curve_publickey = public_key
# If server_key is given, assume client. No server key -> I'm the server
if server_key:
socket.curve_serverkey = server_key
if socket_id:
socket.setsockopt_string(zmq.IDENTITY, socket_id)
else:
socket.curve_server = True
return socket
class Request:
def __init__(self, url, this_view, num_replies=None, request_id=None):
assert url, 'Url not given'
assert num_replies or request_id and not (num_replies and request_id), 'request_id xor num_replies must be given'
self.url = url
self.request_id = request_id
self.num_replies = num_replies
self.this_view = this_view
@classmethod
def from_message(cls, message):
assert message, 'Message was None'
assert len(message) > 0, 'Message had 0 length'
assert message[0] == REQUEST_MSG, 'Message was not of type REQUEST instead was %s' % message[0]
assert len(message) >= 5, 'Malformed message: %r' % message
return cls(message[1],
message[4] if len(message[4]) else None,
int(message[2]) if len(message[2]) else None,
message[3])
def to_message(self):
return [REQUEST_MSG,
self.url,
str(self.num_replies) if self.num_replies else '',
str(self.request_id) if self.request_id else '',
str(self.this_view) if self.this_view else '']
class Reply:
def __init__(self, request_id, url, reply):
assert url, 'Url not given'
self.url = url
self.request_id = request_id
self.reply = reply
@classmethod
def from_message(cls, message):
assert message, 'Message was None'
assert len(message) > 0, 'Message had 0 length'
assert message[0] == REPLY_MSG, 'Message was not of type REPLY instead was %s' % message[0]
assert len(message) >= 3, 'Malformed message: %r' % message
url = message[1]
if len(message) > 3:
# The reply has a request id
request_id = message[2]
reply = message[3]
else:
request_id = None
reply = message[2]
return cls(request_id, url, reply)
# Used by clients to easily turn Requests to Replys
@staticmethod
def from_request(request):
assert request.request_id, 'from_request should be used on requests with request_ids'
return Reply(request.request_id, request.url, None)
@staticmethod
def from_request_msg(request_msg):
return Reply.from_request(Request.from_message(request_msg))
def to_message(self):
message = [REPLY_MSG, str(self.url)]
if self.request_id:
message.append(str(self.request_id))
message.append(str(self.reply))
return message
|
{"/PanoramaClientGroup.py": ["/panorama.py"]}
|
13,154
|
gboleslavsky/POC_RESTful_Flask_API
|
refs/heads/master
|
/tests/cookbook_test.py
|
import unittest
from flask import Flask, current_app, url_for, jsonify
import flask_restful_demo_cookbook as test_app
from flask_restful_demo_cookbook import api
class BasicsTestCase(unittest.TestCase):
def setUp(self):
import base64
#setting up Flask test_client to test the RESTful endpoints in flask_demo
self.app = test_app.flask_demo
self.app.config.update(SERVER_NAME='localhost:5000')
self.app_context = self.app.app_context()
self.app_context.push()
self.client = self.app.test_client(use_cookies=True)
self.app.testing = True
self.auth_header = {
'Authorization':
'Basic ' + base64.b64encode(('gregory' + ':' + 'boleslavsky').encode('utf-8')).decode('utf-8')}
def tearDown(self):
self.app_context.pop()
##################################### utility functions
#did not test them all
def test_change_recipe_fields(self):
recipe_before = test_app.all_recipes[0]
print(test_app.json_recipe(recipe_before))
recipe_after = test_app.change_recipe_fields(recipe_before, {'dish_name':'Not Macaroni and Cheese'} )
self.assertEquals(recipe_after.get('dish_name'), 'Not Macaroni and Cheese') #test return value
self.assertEquals(test_app.all_recipes[0].get('dish_name'), 'Not Macaroni and Cheese') #test side-effect
def test_matching_recipes(self):
self.assertEquals(len(test_app.matching_recipes(field_name='cuisine', field_value='Italian')), 1)
self.assertEquals(len(test_app.matching_recipes(field_name='cuisine', field_value='American')), 1)
self.assertEquals(len(test_app.matching_recipes(field_name='is_vegan', field_value=True)), 2)
self.assertEquals(len(test_app.matching_recipes(field_name='is_vegan', field_value=False)), 1)
#def json_recipe(self):
#RESTful endpoints
#did not test them all, these are just a couple examples how easy it is to test
#REStful endpoints with Flask thoroughly in a unit, not integration, test, so
#they run every build
def test_login_with_no_username_or_password(self):
response = self.client.get(url_for(endpoint='vegan_recipes'))
self.assertTrue(response.status_code == 403)
def test_vegan_recipes(self):
correct_reponse="""{"recipes": [{"cuisine": "Korean", "ingredients": "carrots, sesame oil, rice vinegar, fresh garlic, coriander seeds, cayenne pepper", "uri": "/cookbook/v1.0/recipes/2", "steps": "1. Shred the carrots 2. Mix with the rest of the ingredients 3. Leave in the refrigerator for 1 hour", "dish_name": "Korean Carrots", "is_vegan": true}, {"cuisine": "Italian", "ingredients": "cooked white beans (Canelloni or any other), chopped green onion, balsamic vinegar, olive oil", "uri": "/cookbook/v1.0/recipes/3", "steps": "1. Mix all ingredients 2. Let the dish sit in rerigerator for 1 hour", "dish_name": "Tuscan Bean Salad", "is_vegan": true}]}"""
response = self.client.get(url_for(endpoint='vegan_recipes'),
headers=self.auth_header)
self.assertTrue(response.status_code == 200)
self.assertEquals(response.data, correct_reponse)
def test_post_a_new_recipe(self):
from urllib import urlencode
import json
new_recipe = {
'dish_name': 'fingeling potatoes',
'cuisine': 'American',
'ingredients': 'fingerling potatoes',
'steps': '1. Wash the potatoes. 2. Cook the potatoes',
'is_vegan': True}
#does not work with test_client yet, most likely something is wrong in the config
#works fine with curl
response = self.client.post(url_for(endpoint='recipes'),
headers=self.auth_header,
data=urlencode(new_recipe))
#self.assertTrue(response.status_code == 401)
response_with_new_recipe = json.loads(self.client.get(url_for(endpoint='recipes', id=3 ),
headers=self.auth_header).data)\
.get('recipes')
#self.assertTrue(response.status_code == 200)
#self.assertEquals(new_recipe.get('dish_name'),
# response_with_new_recipe.get('dish_name'))
|
{"/tests/cookbook_test.py": ["/flask_restful_demo_cookbook.py"]}
|
13,155
|
gboleslavsky/POC_RESTful_Flask_API
|
refs/heads/master
|
/flask_restful_demo_cookbook.py
|
#!flask/bin/python
from flask import Flask, jsonify, abort, make_response
from flask.ext.restful import Api, Resource, reqparse, fields, marshal
from flask.ext.httpauth import HTTPBasicAuth
####################################### global reusable functions, static data and constants
flask_demo = Flask(__name__)
api = Api(flask_demo)
auth = HTTPBasicAuth()
all_recipes = [
{
'unique_id': 1,
'dish_name': 'Macaroni and Cheese',
'cuisine': 'American',
'ingredients': 'any small size pasta, cheese that melts well',
'steps': '1. Cook the pasta 2. Shred the cheese 3. Mixed cooked pasta and shredded cheese ' +
'4. Heat on a stove till cheese is melted or microwave for 2 minutes',
'is_vegan': False
},
{
'unique_id': 2,
'dish_name': 'Korean Carrots',
'cuisine': 'Korean',
'ingredients': 'carrots, sesame oil, rice vinegar, fresh garlic, coriander seeds, cayenne pepper',
'steps': '1. Shred the carrots 2. Mix with the rest of the ingredients '
'3. Leave in the refrigerator for 1 hour',
'is_vegan': True
},
{
'unique_id': 3,
'dish_name': 'Tuscan Bean Salad',
'cuisine': 'Italian',
'ingredients': 'cooked white beans (Canelloni or any other), chopped green onion, balsamic vinegar, olive oil',
'steps': '1. Mix all ingredients 2. Let the dish sit in rerigerator for 1 hour',
'is_vegan': True
},
]
recipe_fields = {
'dish_name': fields.String,
'cuisine': fields.String,
'ingredients': fields.String,
'steps': fields.String,
'is_vegan': fields.Boolean,
'uri': fields.Url('recipe') # Flask-RESTful dead simple way to construct a HATEOAS link
}
def recipe_validator():
request_parser = reqparse.RequestParser()
# define fields for the parser so it can validate them
request_parser.add_argument('dish_name',
type=str,
required=True,
help='Please provide the name of the dish')
request_parser.add_argument('cuisine',
type=str,
default="")
request_parser.add_argument('ingredients',
type=str,
required=True,
help='Please provide the list of ingredients')
request_parser.add_argument('steps',
type=str,
required=True,
help='Please provide the steps for preparing the recipe')
request_parser.add_argument('is_vegan',
type=bool,
required=False,
help='Please provide the steps for preparing the recipe')
return request_parser
####################################### utilities
# security callbacks
@auth.get_password
def password(username):
# in a real app, either hit a directory server or a DB with encrypted pws
passwords = {
'gregory': 'boleslavsky',
'test': 'pw'
}
return passwords.get(username, None)
@auth.error_handler
def wrong_credentials():
return make_response(jsonify({'message': 'Wrong username or password'}),
403) # 401 makes browsers pop an auth dialog
# reusable functions
def matching_recipes(field_name, field_value):
return [recipe for recipe in all_recipes if recipe[field_name] == field_value]
def recipe_with_unique_id(unique_id):
recipes = matching_recipes(field_name='unique_id', field_value=unique_id)
if recipes:
return recipes[0]
def change_recipe_fields(recipe, field_names_and_new_values):
for field_name, new_value in field_names_and_new_values.items():
if new_value:
recipe[field_name] = new_value
return recipe # for convenience and to facilitate fluent or compositonal style
def json_recipes(recipes):
return {'recipes': [marshal(recipe, recipe_fields) for recipe in recipes]}
def json_recipe(recipe):
return {'recipe': marshal(recipe, recipe_fields)}
####################################### request handlers
class ItalianRecipes(Resource):
"""
Italian food is very popular and deserves its own URL
"""
decorators = [auth.login_required] # just decorating with @auth.login_required does not work anymore
def __init__(self):
super(ItalianRecipes, self).__init__()
def get(self):
recipes = matching_recipes(field_name='cuisine', field_value='Italian')
if not recipes:
abort(404)
return json_recipes(recipes)
class VeganRecipes(Resource):
"""
Vegan food is getting popular and deserves its own URL
"""
decorators = [auth.login_required] # just decorating with @auth.login_required does not work anymore
def __init__(self):
super(VeganRecipes, self).__init__()
def get(self):
recipes = matching_recipes(field_name='is_vegan', field_value=True)
if not recipes:
abort(404)
return json_recipes(recipes)
class SpecificRecipeAPI(Resource):
decorators = [auth.login_required] # just decorating with @auth.login_required does not work anymore
def __init__(self):
self.request_parser = recipe_validator()
super(SpecificRecipeAPI, self).__init__()
def get(self, unique_id):
recipe = recipe_with_unique_id(unique_id)
if not recipe:
abort(404)
return json_recipe(recipe)
def put(self, unique_id):
recipe = recipe_with_unique_id(unique_id)
if not recipe:
abort(404)
fields_to_change = self.request_parser.parse_args()
recipe = change_recipe_fields(recipe, fields_to_change)
return json_recipe(recipe)
def delete(self, unique_id):
recipe_to_remove = recipe_with_unique_id(unique_id)
if not recipe_to_remove:
abort(404)
all_recipes.remove(recipe_to_remove)
return {'result': True}
class AllRestfulRecipesAPI(Resource):
decorators = [auth.login_required] # just decorating with @auth.login_required does not work anymore
def __init__(self):
self.request_parser = recipe_validator()
super(AllRestfulRecipesAPI, self).__init__()
def get(self):
return json_recipes(all_recipes)
def unique_id(self):
if not all_recipes:
return 1
else:
return all_recipes[-1]['unique_id'] + 1 # one more than the largest unique_id, which is
# always found in the last recipe
def post(self):
args = self.request_parser.parse_args() # parses and validates
recipe = {
'unique_id': self.unique_id(),
'dish_name': args['dish_name'],
'cuisine': args['cuisine'],
'ingredients': args['ingredients'],
'steps': args['steps'],
'is_vegan': args['is_vegan']
}
all_recipes.append(recipe)
return json_recipe(recipe), 201
api.add_resource(ItalianRecipes, '/cookbook/v1.0/recipes/italian', endpoint='italian_recipes')
api.add_resource(VeganRecipes, '/cookbook/v1.0/recipes/vegan', endpoint='vegan_recipes')
api.add_resource(SpecificRecipeAPI, '/cookbook/v1.0/recipes/<int:unique_id>', endpoint='recipe')
api.add_resource(AllRestfulRecipesAPI, '/cookbook/v1.0/recipes', endpoint='recipes')
if __name__ == '__main__':
flask_demo.run()
|
{"/tests/cookbook_test.py": ["/flask_restful_demo_cookbook.py"]}
|
13,164
|
olu-damilare/hatchlings
|
refs/heads/main
|
/airlineReservationAndBooking/seat_class.py
|
class SeatClass(object):
first_class = "FIRSTCLASS"
business = "BUSINESS"
economy = "ECONOMY"
|
{"/tests/validate_credit_card_test.py": ["/credit_card/validation.py"], "/airlineReservationAndBooking/airline.py": ["/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/flight_details.py"], "/airlineReservationAndBooking/flight_booking.py": ["/airlineReservationAndBooking/reservation.py"], "/airlineReservationAndBooking/aeroplane.py": ["/airlineReservationAndBooking/seat.py"], "/tests/test_calculator_oop.py": ["/calculator/calculator_oop.py"], "/tests/test_calculator_functions.py": ["/calculator/CalculatorFunctions.py"], "/airlineReservationAndBooking/payment.py": ["/airlineReservationAndBooking/airline.py"], "/tests/airline_reservation_and_booking_tests.py": ["/airlineReservationAndBooking/boarding_pass.py", "/airlineReservationAndBooking/airline.py", "/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/passenger.py", "/airlineReservationAndBooking/reservation.py", "/airlineReservationAndBooking/seat_class.py", "/airlineReservationAndBooking/flight_booking.py", "/airlineReservationAndBooking/payment.py", "/airlineReservationAndBooking/payment_type.py", "/airlineReservationAndBooking/admin.py"]}
|
13,165
|
olu-damilare/hatchlings
|
refs/heads/main
|
/connect_human_table.py
|
import mysql.connector
from mysql.connector import Error
from getpass import getpass
def connect_fetch():
conn = None
try:
conn = mysql.connector.connect(host='localhost', database='demo', user=input('Enter your username: '),
password=getpass('Enter your password: '))
print('Connecting to the database server')
if conn.is_connected:
print('Connected to the datatbase server')
cursor = conn.cursor(dictionary=True)
cursor.execute("select * from human")
records = cursor.fetchall()
print("Total number of rows in buyer is ", cursor.rowcount, '\n')
print('Printing each buyer record')
for row in records:
for i in row:
print(i, "-", row[i])
print()
except Error as e:
print('Failed to connect to database server due to ', e)
finally:
if conn is not None and conn.is_connected():
conn.close()
print('Database shutdown')
connect_fetch()
|
{"/tests/validate_credit_card_test.py": ["/credit_card/validation.py"], "/airlineReservationAndBooking/airline.py": ["/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/flight_details.py"], "/airlineReservationAndBooking/flight_booking.py": ["/airlineReservationAndBooking/reservation.py"], "/airlineReservationAndBooking/aeroplane.py": ["/airlineReservationAndBooking/seat.py"], "/tests/test_calculator_oop.py": ["/calculator/calculator_oop.py"], "/tests/test_calculator_functions.py": ["/calculator/CalculatorFunctions.py"], "/airlineReservationAndBooking/payment.py": ["/airlineReservationAndBooking/airline.py"], "/tests/airline_reservation_and_booking_tests.py": ["/airlineReservationAndBooking/boarding_pass.py", "/airlineReservationAndBooking/airline.py", "/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/passenger.py", "/airlineReservationAndBooking/reservation.py", "/airlineReservationAndBooking/seat_class.py", "/airlineReservationAndBooking/flight_booking.py", "/airlineReservationAndBooking/payment.py", "/airlineReservationAndBooking/payment_type.py", "/airlineReservationAndBooking/admin.py"]}
|
13,166
|
olu-damilare/hatchlings
|
refs/heads/main
|
/airlineReservationAndBooking/flight_details.py
|
class FlightDetails(object):
def __init__(self):
self.__passenger_info = []
def assign_flight_number(self, flight_number):
self.__flight_number = flight_number
def record_passenger_info(self, passenger):
self.__passenger_info.append(passenger)
def record_pilot_info(self, pilot):
self.__pilot = pilot
def record_host_info(self, host):
self.__host = host
def get_flight_number(self):
return self.__flight_number
def __str__(self):
details = "Flight Details:\nNumber of passengers = " + str(len(self.__passenger_info)) + "\nFlight number = " + str(self.__flight_number) + "\n\nHost Details:\n" + self.__host.__str__() + "\n\nPilot Details:\n" + self.__pilot.__str__() + "\n\nPassengers Information:\n\n"
for passenger in self.__passenger_info:
details += passenger.__str__() + '\n\n'
return details
|
{"/tests/validate_credit_card_test.py": ["/credit_card/validation.py"], "/airlineReservationAndBooking/airline.py": ["/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/flight_details.py"], "/airlineReservationAndBooking/flight_booking.py": ["/airlineReservationAndBooking/reservation.py"], "/airlineReservationAndBooking/aeroplane.py": ["/airlineReservationAndBooking/seat.py"], "/tests/test_calculator_oop.py": ["/calculator/calculator_oop.py"], "/tests/test_calculator_functions.py": ["/calculator/CalculatorFunctions.py"], "/airlineReservationAndBooking/payment.py": ["/airlineReservationAndBooking/airline.py"], "/tests/airline_reservation_and_booking_tests.py": ["/airlineReservationAndBooking/boarding_pass.py", "/airlineReservationAndBooking/airline.py", "/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/passenger.py", "/airlineReservationAndBooking/reservation.py", "/airlineReservationAndBooking/seat_class.py", "/airlineReservationAndBooking/flight_booking.py", "/airlineReservationAndBooking/payment.py", "/airlineReservationAndBooking/payment_type.py", "/airlineReservationAndBooking/admin.py"]}
|
13,167
|
olu-damilare/hatchlings
|
refs/heads/main
|
/airlineReservationAndBooking/reservation.py
|
class Reservation(object):
__reserved_passengers = []
def reserve_flight(self, passenger, seat_class):
self.__reserved_passengers.append(passenger)
passenger.set_seat_class(seat_class)
def has_reserved(self, passenger):
has_reserved = False
for i in self.__reserved_passengers:
if i == passenger:
has_reserved = True
return has_reserved
def get_reservation_ID(self, passenger):
reservation_id = None
index = 0
while index < len(self.__reserved_passengers):
if self.__reserved_passengers[index] == passenger:
reservation_id = index + 1
break
index += 1
return reservation_id
def get_reserved_seat_class(self, passenger):
seat_class = None
index = 0
while index < len(self.__reserved_passengers):
if self.__reserved_passengers[index] == passenger:
seat_class = passenger.get_seat_class()
break
index += 1
return seat_class
def get_total_number_reserved_seats(self):
return len(self.__reserved_passengers)
def cancelReservation(self, reservation_id):
index = 1
while index <= len(self.__reserved_passengers):
if index == reservation_id:
del self.__reserved_passengers[index - 1]
break
index += 1
@classmethod
def get_reserved_passengers(cls):
return cls.__reserved_passengers
def empty_reservation_list(self):
self.__reserved_passengers.clear()
@classmethod
def get_passenger(cls, reservation_id):
for i in range(len(cls.__reserved_passengers)):
if i + 1 == reservation_id:
return cls.__reserved_passengers[i]
|
{"/tests/validate_credit_card_test.py": ["/credit_card/validation.py"], "/airlineReservationAndBooking/airline.py": ["/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/flight_details.py"], "/airlineReservationAndBooking/flight_booking.py": ["/airlineReservationAndBooking/reservation.py"], "/airlineReservationAndBooking/aeroplane.py": ["/airlineReservationAndBooking/seat.py"], "/tests/test_calculator_oop.py": ["/calculator/calculator_oop.py"], "/tests/test_calculator_functions.py": ["/calculator/CalculatorFunctions.py"], "/airlineReservationAndBooking/payment.py": ["/airlineReservationAndBooking/airline.py"], "/tests/airline_reservation_and_booking_tests.py": ["/airlineReservationAndBooking/boarding_pass.py", "/airlineReservationAndBooking/airline.py", "/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/passenger.py", "/airlineReservationAndBooking/reservation.py", "/airlineReservationAndBooking/seat_class.py", "/airlineReservationAndBooking/flight_booking.py", "/airlineReservationAndBooking/payment.py", "/airlineReservationAndBooking/payment_type.py", "/airlineReservationAndBooking/admin.py"]}
|
13,168
|
olu-damilare/hatchlings
|
refs/heads/main
|
/tests/validate_credit_card_test.py
|
import unittest
from credit_card.validation import CreditCardValidation
class MyTestCase(unittest.TestCase):
def setUp(self) -> None:
self.credit_card_number = 4388576018402626
self.validate = CreditCardValidation()
def test_thatTheSumOfDoubleOfEvenPositionsCanBeObtained(self):
self.assertEqual(37, self.validate.calculate_sum_of_double_even_place(self.credit_card_number))
def test_that_the_sum_of_odd_positions_can_be_obtained(self):
self.assertEqual(38, self.validate.calculate_sum_of_odd_place(self.credit_card_number))
def testThatCreditCardIsInvalid(self):
self.assertFalse(self.validate.isValid(self.credit_card_number))
self.assertTrue(self.validate.isValid(371175520987141))
|
{"/tests/validate_credit_card_test.py": ["/credit_card/validation.py"], "/airlineReservationAndBooking/airline.py": ["/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/flight_details.py"], "/airlineReservationAndBooking/flight_booking.py": ["/airlineReservationAndBooking/reservation.py"], "/airlineReservationAndBooking/aeroplane.py": ["/airlineReservationAndBooking/seat.py"], "/tests/test_calculator_oop.py": ["/calculator/calculator_oop.py"], "/tests/test_calculator_functions.py": ["/calculator/CalculatorFunctions.py"], "/airlineReservationAndBooking/payment.py": ["/airlineReservationAndBooking/airline.py"], "/tests/airline_reservation_and_booking_tests.py": ["/airlineReservationAndBooking/boarding_pass.py", "/airlineReservationAndBooking/airline.py", "/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/passenger.py", "/airlineReservationAndBooking/reservation.py", "/airlineReservationAndBooking/seat_class.py", "/airlineReservationAndBooking/flight_booking.py", "/airlineReservationAndBooking/payment.py", "/airlineReservationAndBooking/payment_type.py", "/airlineReservationAndBooking/admin.py"]}
|
13,169
|
olu-damilare/hatchlings
|
refs/heads/main
|
/airlineReservationAndBooking/admin.py
|
class Admin(object):
def __init__(self, full_name, phone_number, email_address, staff_ID):
self.__full_name = full_name
self.__phone_number = phone_number
self.__email_address = email_address
self.__staff_ID = staff_ID
def __str__(self):
return "Full Name = {}\nPhone number = {}\nEmail address = {}\nStaff ID = {}".format(self.__full_name, self.__phone_number, self.__email_address, self.__staff_ID)
|
{"/tests/validate_credit_card_test.py": ["/credit_card/validation.py"], "/airlineReservationAndBooking/airline.py": ["/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/flight_details.py"], "/airlineReservationAndBooking/flight_booking.py": ["/airlineReservationAndBooking/reservation.py"], "/airlineReservationAndBooking/aeroplane.py": ["/airlineReservationAndBooking/seat.py"], "/tests/test_calculator_oop.py": ["/calculator/calculator_oop.py"], "/tests/test_calculator_functions.py": ["/calculator/CalculatorFunctions.py"], "/airlineReservationAndBooking/payment.py": ["/airlineReservationAndBooking/airline.py"], "/tests/airline_reservation_and_booking_tests.py": ["/airlineReservationAndBooking/boarding_pass.py", "/airlineReservationAndBooking/airline.py", "/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/passenger.py", "/airlineReservationAndBooking/reservation.py", "/airlineReservationAndBooking/seat_class.py", "/airlineReservationAndBooking/flight_booking.py", "/airlineReservationAndBooking/payment.py", "/airlineReservationAndBooking/payment_type.py", "/airlineReservationAndBooking/admin.py"]}
|
13,170
|
olu-damilare/hatchlings
|
refs/heads/main
|
/airlineReservationAndBooking/passenger.py
|
class Passenger(object):
def __init__(self, name, phone_number, email_address):
self.__name = name
self.__phone_number = phone_number
self.__email_address = email_address
self.__payment_type = None
self.__seat_class = None
self.__paid = False
self.__is_booked = False
self.__seat_number = 0
def set_seat_class(self, seat_class):
self.__seat_class = seat_class
def get_seat_class(self):
return self.__seat_class
def set_payment_type(self, payment_type):
self.__payment_type = payment_type
def get_payment_type(self):
return self.__payment_type
def has_paid(self):
return self.__paid
def set_booked_status(self, booked):
self.__is_booked = booked
def has_booked(self):
return self.__is_booked
def assign_seat_number(self, seat_number):
self.__seat_number = seat_number
def make_payment(self, has_paid):
self.__paid = has_paid
def __str__(self):
return "Full Name = {}\nPhone number = {}\nEmail address = {}\nSeat class = {}\nSeat number = {}\nPayment " \
"type = {}".format(self.__name, self.__phone_number, self.__email_address,
self.__seat_class, self.__seat_number, self.__payment_type)
def get_seat_number(self):
return self.__seat_number
|
{"/tests/validate_credit_card_test.py": ["/credit_card/validation.py"], "/airlineReservationAndBooking/airline.py": ["/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/flight_details.py"], "/airlineReservationAndBooking/flight_booking.py": ["/airlineReservationAndBooking/reservation.py"], "/airlineReservationAndBooking/aeroplane.py": ["/airlineReservationAndBooking/seat.py"], "/tests/test_calculator_oop.py": ["/calculator/calculator_oop.py"], "/tests/test_calculator_functions.py": ["/calculator/CalculatorFunctions.py"], "/airlineReservationAndBooking/payment.py": ["/airlineReservationAndBooking/airline.py"], "/tests/airline_reservation_and_booking_tests.py": ["/airlineReservationAndBooking/boarding_pass.py", "/airlineReservationAndBooking/airline.py", "/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/passenger.py", "/airlineReservationAndBooking/reservation.py", "/airlineReservationAndBooking/seat_class.py", "/airlineReservationAndBooking/flight_booking.py", "/airlineReservationAndBooking/payment.py", "/airlineReservationAndBooking/payment_type.py", "/airlineReservationAndBooking/admin.py"]}
|
13,171
|
olu-damilare/hatchlings
|
refs/heads/main
|
/airlineReservationAndBooking/airline.py
|
from airlineReservationAndBooking.aeroplane import Aeroplane
from airlineReservationAndBooking.flight_details import FlightDetails
class Airline(object):
__first_class_seat_price = None
__business_class_seat_price = None
__economy_class_seat_price = None
def __init__(self, airline_name: str, aeroplane: Aeroplane):
self.__aeroplanes = []
self.__flight_details = []
self.__airlineName = airline_name
self.__aeroplanes.append(aeroplane)
def get_airline_name(self):
return self.__airlineName
def __str__(self):
return "Airline name: " + self.get_airline_name() + "\nNumber of aeroplanes: " + str(self.get_total_number_of_aeroplanes())
def get_total_number_of_aeroplanes(self):
return len(self.__aeroplanes)
def acquireAeroplane(self, aeroplane):
self.__aeroplanes.append(aeroplane)
@classmethod
def set_price_of_first_class(cls, amount):
cls.__first_class_seat_price = amount
@classmethod
def get_price_of_first_class_seat(cls):
return cls.__first_class_seat_price
@classmethod
def set_price_of_business_class(cls, amount):
cls.__business_class_seat_price = amount
@classmethod
def get_price_of_business_class_seat(cls):
return cls.__business_class_seat_price
@classmethod
def set_price_of_economy_class(cls, amount):
cls.__economy_class_seat_price = amount
@classmethod
def get_price_of_economy_class_seat(cls):
return cls.__economy_class_seat_price
def generate_flight_number(self):
details = FlightDetails()
details.assign_flight_number(len(self.__flight_details) + 1)
self.__flight_details.append(details)
return len(self.__flight_details)
def assign_pilot(self, pilot, flight_number):
for flight_details in self.__flight_details:
if flight_details.get_flight_number() == flight_number:
flight_details.record_pilot_info(pilot)
def assign_host(self, host, flight_number):
for flight_details in self.__flight_details:
if flight_details.get_flight_number() == flight_number:
flight_details.record_host_info(host)
def board_passenger(self, passenger, flight_number):
for flight_details in self.__flight_details:
if flight_details.get_flight_number() == flight_number:
flight_details.record_passenger_info(passenger)
def generate_flight_details(self, flight_number):
for flight_details in self.__flight_details:
if flight_details.get_flight_number() == flight_number:
return flight_details.__str__()
|
{"/tests/validate_credit_card_test.py": ["/credit_card/validation.py"], "/airlineReservationAndBooking/airline.py": ["/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/flight_details.py"], "/airlineReservationAndBooking/flight_booking.py": ["/airlineReservationAndBooking/reservation.py"], "/airlineReservationAndBooking/aeroplane.py": ["/airlineReservationAndBooking/seat.py"], "/tests/test_calculator_oop.py": ["/calculator/calculator_oop.py"], "/tests/test_calculator_functions.py": ["/calculator/CalculatorFunctions.py"], "/airlineReservationAndBooking/payment.py": ["/airlineReservationAndBooking/airline.py"], "/tests/airline_reservation_and_booking_tests.py": ["/airlineReservationAndBooking/boarding_pass.py", "/airlineReservationAndBooking/airline.py", "/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/passenger.py", "/airlineReservationAndBooking/reservation.py", "/airlineReservationAndBooking/seat_class.py", "/airlineReservationAndBooking/flight_booking.py", "/airlineReservationAndBooking/payment.py", "/airlineReservationAndBooking/payment_type.py", "/airlineReservationAndBooking/admin.py"]}
|
13,172
|
olu-damilare/hatchlings
|
refs/heads/main
|
/movies_review/connect_ratings.py
|
import mysql.connector
from mysql.connector import Error
def connect_run():
conn = None
try:
conn = mysql.connector.connect(host = 'localhost', database = 'movie_review', user = input('Enter your username: '), password = input('Enter your password: '))
if conn.is_connected:
print('Connected to the database server\n')
list_vals = []
cursor = conn.cursor(dictionary = True)
menu = "Press 1 to insert into ratings table \nPress 2 to update ratings table \nPress 3 to delete row from ratings table\n"
user_selection = int(input(menu))
while user_selection < 1 or user_selection > 3:
print("\nInvalid selection.")
user_selection = int(input(menu))
if user_selection == 1:
row_num = int(input('How many rows do you want to insert? '))
sql_query = "Insert into ratings (rating, movie_id, reviewer_id) Values (%s, %s, %s);"
for i in range(row_num):
print('Row', i+1)
movie_id = input("Enter the movie id: ")
reviewer_id = input("Enter the reviewer id: ")
rating = input("Enter the rating for the movie with the provided movie id: ")
val = (rating, movie_id, reviewer_id)
list_vals.append(val)
print()
cursor.executemany(sql_query, list_vals)
conn.commit()
print(cursor.rowcount, ' row was inserted')
elif user_selection == 2:
number_of_columns = int(input("How many fields do you want to update? "))
list = []
for i in range(number_of_columns):
movie_id = input("Enter the movie id: ")
reviewer_id = input("Enter the reviewer id: ")
new_value = input("Enter the new value of the rating: ")
sql_query = "Update ratings set rating = \'" + new_value + "\' where movie_ID = \'" + movie_id + "\' and reviewer_ID = \'" + reviewer_id + "\'"
cursor.execute(sql_query)
conn.commit()
print(cursor.rowcount, "row successfully updated in movies table")
elif user_selection == 3:
number_of_rows = int(input("How many rows do you want to delete? "))
list = []
for i in range(number_of_rows):
movie_id = input("Enter the movie id: ")
reviewer_id = input("Enter the reviewer id: ")
sql_query = "delete from ratings where movie_ID = \'" + movie_id + "\' and reviewer_ID = \'" + reviewer_id + "\'"
cursor.execute(sql_query)
conn.commit()
print(cursor.rowcount, "row successfully deleted from reviewers table")
cursor.close()
except Error as e:
print("Failed to connect due to ", e)
finally:
if conn is not None and conn.is_connected():
conn.close()
print('Disconnected from the database')
connect_run()
|
{"/tests/validate_credit_card_test.py": ["/credit_card/validation.py"], "/airlineReservationAndBooking/airline.py": ["/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/flight_details.py"], "/airlineReservationAndBooking/flight_booking.py": ["/airlineReservationAndBooking/reservation.py"], "/airlineReservationAndBooking/aeroplane.py": ["/airlineReservationAndBooking/seat.py"], "/tests/test_calculator_oop.py": ["/calculator/calculator_oop.py"], "/tests/test_calculator_functions.py": ["/calculator/CalculatorFunctions.py"], "/airlineReservationAndBooking/payment.py": ["/airlineReservationAndBooking/airline.py"], "/tests/airline_reservation_and_booking_tests.py": ["/airlineReservationAndBooking/boarding_pass.py", "/airlineReservationAndBooking/airline.py", "/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/passenger.py", "/airlineReservationAndBooking/reservation.py", "/airlineReservationAndBooking/seat_class.py", "/airlineReservationAndBooking/flight_booking.py", "/airlineReservationAndBooking/payment.py", "/airlineReservationAndBooking/payment_type.py", "/airlineReservationAndBooking/admin.py"]}
|
13,173
|
olu-damilare/hatchlings
|
refs/heads/main
|
/movies_review/connect_movie.py
|
import mysql.connector
import stdiomask
from mysql.connector import Error
def connect_insert():
conn = None
user_host = input('Input the name of the host server: ')
user_database = input("What database do you want to work with? ")
username = input('Enter your username: ')
user_password = stdiomask.getpass(prompt ='Enter your password: ', mask = '*')
try:
conn = mysql.connector.connect(host = user_host, database = user_database, user = username, password = user_password)
if conn.is_connected:
print('\nConnected to the database server')
list_vals = []
cursor = conn.cursor(dictionary = True)
table = input("What table in the {} database do you want to work with? ".format(user_database))
user_selection = int(input("Press 1 to insert into {} table \nPress 2 to update {} table \nPress 3 to delete row from {} table\n\n".format(table, table, table)))
if user_selection == 1:
row_num = int(input('How many rows do you want to insert? '))
for i in range(row_num):
print('\nRow', i+1)
title = input("Enter the title of the movie: ")
release_year = input("Enter the year which the movie was released: ")
genre = input("Enter the genre of the movie: ")
collection_in_mil = input("Enter the sales value of the movie in million: ")
val = (title, release_year, genre, collection_in_mil)
list_vals.append(val)
print()
sql_query = "Insert into {} (title, release_year, genre, collection_in_mil) Values (%s, %s, %s, %s);".format(table)
cursor.executemany(sql_query, list_vals)
conn.commit()
print(cursor.rowcount, ' row was inserted')
elif user_selection == 2:
number_of_columns = int(input("How many fields do you want to update? "))
for i in range(number_of_columns):
column_name = input("Enter column name: ")
new_value = input("Enter the new value: ")
sql_query = "Update movies set " + column_name + " = " + "\'" + new_value + "\' where id = " + str(id)
cursor.execute(sql_query)
conn.commit()
print("field successfully updated in movies table")
elif user_selection == 3:
number_of_rows = int(input("How many rows do you want to delete? "))
for i in range(number_of_rows):
value = input("Enter the key value of the row(s) to be deleted: ")
column_name = input("Enter column name where the column exists: ")
sql_query = "delete from movies where " + column_name + " = " + "\'" + value + "\'"
cursor.execute(sql_query)
conn.commit()
print(cursor.rowcount, "row successfully deleted from movies table")
cursor.close()
except Error as e:
print("Failed to connect due to ", e)
finally:
if conn is not None and conn.is_connected():
conn.close()
print('Disconnected from the database')
connect_insert()
|
{"/tests/validate_credit_card_test.py": ["/credit_card/validation.py"], "/airlineReservationAndBooking/airline.py": ["/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/flight_details.py"], "/airlineReservationAndBooking/flight_booking.py": ["/airlineReservationAndBooking/reservation.py"], "/airlineReservationAndBooking/aeroplane.py": ["/airlineReservationAndBooking/seat.py"], "/tests/test_calculator_oop.py": ["/calculator/calculator_oop.py"], "/tests/test_calculator_functions.py": ["/calculator/CalculatorFunctions.py"], "/airlineReservationAndBooking/payment.py": ["/airlineReservationAndBooking/airline.py"], "/tests/airline_reservation_and_booking_tests.py": ["/airlineReservationAndBooking/boarding_pass.py", "/airlineReservationAndBooking/airline.py", "/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/passenger.py", "/airlineReservationAndBooking/reservation.py", "/airlineReservationAndBooking/seat_class.py", "/airlineReservationAndBooking/flight_booking.py", "/airlineReservationAndBooking/payment.py", "/airlineReservationAndBooking/payment_type.py", "/airlineReservationAndBooking/admin.py"]}
|
13,174
|
olu-damilare/hatchlings
|
refs/heads/main
|
/calculator/calculator_oop.py
|
class Calculator(object):
@classmethod
def add(cls, num1: int, num2: int):
return num1 + num2
@classmethod
def subtract(cls, param: int, param1: int):
return param - param1
@classmethod
def multiply(cls, param: int, param1: int):
if isinstance(param, int) and isinstance(param1, int):
return param * param1
else:
raise TypeError()
@classmethod
def divide(cls, param, param1):
return param // param1
|
{"/tests/validate_credit_card_test.py": ["/credit_card/validation.py"], "/airlineReservationAndBooking/airline.py": ["/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/flight_details.py"], "/airlineReservationAndBooking/flight_booking.py": ["/airlineReservationAndBooking/reservation.py"], "/airlineReservationAndBooking/aeroplane.py": ["/airlineReservationAndBooking/seat.py"], "/tests/test_calculator_oop.py": ["/calculator/calculator_oop.py"], "/tests/test_calculator_functions.py": ["/calculator/CalculatorFunctions.py"], "/airlineReservationAndBooking/payment.py": ["/airlineReservationAndBooking/airline.py"], "/tests/airline_reservation_and_booking_tests.py": ["/airlineReservationAndBooking/boarding_pass.py", "/airlineReservationAndBooking/airline.py", "/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/passenger.py", "/airlineReservationAndBooking/reservation.py", "/airlineReservationAndBooking/seat_class.py", "/airlineReservationAndBooking/flight_booking.py", "/airlineReservationAndBooking/payment.py", "/airlineReservationAndBooking/payment_type.py", "/airlineReservationAndBooking/admin.py"]}
|
13,175
|
olu-damilare/hatchlings
|
refs/heads/main
|
/airlineReservationAndBooking/flight_booking.py
|
from airlineReservationAndBooking.reservation import Reservation
class FlightBooking(object):
booked_seats = []
def book_with_reservation_id(self, reservation_id):
reserved_passenger = Reservation.get_passenger(reservation_id)
if reserved_passenger.get_seat_class() == "FIRSTCLASS":
seat_count = self.get_total_number_of_first_class_seats_booked()
if seat_count < 10 and not self.__passenger_has_booked(reserved_passenger):
self.booked_seats.append(reserved_passenger)
reserved_passenger.set_booked_status(True)
seat_number = seat_count + 1
reserved_passenger.assign_seat_number(seat_number)
else:
return "No available first class seats"
elif reserved_passenger.get_seat_class() == "BUSINESS":
seat_count = self.get_total_number_of_business_class_seats_booked()
if seat_count < 20 and not self.__passenger_has_booked(reserved_passenger):
self.booked_seats.append(reserved_passenger)
reserved_passenger.set_booked_status(True)
seat_number = seat_count + 11
reserved_passenger.assign_seat_number(seat_number)
else:
return "No available Business class seats"
elif reserved_passenger.get_seat_class() == "ECONOMY":
seat_count = self.get_total_number_of_economy_class_seats_booked()
if seat_count < 20 and not self.__passenger_has_booked(reserved_passenger):
self.booked_seats.append(reserved_passenger)
reserved_passenger.set_booked_status(True)
seat_number = seat_count + 31
reserved_passenger.assign_seat_number(seat_number)
else:
return "No available Economy class seats"
def get_total_count_of_seats_booked(self):
return len(self.booked_seats)
@classmethod
def get_booked_seat_type(cls, passenger):
for booked_passenger in cls.booked_seats:
if booked_passenger == passenger:
return booked_passenger.get_seat_class()
def __passenger_has_booked(self, passenger):
passenger_has_booked = False
for i in self.booked_seats:
if i == passenger:
passenger_has_booked = True
break
return passenger_has_booked
def book_flight(self, passenger, seat_class):
if seat_class == "FIRSTCLASS":
seat_count = self.get_total_number_of_first_class_seats_booked()
if seat_count < 10:
if not self.__passenger_has_booked(passenger):
self.booked_seats.append(passenger)
passenger.set_seat_class(seat_class)
passenger.set_booked_status(True)
seat_number = seat_count + 1
passenger.assign_seat_number(seat_number)
else:
return "No available first class seats"
elif seat_class == "BUSINESS":
seat_count = self.get_total_number_of_business_class_seats_booked()
if seat_count < 10:
if not self.__passenger_has_booked(passenger):
self.booked_seats.append(passenger)
passenger.set_seat_class(seat_class)
passenger.set_booked_status(True)
seat_number = seat_count + 11
passenger.assign_seat_number(seat_number)
else:
return "No available Business class seats"
elif seat_class == "ECONOMY":
seat_count = self.get_total_number_of_economy_class_seats_booked()
if seat_count < 10:
if not self.__passenger_has_booked(passenger):
self.booked_seats.append(passenger)
passenger.set_seat_class(seat_class)
passenger.set_booked_status(True)
seat_number = seat_count + 31
passenger.assign_seat_number(seat_number)
else:
return "No available economy class seats"
def get_total_number_of_first_class_seats_booked(self):
counter = 0
for passenger in self.booked_seats:
if passenger.get_seat_class() == "FIRSTCLASS":
counter += 1
return counter
def get_total_number_of_business_class_seats_booked(self):
counter = 0
for passenger in self.booked_seats:
if passenger.get_seat_class() == "BUSINESS":
counter += 1
return counter
def get_total_number_of_economy_class_seats_booked(self):
counter = 0
for passenger in self.booked_seats:
if passenger.get_seat_class() == "ECONOMY":
counter += 1
return counter
def empty_booked_list(self):
self.booked_seats.clear()
@classmethod
def get_passenger_booked_seat_type(cls, passenger):
for booked_passenger in cls.booked_seats:
if booked_passenger == passenger:
return booked_passenger.get_seat_class()
@classmethod
def get_booked_seats(cls):
return cls.booked_seats
|
{"/tests/validate_credit_card_test.py": ["/credit_card/validation.py"], "/airlineReservationAndBooking/airline.py": ["/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/flight_details.py"], "/airlineReservationAndBooking/flight_booking.py": ["/airlineReservationAndBooking/reservation.py"], "/airlineReservationAndBooking/aeroplane.py": ["/airlineReservationAndBooking/seat.py"], "/tests/test_calculator_oop.py": ["/calculator/calculator_oop.py"], "/tests/test_calculator_functions.py": ["/calculator/CalculatorFunctions.py"], "/airlineReservationAndBooking/payment.py": ["/airlineReservationAndBooking/airline.py"], "/tests/airline_reservation_and_booking_tests.py": ["/airlineReservationAndBooking/boarding_pass.py", "/airlineReservationAndBooking/airline.py", "/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/passenger.py", "/airlineReservationAndBooking/reservation.py", "/airlineReservationAndBooking/seat_class.py", "/airlineReservationAndBooking/flight_booking.py", "/airlineReservationAndBooking/payment.py", "/airlineReservationAndBooking/payment_type.py", "/airlineReservationAndBooking/admin.py"]}
|
13,176
|
olu-damilare/hatchlings
|
refs/heads/main
|
/airlineReservationAndBooking/aeroplane.py
|
from airlineReservationAndBooking.seat import Seat
class Aeroplane(object):
def __init__(self, aeroplane_name: str, ):
self.__seats = []
self.__aeroplane_name = aeroplane_name
seat = Seat()
for i in range(50):
self.__seats.append(seat)
def get_total_number_of_seats(self):
return len(self.__seats)
|
{"/tests/validate_credit_card_test.py": ["/credit_card/validation.py"], "/airlineReservationAndBooking/airline.py": ["/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/flight_details.py"], "/airlineReservationAndBooking/flight_booking.py": ["/airlineReservationAndBooking/reservation.py"], "/airlineReservationAndBooking/aeroplane.py": ["/airlineReservationAndBooking/seat.py"], "/tests/test_calculator_oop.py": ["/calculator/calculator_oop.py"], "/tests/test_calculator_functions.py": ["/calculator/CalculatorFunctions.py"], "/airlineReservationAndBooking/payment.py": ["/airlineReservationAndBooking/airline.py"], "/tests/airline_reservation_and_booking_tests.py": ["/airlineReservationAndBooking/boarding_pass.py", "/airlineReservationAndBooking/airline.py", "/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/passenger.py", "/airlineReservationAndBooking/reservation.py", "/airlineReservationAndBooking/seat_class.py", "/airlineReservationAndBooking/flight_booking.py", "/airlineReservationAndBooking/payment.py", "/airlineReservationAndBooking/payment_type.py", "/airlineReservationAndBooking/admin.py"]}
|
13,177
|
olu-damilare/hatchlings
|
refs/heads/main
|
/movies_review/connect_reviewer.py
|
import mysql.connector
from mysql.connector import Error
def connect_insert():
conn = None
try:
conn = mysql.connector.connect(host = 'localhost', database = 'movie_review', user = input('Enter your username: '), password = input('Enter your password: '))
if conn.is_connected:
print('Connected to the database server')
list_vals = []
cursor = conn.cursor(dictionary = True)
user_selection = int(input("Press 1 to insert into Reviewers table \nPress 2 to update Reviewers table \nPress 3 to delete a row from Reviewers table\n"))
if user_selection == 1:
row_num = int(input('How many rows do you want to insert? '))
sql_query = "Insert into Reviewer (first_name, last_name) Values (%s, %s);"
for i in range(row_num):
print('Row', i+1)
first_name = input("Enter the first name: ")
last_name = input("Enter the last name: ")
val = (first_name, last_name)
list_vals.append(val)
print()
cursor.executemany(sql_query, list_vals)
conn.commit()
print(cursor.rowcount, ' row was inserted')
if user_selection == 2:
number_of_columns = int(input("How many fields do you want to update? "))
list = []
for i in range(number_of_columns):
column_name = input("Enter column name: ")
new_value = input("Enter the new value: ")
id = int(input("Enter the reviewer ID: "))
update = column_name + " = " + new_value
sql_query = "Update Reviewer set " + column_name + " = " + "\'" + new_value + "\' where id = " + str(id)
cursor.execute(sql_query)
conn.commit()
print(cursor.rowcount, "row successfully updated in reviewers table")
if user_selection == 3:
number_of_rows = int(input("How many rows do you want to delete? "))
list = []
for i in range(number_of_rows):
value = input("Enter the key value of the row: ")
column_name = input("Enter column name where the column exists: ")
sql_query = "delete from Reviewer where " + column_name + " = " + "\'" + value + "\'"
cursor.execute(sql_query)
conn.commit()
print(cursor.rowcount, "row successfully deleted from reviewers table")
cursor.close()
except Error as e:
print("Failed to connect due to ", e)
finally:
if conn is not None and conn.is_connected():
conn.close()
print('Disconnected from the database')
connect_insert()
|
{"/tests/validate_credit_card_test.py": ["/credit_card/validation.py"], "/airlineReservationAndBooking/airline.py": ["/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/flight_details.py"], "/airlineReservationAndBooking/flight_booking.py": ["/airlineReservationAndBooking/reservation.py"], "/airlineReservationAndBooking/aeroplane.py": ["/airlineReservationAndBooking/seat.py"], "/tests/test_calculator_oop.py": ["/calculator/calculator_oop.py"], "/tests/test_calculator_functions.py": ["/calculator/CalculatorFunctions.py"], "/airlineReservationAndBooking/payment.py": ["/airlineReservationAndBooking/airline.py"], "/tests/airline_reservation_and_booking_tests.py": ["/airlineReservationAndBooking/boarding_pass.py", "/airlineReservationAndBooking/airline.py", "/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/passenger.py", "/airlineReservationAndBooking/reservation.py", "/airlineReservationAndBooking/seat_class.py", "/airlineReservationAndBooking/flight_booking.py", "/airlineReservationAndBooking/payment.py", "/airlineReservationAndBooking/payment_type.py", "/airlineReservationAndBooking/admin.py"]}
|
13,178
|
olu-damilare/hatchlings
|
refs/heads/main
|
/calculator/CalculatorFunctions.py
|
def add(first_number: int, second_number: int):
return first_number + second_number
def subtract(first_number: int, second_number: int):
return first_number - second_number
def multiply(first_number: int, second_number: int):
if isinstance(first_number, int) and isinstance(second_number, int):
return first_number * second_number
else:
raise TypeError(print("number must be of int type"))
def divide(first_number: int, second_number: int):
return int(first_number / second_number)
|
{"/tests/validate_credit_card_test.py": ["/credit_card/validation.py"], "/airlineReservationAndBooking/airline.py": ["/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/flight_details.py"], "/airlineReservationAndBooking/flight_booking.py": ["/airlineReservationAndBooking/reservation.py"], "/airlineReservationAndBooking/aeroplane.py": ["/airlineReservationAndBooking/seat.py"], "/tests/test_calculator_oop.py": ["/calculator/calculator_oop.py"], "/tests/test_calculator_functions.py": ["/calculator/CalculatorFunctions.py"], "/airlineReservationAndBooking/payment.py": ["/airlineReservationAndBooking/airline.py"], "/tests/airline_reservation_and_booking_tests.py": ["/airlineReservationAndBooking/boarding_pass.py", "/airlineReservationAndBooking/airline.py", "/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/passenger.py", "/airlineReservationAndBooking/reservation.py", "/airlineReservationAndBooking/seat_class.py", "/airlineReservationAndBooking/flight_booking.py", "/airlineReservationAndBooking/payment.py", "/airlineReservationAndBooking/payment_type.py", "/airlineReservationAndBooking/admin.py"]}
|
13,179
|
olu-damilare/hatchlings
|
refs/heads/main
|
/airlineReservationAndBooking/payment_type.py
|
class PaymentType(object):
master_card = "MASTERCARD"
visa = "VISA"
|
{"/tests/validate_credit_card_test.py": ["/credit_card/validation.py"], "/airlineReservationAndBooking/airline.py": ["/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/flight_details.py"], "/airlineReservationAndBooking/flight_booking.py": ["/airlineReservationAndBooking/reservation.py"], "/airlineReservationAndBooking/aeroplane.py": ["/airlineReservationAndBooking/seat.py"], "/tests/test_calculator_oop.py": ["/calculator/calculator_oop.py"], "/tests/test_calculator_functions.py": ["/calculator/CalculatorFunctions.py"], "/airlineReservationAndBooking/payment.py": ["/airlineReservationAndBooking/airline.py"], "/tests/airline_reservation_and_booking_tests.py": ["/airlineReservationAndBooking/boarding_pass.py", "/airlineReservationAndBooking/airline.py", "/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/passenger.py", "/airlineReservationAndBooking/reservation.py", "/airlineReservationAndBooking/seat_class.py", "/airlineReservationAndBooking/flight_booking.py", "/airlineReservationAndBooking/payment.py", "/airlineReservationAndBooking/payment_type.py", "/airlineReservationAndBooking/admin.py"]}
|
13,180
|
olu-damilare/hatchlings
|
refs/heads/main
|
/tests/test_calculator_oop.py
|
import unittest
from calculator.calculator_oop import Calculator
class CalculatorTest(unittest.TestCase):
def test_oop_add(self):
self.assertEqual(9, Calculator.add(4, 5))
def test_add_result_type(self):
self.assertIsInstance(Calculator.add(2, 3), int)
def test_add_non_int_type(self):
with self.assertRaises(TypeError):
Calculator.add("1", 1)
def test_illegal_additional_argument(self):
with self.assertRaises(TypeError):
self.assertEqual(Calculator.add(1, -7, 5), -6)
def test_calculator_can_subtract_two_Numbers(self):
self.assertEqual(Calculator.subtract(8, 3), 5)
self.assertEqual(Calculator.subtract(-5, 3), -8)
self.assertEqual(Calculator.subtract(1, -6), 7)
def test_subtract_result_type(self):
self.assertIsInstance(Calculator.subtract(2, 3), int)
def test_subtract_non_int_type(self):
with self.assertRaises(TypeError):
Calculator.subtract("1", 1)
def test_illegal_subtraction_argument(self):
with self.assertRaises(TypeError):
self.assertEqual(Calculator.subtract(1, -7, 5), -6)
def test_calculator_can_multiply_two_Numbers(self):
self.assertEqual(Calculator.multiply(8, 3), 24)
self.assertEqual(Calculator.multiply(-5, 3), -15)
self.assertEqual(Calculator.multiply(1, -6), -6)
def test_multiply_result_type(self):
self.assertIsInstance(Calculator.multiply(2, 3), int)
def test_multiply_non_int_type(self):
with self.assertRaises(TypeError):
Calculator.multiply("1", 1)
def test_illegal_multiplication_argument(self):
with self.assertRaises(TypeError):
self.assertEqual(Calculator.multiply(1, -7, 5), -6)
def test_calculator_can_divide_two_Numbers(self):
self.assertEqual(Calculator.divide(8, 2), 4)
self.assertEqual(Calculator.divide(-15, 3), -5)
self.assertEqual(Calculator.divide(12, -6), -2)
def test_divide_result_type(self):
self.assertIsInstance(Calculator.divide(12, 3), int)
def test_division_non_int_type(self):
with self.assertRaises(TypeError):
Calculator.divide("1", 1)
def test_illegal_division_argument(self):
with self.assertRaises(TypeError):
self.assertEqual(Calculator.divide(14, -7, 5), -2)
|
{"/tests/validate_credit_card_test.py": ["/credit_card/validation.py"], "/airlineReservationAndBooking/airline.py": ["/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/flight_details.py"], "/airlineReservationAndBooking/flight_booking.py": ["/airlineReservationAndBooking/reservation.py"], "/airlineReservationAndBooking/aeroplane.py": ["/airlineReservationAndBooking/seat.py"], "/tests/test_calculator_oop.py": ["/calculator/calculator_oop.py"], "/tests/test_calculator_functions.py": ["/calculator/CalculatorFunctions.py"], "/airlineReservationAndBooking/payment.py": ["/airlineReservationAndBooking/airline.py"], "/tests/airline_reservation_and_booking_tests.py": ["/airlineReservationAndBooking/boarding_pass.py", "/airlineReservationAndBooking/airline.py", "/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/passenger.py", "/airlineReservationAndBooking/reservation.py", "/airlineReservationAndBooking/seat_class.py", "/airlineReservationAndBooking/flight_booking.py", "/airlineReservationAndBooking/payment.py", "/airlineReservationAndBooking/payment_type.py", "/airlineReservationAndBooking/admin.py"]}
|
13,181
|
olu-damilare/hatchlings
|
refs/heads/main
|
/tests/test_calculator_functions.py
|
import unittest
from calculator.CalculatorFunctions import add, subtract, multiply, divide
class CalculatorFunctionTest(unittest.TestCase):
def test_calculator_can_add_two_Numbers(self):
self.assertEqual(add(2, 3), 5)
self.assertEqual(add(-5, 3), -2)
self.assertEqual(add(1, -7), -6)
def test_add_result_type(self):
self.assertIsInstance(add(2, 3), int)
def test_add_non_int_type(self):
with self.assertRaises(TypeError):
add("1", 1)
def test_illegal_additional_argument(self):
with self.assertRaises(TypeError):
self.assertEqual(add(1, -7, 5), -6)
def test_calculator_can_subtract_two_Numbers(self):
self.assertEqual(subtract(8, 3), 5)
self.assertEqual(subtract(-5, 3), -8)
self.assertEqual(subtract(1, -6), 7)
def test_subtract_result_type(self):
self.assertIsInstance(subtract(2, 3), int)
def test_subtract_non_int_type(self):
with self.assertRaises(TypeError):
subtract("1", 1)
def test_illegal_subtraction_argument(self):
with self.assertRaises(TypeError):
self.assertEqual(subtract(1, -7, 5), -6)
def test_calculator_can_multiply_two_Numbers(self):
self.assertEqual(multiply(8, 3), 24)
self.assertEqual(multiply(-5, 3), -15)
self.assertEqual(multiply(1, -6), -6)
def test_multiply_result_type(self):
self.assertIsInstance(multiply(2, 3), int)
def test_multiply_non_int_type(self):
with self.assertRaises(TypeError):
multiply("1", 1)
def test_illegal_multiplication_argument(self):
with self.assertRaises(TypeError):
self.assertEqual(multiply(1, -7, 5), -6)
def test_calculator_can_divide_two_Numbers(self):
self.assertEqual(divide(8, 2), 4)
self.assertEqual(divide(-15, 3), -5)
self.assertEqual(divide(12, -6), -2)
def test_divide_result_type(self):
self.assertIsInstance(divide(12, 3), int)
def test_division_non_int_type(self):
with self.assertRaises(TypeError):
divide("1", 1)
def test_illegal_division_argument(self):
with self.assertRaises(TypeError):
self.assertEqual(divide(14, -7, 5), -2)
if __name__ == '__main__':
unittest.main()
|
{"/tests/validate_credit_card_test.py": ["/credit_card/validation.py"], "/airlineReservationAndBooking/airline.py": ["/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/flight_details.py"], "/airlineReservationAndBooking/flight_booking.py": ["/airlineReservationAndBooking/reservation.py"], "/airlineReservationAndBooking/aeroplane.py": ["/airlineReservationAndBooking/seat.py"], "/tests/test_calculator_oop.py": ["/calculator/calculator_oop.py"], "/tests/test_calculator_functions.py": ["/calculator/CalculatorFunctions.py"], "/airlineReservationAndBooking/payment.py": ["/airlineReservationAndBooking/airline.py"], "/tests/airline_reservation_and_booking_tests.py": ["/airlineReservationAndBooking/boarding_pass.py", "/airlineReservationAndBooking/airline.py", "/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/passenger.py", "/airlineReservationAndBooking/reservation.py", "/airlineReservationAndBooking/seat_class.py", "/airlineReservationAndBooking/flight_booking.py", "/airlineReservationAndBooking/payment.py", "/airlineReservationAndBooking/payment_type.py", "/airlineReservationAndBooking/admin.py"]}
|
13,182
|
olu-damilare/hatchlings
|
refs/heads/main
|
/airlineReservationAndBooking/seat.py
|
class Seat(object):
pass
|
{"/tests/validate_credit_card_test.py": ["/credit_card/validation.py"], "/airlineReservationAndBooking/airline.py": ["/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/flight_details.py"], "/airlineReservationAndBooking/flight_booking.py": ["/airlineReservationAndBooking/reservation.py"], "/airlineReservationAndBooking/aeroplane.py": ["/airlineReservationAndBooking/seat.py"], "/tests/test_calculator_oop.py": ["/calculator/calculator_oop.py"], "/tests/test_calculator_functions.py": ["/calculator/CalculatorFunctions.py"], "/airlineReservationAndBooking/payment.py": ["/airlineReservationAndBooking/airline.py"], "/tests/airline_reservation_and_booking_tests.py": ["/airlineReservationAndBooking/boarding_pass.py", "/airlineReservationAndBooking/airline.py", "/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/passenger.py", "/airlineReservationAndBooking/reservation.py", "/airlineReservationAndBooking/seat_class.py", "/airlineReservationAndBooking/flight_booking.py", "/airlineReservationAndBooking/payment.py", "/airlineReservationAndBooking/payment_type.py", "/airlineReservationAndBooking/admin.py"]}
|
13,183
|
olu-damilare/hatchlings
|
refs/heads/main
|
/con_insert.py
|
import mysql.connector
from mysql.connector import Error
def connect_insert():
conn = None
try:
conn = mysql.connector.connect(host = 'localhost', database = 'demo', user = input('Enter your username: '), password = input('Enter your password: '))
if conn.is_connected:
print('Connected to the datatbase server')
cursor = conn.cursor(dictionary = True)
sql_query = "Insert into Human (humanID, name, color, Gender, bloodgroup) Values (%s, %s, %s, %s, %s)"
row_num = int(input('How many rows do you want to insert? '))
list_vals = []
for i in range(row_num):
print('Row', i+1)
humanID = input("Enter the Human ID: ")
name = input("Enter the name: ")
color = input("Enter the color: ")
gender = input("Enter the gender: ")
blood_group = input("Enter the blood group: ")
val = (humanID, name, color, gender, blood_group)
list_vals.append(val)
print()
cursor.executemany(sql_query, list_vals)
conn.commit()
print(cursor.rowcount, ' row was inserted')
cursor.close()
except Error as e:
print("Failed to connect due to ", e)
finally:
if conn is not None and conn.is_connected():
conn.close()
print('Disconnected from the database')
connect_insert()
|
{"/tests/validate_credit_card_test.py": ["/credit_card/validation.py"], "/airlineReservationAndBooking/airline.py": ["/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/flight_details.py"], "/airlineReservationAndBooking/flight_booking.py": ["/airlineReservationAndBooking/reservation.py"], "/airlineReservationAndBooking/aeroplane.py": ["/airlineReservationAndBooking/seat.py"], "/tests/test_calculator_oop.py": ["/calculator/calculator_oop.py"], "/tests/test_calculator_functions.py": ["/calculator/CalculatorFunctions.py"], "/airlineReservationAndBooking/payment.py": ["/airlineReservationAndBooking/airline.py"], "/tests/airline_reservation_and_booking_tests.py": ["/airlineReservationAndBooking/boarding_pass.py", "/airlineReservationAndBooking/airline.py", "/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/passenger.py", "/airlineReservationAndBooking/reservation.py", "/airlineReservationAndBooking/seat_class.py", "/airlineReservationAndBooking/flight_booking.py", "/airlineReservationAndBooking/payment.py", "/airlineReservationAndBooking/payment_type.py", "/airlineReservationAndBooking/admin.py"]}
|
13,184
|
olu-damilare/hatchlings
|
refs/heads/main
|
/airlineReservationAndBooking/payment.py
|
from airlineReservationAndBooking.airline import Airline
class Payment(object):
def make_payment(self, passenger, amount, seat_class, payment_type):
has_paid = False
if passenger.has_booked():
if seat_class == "FIRSTCLASS":
if amount >= Airline.get_price_of_first_class_seat():
has_paid = True
passenger.set_payment_type(payment_type)
elif seat_class == "BUSINESS":
if amount >= Airline.get_price_of_business_class_seat():
has_paid = True
passenger.set_payment_type(payment_type)
elif seat_class == "ECONOMY":
if amount >= Airline.get_price_of_economy_class_seat():
has_paid = True
passenger.set_payment_type(payment_type)
passenger.make_payment(has_paid)
|
{"/tests/validate_credit_card_test.py": ["/credit_card/validation.py"], "/airlineReservationAndBooking/airline.py": ["/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/flight_details.py"], "/airlineReservationAndBooking/flight_booking.py": ["/airlineReservationAndBooking/reservation.py"], "/airlineReservationAndBooking/aeroplane.py": ["/airlineReservationAndBooking/seat.py"], "/tests/test_calculator_oop.py": ["/calculator/calculator_oop.py"], "/tests/test_calculator_functions.py": ["/calculator/CalculatorFunctions.py"], "/airlineReservationAndBooking/payment.py": ["/airlineReservationAndBooking/airline.py"], "/tests/airline_reservation_and_booking_tests.py": ["/airlineReservationAndBooking/boarding_pass.py", "/airlineReservationAndBooking/airline.py", "/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/passenger.py", "/airlineReservationAndBooking/reservation.py", "/airlineReservationAndBooking/seat_class.py", "/airlineReservationAndBooking/flight_booking.py", "/airlineReservationAndBooking/payment.py", "/airlineReservationAndBooking/payment_type.py", "/airlineReservationAndBooking/admin.py"]}
|
13,185
|
olu-damilare/hatchlings
|
refs/heads/main
|
/airlineReservationAndBooking/boarding_pass.py
|
class BoardingPass(object):
def display_boarding_pass(self, passenger):
return passenger.__str__()
|
{"/tests/validate_credit_card_test.py": ["/credit_card/validation.py"], "/airlineReservationAndBooking/airline.py": ["/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/flight_details.py"], "/airlineReservationAndBooking/flight_booking.py": ["/airlineReservationAndBooking/reservation.py"], "/airlineReservationAndBooking/aeroplane.py": ["/airlineReservationAndBooking/seat.py"], "/tests/test_calculator_oop.py": ["/calculator/calculator_oop.py"], "/tests/test_calculator_functions.py": ["/calculator/CalculatorFunctions.py"], "/airlineReservationAndBooking/payment.py": ["/airlineReservationAndBooking/airline.py"], "/tests/airline_reservation_and_booking_tests.py": ["/airlineReservationAndBooking/boarding_pass.py", "/airlineReservationAndBooking/airline.py", "/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/passenger.py", "/airlineReservationAndBooking/reservation.py", "/airlineReservationAndBooking/seat_class.py", "/airlineReservationAndBooking/flight_booking.py", "/airlineReservationAndBooking/payment.py", "/airlineReservationAndBooking/payment_type.py", "/airlineReservationAndBooking/admin.py"]}
|
13,186
|
olu-damilare/hatchlings
|
refs/heads/main
|
/credit_card/validation.py
|
class CreditCardValidation(object):
def calculate_sum_of_double_even_place(self, credit_card_number):
counter = len(str(credit_card_number)) - 2
self.sum = 0
while counter >= 0:
temp_sum = 2 * int(str(credit_card_number)[counter])
if temp_sum < 10:
self.sum += temp_sum
else:
self.sum += (temp_sum // 10) + (temp_sum % 10)
counter -= 2
return self.sum
def calculate_sum_of_odd_place(self, credit_card_number):
counter = len(str(credit_card_number)) - 1
self.sum = 0
while counter >= 0:
self.sum += int(str(credit_card_number)[counter])
counter -= 2
return self.sum
def isValid(self, credit_card_number):
return (self.calculate_sum_of_odd_place(credit_card_number) +
self.calculate_sum_of_double_even_place(credit_card_number)) % 10 == 0
|
{"/tests/validate_credit_card_test.py": ["/credit_card/validation.py"], "/airlineReservationAndBooking/airline.py": ["/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/flight_details.py"], "/airlineReservationAndBooking/flight_booking.py": ["/airlineReservationAndBooking/reservation.py"], "/airlineReservationAndBooking/aeroplane.py": ["/airlineReservationAndBooking/seat.py"], "/tests/test_calculator_oop.py": ["/calculator/calculator_oop.py"], "/tests/test_calculator_functions.py": ["/calculator/CalculatorFunctions.py"], "/airlineReservationAndBooking/payment.py": ["/airlineReservationAndBooking/airline.py"], "/tests/airline_reservation_and_booking_tests.py": ["/airlineReservationAndBooking/boarding_pass.py", "/airlineReservationAndBooking/airline.py", "/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/passenger.py", "/airlineReservationAndBooking/reservation.py", "/airlineReservationAndBooking/seat_class.py", "/airlineReservationAndBooking/flight_booking.py", "/airlineReservationAndBooking/payment.py", "/airlineReservationAndBooking/payment_type.py", "/airlineReservationAndBooking/admin.py"]}
|
13,187
|
olu-damilare/hatchlings
|
refs/heads/main
|
/tests/airline_reservation_and_booking_tests.py
|
import unittest
from airlineReservationAndBooking.boarding_pass import BoardingPass
from airlineReservationAndBooking.airline import Airline
from airlineReservationAndBooking.aeroplane import Aeroplane
from airlineReservationAndBooking.passenger import Passenger
from airlineReservationAndBooking.reservation import Reservation
from airlineReservationAndBooking.seat_class import SeatClass
from airlineReservationAndBooking.flight_booking import FlightBooking
from airlineReservationAndBooking.payment import Payment
from airlineReservationAndBooking.payment_type import PaymentType
from airlineReservationAndBooking.admin import Admin
class MyTestCase(unittest.TestCase):
def setUp(self) -> None:
self.aeroplane = Aeroplane("Eagle squad")
self.airline = Airline("Imperial Airline", self.aeroplane)
self.reservation = Reservation()
self.passenger = Passenger("Olu Jola", "0000", "bina@jolo.com")
self.flight_booking = FlightBooking()
self.payment = Payment()
self.boarding_pass = BoardingPass()
def tearDown(self) -> None:
self.reservation.empty_reservation_list()
self.flight_booking.empty_booked_list()
def test_that_airline_can_be_created(self):
self.assertEqual("Airline name: Imperial Airline" +
"\nNumber of aeroplanes: 1", self.airline.__str__())
def test_that_airline_can_have_aeroplanes(self):
self.assertEqual(1, self.airline.get_total_number_of_aeroplanes())
second_aeroplane = Aeroplane
self.airline.acquireAeroplane(second_aeroplane)
self.assertEqual(2, self.airline.get_total_number_of_aeroplanes())
def test_that_aeroplane_has_fifty_seats(self):
self.assertEqual(50, self.aeroplane.get_total_number_of_seats())
def test_first_class_reservation(self):
self.reservation.reserve_flight(self.passenger, SeatClass.first_class)
self.assertTrue(self.reservation.has_reserved(self.passenger))
self.assertEqual(1, self.reservation.get_reservation_ID(self.passenger))
self.assertEqual("FIRSTCLASS", self.reservation.get_reserved_seat_class(self.passenger))
def test_business_class_reservation(self):
self.reservation.reserve_flight(self.passenger, SeatClass.business)
self.assertTrue(self.reservation.has_reserved(self.passenger))
self.assertEqual(1, self.reservation.get_reservation_ID(self.passenger))
self.assertEqual("BUSINESS", self.reservation.get_reserved_seat_class(self.passenger))
def test_economy_class_reservation(self):
self.reservation.reserve_flight(self.passenger, SeatClass.economy)
self.assertTrue(self.reservation.has_reserved(self.passenger))
self.assertEqual(1, self.reservation.get_reservation_ID(self.passenger))
self.assertEqual("ECONOMY", self.reservation.get_reserved_seat_class(self.passenger))
def test_multiple_passenger_can_reserve_first_class(self):
self.passenger1 = Passenger("Ade Bajomo", "23543", "dbomo@gmail.com")
self.reservation.reserve_flight(self.passenger, SeatClass.first_class)
self.reservation.reserve_flight(self.passenger1, SeatClass.first_class)
self.assertTrue(self.reservation.has_reserved(self.passenger))
self.assertTrue(self.reservation.has_reserved(self.passenger1))
self.assertEqual(1, self.reservation.get_reservation_ID(self.passenger))
self.assertEqual(2, self.reservation.get_reservation_ID(self.passenger1))
self.assertEqual("FIRSTCLASS", self.reservation.get_reserved_seat_class(self.passenger))
self.assertEqual("FIRSTCLASS", self.reservation.get_reserved_seat_class(self.passenger1))
self.assertEqual(2, self.reservation.get_total_number_reserved_seats())
def test_multiple_passenger_can_reserve_business_class(self):
self.passenger1 = Passenger("Ade Bajomo", "23543", "dbomo@gmail.com")
self.reservation.reserve_flight(self.passenger, SeatClass.business)
self.reservation.reserve_flight(self.passenger1, SeatClass.business)
self.assertTrue(self.reservation.has_reserved(self.passenger))
self.assertTrue(self.reservation.has_reserved(self.passenger1))
self.assertEqual(1, self.reservation.get_reservation_ID(self.passenger))
self.assertEqual(2, self.reservation.get_reservation_ID(self.passenger1))
self.assertEqual("BUSINESS", self.reservation.get_reserved_seat_class(self.passenger))
self.assertEqual("BUSINESS", self.reservation.get_reserved_seat_class(self.passenger1))
self.assertEqual(2, self.reservation.get_total_number_reserved_seats())
def test_multiple_passenger_can_reserve_economy_class(self):
self.passenger1 = Passenger("Ade Bajomo", "23543", "dbomo@gmail.com")
self.reservation.reserve_flight(self.passenger, SeatClass.economy)
self.reservation.reserve_flight(self.passenger1, SeatClass.economy)
self.assertTrue(self.reservation.has_reserved(self.passenger))
self.assertTrue(self.reservation.has_reserved(self.passenger1))
self.assertEqual(1, self.reservation.get_reservation_ID(self.passenger))
self.assertEqual(2, self.reservation.get_reservation_ID(self.passenger1))
self.assertEqual("ECONOMY", self.reservation.get_reserved_seat_class(self.passenger))
self.assertEqual("ECONOMY", self.reservation.get_reserved_seat_class(self.passenger1))
self.assertEqual(2, self.reservation.get_total_number_reserved_seats())
def test_that_passenger_can_cancel_reservation(self):
self.reservation.reserve_flight(self.passenger, SeatClass.economy)
self.assertTrue(self.reservation.has_reserved(self.passenger))
self.assertEqual(1, self.reservation.get_reservation_ID(self.passenger))
self.assertEqual("ECONOMY", self.reservation.get_reserved_seat_class(self.passenger))
reservation_id = self.reservation.get_reservation_ID(self.passenger)
self.reservation.cancelReservation(reservation_id)
self.assertFalse(self.reservation.has_reserved(self.passenger))
self.assertEqual(0, self.reservation.get_total_number_reserved_seats())
self.assertIsNone(self.reservation.get_reserved_seat_class(self.passenger))
def test_that_passenger_can_book_first_class_with_reservation_id(self):
self.reservation.reserve_flight(self.passenger, SeatClass.first_class)
self.assertEqual(1, self.reservation.get_total_number_reserved_seats())
reservation_id = self.reservation.get_reservation_ID(self.passenger)
self.flight_booking.book_with_reservation_id(reservation_id)
self.assertEqual(1, self.flight_booking.get_total_count_of_seats_booked())
self.assertEqual("FIRSTCLASS", FlightBooking.get_booked_seat_type(self.passenger))
def test_that_passenger_can_book_economy_class_with_reservation_id(self):
self.reservation.reserve_flight(self.passenger, SeatClass.economy)
self.passenger1 = Passenger("Ade Bajomo", "23543", "dbomo@gmail.com")
self.reservation.reserve_flight(self.passenger1, SeatClass.first_class)
self.assertEqual(2, self.reservation.get_total_number_reserved_seats())
reservation_id = self.reservation.get_reservation_ID(self.passenger)
self.flight_booking.book_with_reservation_id(reservation_id)
self.assertEqual(1, self.flight_booking.get_total_count_of_seats_booked())
self.assertEqual("ECONOMY", FlightBooking.get_booked_seat_type(self.passenger))
def test_that_passenger_can_book_business_class_with_reservation_id(self):
self.reservation.reserve_flight(self.passenger, SeatClass.business)
self.assertEqual(1, self.reservation.get_total_number_reserved_seats())
reservation_id = self.reservation.get_reservation_ID(self.passenger)
self.flight_booking.book_with_reservation_id(reservation_id)
self.assertEqual(1, self.flight_booking.get_total_number_of_business_class_seats_booked())
self.assertEqual(1, self.flight_booking.get_total_count_of_seats_booked())
self.assertEqual("BUSINESS", FlightBooking.get_booked_seat_type(self.passenger))
def test_that_same_reservation_id_cannot_be_used_to_book_a_flight_twice(self):
self.reservation.reserve_flight(self.passenger, SeatClass.first_class)
self.assertEqual(1, self.reservation.get_total_number_reserved_seats())
reservation_id = self.reservation.get_reservation_ID(self.passenger)
self.flight_booking.book_with_reservation_id(reservation_id)
self.assertEqual(1, self.flight_booking.get_total_count_of_seats_booked())
self.assertEqual("FIRSTCLASS", FlightBooking.get_booked_seat_type(self.passenger))
self.flight_booking.book_with_reservation_id(reservation_id)
self.assertEqual(1, self.flight_booking.get_total_count_of_seats_booked())
def test_that_passenger_can_book_first_class_without_first_reserving_seat(self):
self.flight_booking.book_flight(self.passenger, SeatClass.first_class)
self.assertEqual(1, self.flight_booking.get_total_count_of_seats_booked())
self.assertEqual("FIRSTCLASS", FlightBooking.get_booked_seat_type(self.passenger))
def test_that_passenger_can_book_business_class_without_first_reserving_seat(self):
self.flight_booking.book_flight(self.passenger, SeatClass.business)
self.assertEqual(1, self.flight_booking.get_total_count_of_seats_booked())
self.assertEqual("BUSINESS", FlightBooking.get_booked_seat_type(self.passenger))
def test_that_passenger_can_book_economy_class_without_first_reserving_seat(self):
self.flight_booking.book_flight(self.passenger, SeatClass.economy)
self.assertEqual(1, self.flight_booking.get_total_count_of_seats_booked())
self.assertEqual("ECONOMY", FlightBooking.get_booked_seat_type(self.passenger))
def test_that_only_ten_first_class_seats_can_be_booked(self):
passenger_1 = Passenger("Olu Jola", "0000", "bina@jolo.com")
passenger_2 = Passenger("Olu Jola", "0000", "bina@jolo.com")
passenger_3 = Passenger("Olu Jola", "0000", "bina@jolo.com")
passenger_4 = Passenger("Olu Jola", "0000", "bina@jolo.com")
passenger_5 = Passenger("Olu Jola", "0000", "bina@jolo.com")
passenger_6 = Passenger("Olu Jola", "0000", "bina@jolo.com")
passenger_7 = Passenger("Olu Jola", "0000", "bina@jolo.com")
passenger_8 = Passenger("Olu Jola", "0000", "bina@jolo.com")
passenger_9 = Passenger("Olu Jola", "0000", "bina@jolo.com")
passenger_10 = Passenger("Olu Jola", "0000", "bina@jolo.com")
passenger_11 = Passenger("Olu Jola", "0000", "bina@jolo.com")
self.flight_booking.book_flight(passenger_1, SeatClass.first_class)
self.flight_booking.book_flight(passenger_2, SeatClass.first_class)
self.flight_booking.book_flight(passenger_3, SeatClass.first_class)
self.flight_booking.book_flight(passenger_4, SeatClass.first_class)
self.flight_booking.book_flight(passenger_5, SeatClass.first_class)
self.flight_booking.book_flight(passenger_6, SeatClass.first_class)
self.flight_booking.book_flight(passenger_7, SeatClass.first_class)
self.flight_booking.book_flight(passenger_8, SeatClass.first_class)
self.flight_booking.book_flight(passenger_9, SeatClass.first_class)
self.flight_booking.book_flight(passenger_10, SeatClass.first_class)
self.flight_booking.book_flight(passenger_11, SeatClass.first_class)
self.assertEqual(10, self.flight_booking.get_total_number_of_first_class_seats_booked())
self.assertEqual(10, self.flight_booking.get_total_count_of_seats_booked())
def test_that_airline_can_set_the_price_of_first_class_booking_pass(self):
self.airline.set_price_of_first_class(1000)
self.assertEqual(1000, self.airline.get_price_of_first_class_seat())
def test_that_airline_can_set_the_price_of_business_class_booking_pass(self):
self.airline.set_price_of_business_class(700)
self.assertEqual(700, self.airline.get_price_of_business_class_seat())
def test_that_airline_can_set_the_price_of_economy_class_booking_pass(self):
self.airline.set_price_of_business_class(500)
self.assertEqual(500, self.airline.get_price_of_business_class_seat())
def test_that_passenger_can_make_payment_for_first_class_booking_pass(self):
self.flight_booking.book_flight(self.passenger, SeatClass.first_class)
self.assertEqual(1, self.flight_booking.get_total_number_of_first_class_seats_booked())
self.assertEqual(SeatClass.first_class, FlightBooking.get_passenger_booked_seat_type(self.passenger))
self.airline.set_price_of_first_class(1000)
self.assertEqual(1000, self.airline.get_price_of_first_class_seat())
self.payment.make_payment(self.passenger, 1000, SeatClass.first_class, PaymentType.master_card)
self.assertTrue(self.passenger.has_paid())
self.assertEqual(PaymentType.master_card, self.passenger.get_payment_type())
def test_that_passenger_can_make_payment_for_business_class_booking_pass(self):
self.flight_booking.book_flight(self.passenger, SeatClass.business)
self.assertEqual(1, self.flight_booking.get_total_number_of_business_class_seats_booked())
self.assertEqual(SeatClass.business, FlightBooking.get_passenger_booked_seat_type(self.passenger))
self.airline.set_price_of_business_class(700)
self.assertEqual(700, self.airline.get_price_of_business_class_seat())
self.payment.make_payment(self.passenger, 700, SeatClass.business, PaymentType.visa)
self.assertTrue(self.passenger.has_paid())
self.assertEqual(PaymentType.visa, self.passenger.get_payment_type())
def test_that_passenger_can_make_payment_for_economy_class_booking_pass(self):
self.flight_booking.book_flight(self.passenger, SeatClass.economy)
self.assertEqual(1, self.flight_booking.get_total_number_of_economy_class_seats_booked())
self.assertEqual(SeatClass.economy, FlightBooking.get_passenger_booked_seat_type(self.passenger))
self.airline.set_price_of_economy_class(500)
self.assertEqual(500, self.airline.get_price_of_economy_class_seat())
self.payment.make_payment(self.passenger, 500, SeatClass.economy, PaymentType.master_card)
self.assertTrue(self.passenger.has_paid())
self.assertEqual(PaymentType.master_card, self.passenger.get_payment_type())
def testThatPassengerCannotMakePaymentWithoutBookingFlight(self):
self.airline.set_price_of_economy_class(500)
self.assertEqual(500, self.airline.get_price_of_economy_class_seat())
self.payment.make_payment(self.passenger, 500, SeatClass.economy, PaymentType.master_card)
self.assertFalse(self.passenger.has_paid())
def test_that_passenger_cannot_make_payment_for_first_class_with_insufficient_amount(self):
self.flight_booking.book_flight(self.passenger, SeatClass.first_class)
self.assertEqual(1, self.flight_booking.get_total_number_of_first_class_seats_booked())
self.assertEqual(SeatClass.first_class, FlightBooking.get_passenger_booked_seat_type(self.passenger))
self.airline.set_price_of_first_class(1000)
self.assertEqual(1000, self.airline.get_price_of_first_class_seat())
self.payment.make_payment(self.passenger, 900, SeatClass.first_class, PaymentType.master_card)
self.assertFalse(self.passenger.has_paid())
self.assertIsNone(self.passenger.get_payment_type())
def test_that_passenger_cannot_make_payment_for_business_class_with_insufficient_amount(self):
self.flight_booking.book_flight(self.passenger, SeatClass.business)
self.assertEqual(1, self.flight_booking.get_total_number_of_business_class_seats_booked())
self.assertEqual(SeatClass.business, FlightBooking.get_passenger_booked_seat_type(self.passenger))
self.airline.set_price_of_business_class(700)
self.assertEqual(700, self.airline.get_price_of_business_class_seat())
self.payment.make_payment(self.passenger, 500, SeatClass.business, PaymentType.master_card)
self.assertFalse(self.passenger.has_paid())
self.assertIsNone(self.passenger.get_payment_type())
def test_that_passenger_cannot_make_payment_for_economy_class_with_insufficient_amount(self):
self.flight_booking.book_flight(self.passenger, SeatClass.economy)
self.assertEqual(1, self.flight_booking.get_total_number_of_economy_class_seats_booked())
self.assertEqual(SeatClass.economy, FlightBooking.get_passenger_booked_seat_type(self.passenger))
self.airline.set_price_of_economy_class(500)
self.assertEqual(500, self.airline.get_price_of_economy_class_seat())
self.payment.make_payment(self.passenger, 300, SeatClass.economy, PaymentType.visa)
self.assertFalse(self.passenger.has_paid())
self.assertIsNone(self.passenger.get_payment_type())
def test_that_boarding_pass_info_can_be_generated_with_passenger_details(self):
self.flight_booking.book_flight(self.passenger, SeatClass.business)
self.assertEqual(1, self.flight_booking.get_total_number_of_business_class_seats_booked())
self.assertEqual(SeatClass.business, FlightBooking.get_passenger_booked_seat_type(self.passenger))
self.airline.set_price_of_business_class(700)
self.assertEqual(700, self.airline.get_price_of_business_class_seat())
self.payment.make_payment(self.passenger, 700, SeatClass.business, PaymentType.visa)
self.assertTrue(self.passenger.has_paid())
self.assertEqual(PaymentType.visa, self.passenger.get_payment_type())
self.assertEqual("Full Name = Olu Jola\nPhone number = 0000\nEmail address = bina@jolo.com\nSeat class = "
"BUSINESS\nSeat number = 11\nPayment type = VISA""",
self.boarding_pass.display_boarding_pass(self.passenger))
def test_that_airline_can_generate_flight_details(self):
self.flight_booking.book_flight(self.passenger, SeatClass.first_class)
self.airline.set_price_of_first_class(1000)
self.assertEqual(1000, Airline.get_price_of_first_class_seat())
self.payment.make_payment(self.passenger, 1000, SeatClass.first_class, PaymentType.master_card)
self.assertTrue(self.passenger.has_paid())
self.assertEqual(PaymentType.master_card, self.passenger.get_payment_type())
passenger_1 = Passenger("Ben CHi", "1235660", "ba@jasiilo.com")
self.flight_booking.book_flight(passenger_1, SeatClass.business)
self.airline.set_price_of_business_class(700)
self.assertEqual(700, Airline.get_price_of_business_class_seat())
self.payment.make_payment(passenger_1, 700, SeatClass.business, PaymentType.visa)
self.assertTrue(passenger_1.has_paid())
self.assertEqual(PaymentType.visa, passenger_1.get_payment_type())
flight_number = self.airline.generate_flight_number()
pilot = Admin("Joe Bloggs", "08012345678", "dolo@gmail.com", "12345")
self.airline.assign_pilot(pilot, flight_number)
host = Admin("Joe Bost", "08012345678", "dolo@gmail.com", "12345")
self.airline.assign_host(host, flight_number)
self.airline.board_passenger(self.passenger, flight_number)
self.airline.board_passenger(passenger_1, flight_number)
self.assertEqual("""Flight Details:\nNumber of passengers = 2\nFlight number = 1\n\nHost Details:\nFull Name = Joe Bost\nPhone number = 08012345678\nEmail address = dolo@gmail.com\nStaff ID = 12345\n\nPilot Details:\nFull Name = Joe Bloggs\nPhone number = 08012345678\nEmail address = dolo@gmail.com\nStaff ID = 12345\n\nPassengers Information:\n\nFull Name = Olu Jola\nPhone number = 0000\nEmail address = bina@jolo.com\nSeat class = FIRSTCLASS\nSeat number = 1\nPayment type = MASTERCARD\n\nFull Name = Ben CHi\nPhone number = 1235660\nEmail address = ba@jasiilo.com\nSeat class = BUSINESS\nSeat number = 11\nPayment type = VISA
""", self.airline.generate_flight_details(flight_number))
|
{"/tests/validate_credit_card_test.py": ["/credit_card/validation.py"], "/airlineReservationAndBooking/airline.py": ["/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/flight_details.py"], "/airlineReservationAndBooking/flight_booking.py": ["/airlineReservationAndBooking/reservation.py"], "/airlineReservationAndBooking/aeroplane.py": ["/airlineReservationAndBooking/seat.py"], "/tests/test_calculator_oop.py": ["/calculator/calculator_oop.py"], "/tests/test_calculator_functions.py": ["/calculator/CalculatorFunctions.py"], "/airlineReservationAndBooking/payment.py": ["/airlineReservationAndBooking/airline.py"], "/tests/airline_reservation_and_booking_tests.py": ["/airlineReservationAndBooking/boarding_pass.py", "/airlineReservationAndBooking/airline.py", "/airlineReservationAndBooking/aeroplane.py", "/airlineReservationAndBooking/passenger.py", "/airlineReservationAndBooking/reservation.py", "/airlineReservationAndBooking/seat_class.py", "/airlineReservationAndBooking/flight_booking.py", "/airlineReservationAndBooking/payment.py", "/airlineReservationAndBooking/payment_type.py", "/airlineReservationAndBooking/admin.py"]}
|
13,206
|
assassinen/hyperquant
|
refs/heads/master
|
/hyperquant/clients/tests/test_init.py
|
import logging
import time
from datetime import datetime
from unittest import TestCase
from hyperquant.api import Sorting, Interval, OrderType, Direction
from hyperquant.clients import Error, ErrorCode, ParamName, ProtocolConverter, \
Endpoint, DataObject, Order, OrderBook
from hyperquant.clients.tests.utils import wait_for, AssertUtil, set_up_logging
from hyperquant.clients.utils import create_ws_client, create_rest_client
set_up_logging()
# Converter
class TestConverter(TestCase):
converter_class = ProtocolConverter
def setUp(self):
super().setUp()
# def test_(self):
# pass
# Common client
class TestClient(TestCase):
is_rest = None
platform_id = None
version = None
is_sorting_supported = False
testing_symbol = "EOSETH"
testing_symbols = ["EOSETH", "BNBBTC"]
wrong_symbol = "XXXYYY"
client = None
client_authed = None
def setUp(self):
self.skipIfBase()
super().setUp()
if self.is_rest:
self.client = create_rest_client(self.platform_id, version=self.version)
self.client_authed = create_rest_client(self.platform_id, True, self.version)
else:
self.client = create_ws_client(self.platform_id, version=self.version)
self.client_authed = create_ws_client(self.platform_id, True, self.version)
def tearDown(self):
self.client.close()
super().tearDown()
def skipIfBase(self):
if self.platform_id is None:
self.skipTest("Skip base class")
# Utility
def _result_info(self, result, sorting):
is_asc_sorting = sorting == Sorting.ASCENDING
items_info = "%s first: %s last: %s sort-ok: %s " % (
"ASC" if is_asc_sorting else "DESC",
self._str_item(result[0]) if result else "-",
self._str_item(result[-1]) if result else "-",
(result[0].timestamp < result[-1].timestamp if is_asc_sorting
else result[0].timestamp > result[-1].timestamp) if result else "-")
return items_info + "count: %s" % (len(result) if result else "-")
def _str_item(self, item):
# return str(item.item_id) + " " + str(item.timestamp / 100000)
# return str(item.timestamp / 100000)
dt = datetime.utcfromtimestamp(item.timestamp)
return dt.isoformat()
def assertRightSymbols(self, items):
if self.testing_symbol:
for item in items:
# was: item.symbol = self.testing_symbol
self.assertEqual(item.symbol, item.symbol.upper())
self.assertEqual(item.symbol, self.testing_symbol)
else:
# For Trades in BitMEX
symbols = set([item.symbol for item in items])
self.assertGreater(len(symbols), 1)
# self.assertGreater(len(symbols), 10)
# (Assert items)
def assertItemIsValid(self, trade, testing_symbol_or_symbols=None):
if not testing_symbol_or_symbols:
testing_symbol_or_symbols = self.testing_symbol
AssertUtil.assertItemIsValid(self, trade, testing_symbol_or_symbols, self.platform_id)
def assertTradeIsValid(self, trade, testing_symbol_or_symbols=None):
if not testing_symbol_or_symbols:
testing_symbol_or_symbols = self.testing_symbol
AssertUtil.assertTradeIsValid(self, trade, testing_symbol_or_symbols, self.platform_id)
def assertMyTradeIsValid(self, my_trade, testing_symbol_or_symbols=None):
if not testing_symbol_or_symbols:
testing_symbol_or_symbols = self.testing_symbol
AssertUtil.assertMyTradeIsValid(self, my_trade, testing_symbol_or_symbols, self.platform_id)
def assertCandleIsValid(self, candle, testing_symbol_or_symbols=None):
if not testing_symbol_or_symbols:
testing_symbol_or_symbols = self.testing_symbol
AssertUtil.assertCandleIsValid(self, candle, testing_symbol_or_symbols, self.platform_id)
def assertTickerIsValid(self, ticker, testing_symbol_or_symbols=None):
# if not testing_symbol_or_symbols:
# testing_symbol_or_symbols = self.testing_symbol
AssertUtil.assertTickerIsValid(self, ticker, testing_symbol_or_symbols, self.platform_id)
def assertOrderBookIsValid(self, order_book, testing_symbol_or_symbols=None):
if not testing_symbol_or_symbols:
testing_symbol_or_symbols = self.testing_symbol
AssertUtil.assertOrderBookIsValid(self, order_book, testing_symbol_or_symbols, self.platform_id)
def assertOrderBookDiffIsValid(self, order_book, testing_symbol_or_symbols=None):
if not testing_symbol_or_symbols:
testing_symbol_or_symbols = self.testing_symbol
AssertUtil.assertOrderBookDiffIsValid(self, order_book, testing_symbol_or_symbols, self.platform_id)
# def assertOrderBookItemIsValid(self, order_book_item, testing_symbol_or_symbols=None):
# if not testing_symbol_or_symbols:
# testing_symbol_or_symbols = self.testing_symbol
#
# AssertUtil.assertOrderBookItemIsValid(self, order_book_item, testing_symbol_or_symbols, self.platform_id)
def assertAccountIsValid(self, account):
AssertUtil.assertAccountIsValid(self, account, self.platform_id)
def assertOrderIsValid(self, order, testing_symbol_or_symbols=None):
if not testing_symbol_or_symbols:
testing_symbol_or_symbols = self.testing_symbol
AssertUtil.assertOrderIsValid(self, order, testing_symbol_or_symbols, self.platform_id)
# REST
class BaseTestRESTClient(TestClient):
is_rest = True
# (If False then platform supposed to use its max_limit instead
# of returning error when we send too big limit)
has_limit_error = False
is_symbol_case_sensitive = True
is_rate_limit_error = False
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.is_rate_limit_error = False
def setUp(self):
self.skipIfRateLimit()
super().setUp()
def assertGoodResult(self, result, is_iterable=True, message=None):
if isinstance(result, Error) and result.code == ErrorCode.RATE_LIMIT:
self.__class__.is_rate_limit_error = True
self.skipIfRateLimit()
self.assertIsNotNone(result, message)
self.assertNotIsInstance(result, Error, message or Error)
if is_iterable:
self.assertGreater(len(result), 0, message)
def assertErrorResult(self, result, error_code_expected=None):
if isinstance(result, Error) and result.code == ErrorCode.RATE_LIMIT:
self.__class__.is_rate_limit_error = True
self.skipIfRateLimit()
self.assertIsNotNone(result)
self.assertIsInstance(result, Error)
if error_code_expected is not None:
self.assertEqual(result.code, error_code_expected)
def skipIfRateLimit(self):
if self.__class__.is_rate_limit_error:
self.skipTest("Rate limit reached for this platform. Try again later.")
class TestRESTClient(BaseTestRESTClient):
# Test all methods except history methods
# (All numbers taken from https://api.binance.com/api/v1/exchangeInfo for EOSETH.
# Define your dicts for other platforms in subclasses.)
order_sell_limit_params = {
ParamName.ORDER_TYPE: OrderType.LIMIT,
ParamName.DIRECTION: Direction.SELL,
# todo check to avoid problems
ParamName.PRICE: "0.22",
ParamName.AMOUNT: "0.1",
}
order_buy_market_params = {
ParamName.ORDER_TYPE: OrderType.MARKET,
ParamName.DIRECTION: Direction.BUY,
# todo check to avoid problems
# ParamName.PRICE: "0.000001", # no price for MARKET order
ParamName.AMOUNT: "0.01",
}
order_sell_market_params = {
ParamName.ORDER_TYPE: OrderType.MARKET,
ParamName.DIRECTION: Direction.SELL,
# todo check to avoid problems
# ParamName.PRICE: "0.000001", # no price for MARKET order
ParamName.AMOUNT: "0.01",
}
created_orders = None
def tearDown(self):
# Cancel all created orders
if self.created_orders:
for item in self.created_orders:
self.client_authed.cancel_order(item)
super().tearDown()
# Simple methods
def test_ping(self, is_auth=False):
client = self.client_authed if is_auth else self.client
result = client.ping()
self.assertGoodResult(result, False)
def test_get_server_timestamp(self, is_auth=False):
client = self.client_authed if is_auth else self.client
# With request
client.use_milliseconds = True
result0_ms = result = client.get_server_timestamp(is_refresh=True)
self.assertGoodResult(result, False)
self.assertGreater(result, 1500000000000)
self.assertIsInstance(result, int)
client.use_milliseconds = False
result0_s = result = client.get_server_timestamp(is_refresh=True)
self.assertGoodResult(result, False)
self.assertGreater(result, 1500000000)
self.assertLess(result, 15000000000)
self.assertIsInstance(result, (int, float))
# Cached
client.use_milliseconds = True
result = client.get_server_timestamp(is_refresh=False)
self.assertGoodResult(result, False)
self.assertGreater(result, 1500000000000)
self.assertIsInstance(result, int)
self.assertGreater(result, result0_ms)
client.use_milliseconds = False
result = client.get_server_timestamp(is_refresh=False)
self.assertGoodResult(result, False)
self.assertGreater(result, 1500000000)
self.assertLess(result, 15000000000)
self.assertIsInstance(result, (int, float))
self.assertGreater(result, result0_s)
def test_get_symbols(self, is_auth=False):
client = self.client_authed if is_auth else self.client
result = client.get_symbols()
self.assertGoodResult(result)
self.assertGreater(len(result), 1)
self.assertGreater(len(result), 50)
self.assertIsInstance(result[0], str)
if self.testing_symbol:
self.assertIn(self.testing_symbol, result)
# fetch_trades
def test_fetch_trades(self, method_name="fetch_trades", is_auth=False):
client = self.client_authed if is_auth else self.client
result = getattr(client, method_name)(self.testing_symbol)
self.assertGoodResult(result)
self.assertGreater(len(result), 1)
self.assertGreater(len(result), 50)
self.assertTradeIsValid(result[0])
for item in result:
self.assertTradeIsValid(item)
self.assertRightSymbols(result)
def test_fetch_trades_errors(self, method_name="fetch_trades", is_auth=False):
client = self.client_authed if is_auth else self.client
# Wrong symbol
result = getattr(client, method_name)(self.wrong_symbol)
self.assertIsNotNone(result)
self.assertIsInstance(result, Error)
self.assertEqual(result.code, ErrorCode.WRONG_SYMBOL)
if self.is_symbol_case_sensitive:
# Symbol in lower case as wrong symbol
result = getattr(client, method_name)(self.testing_symbol.lower())
self.assertIsNotNone(result)
self.assertIsInstance(result, Error)
self.assertTrue(result.code == ErrorCode.WRONG_SYMBOL or
result.code == ErrorCode.WRONG_PARAM)
def test_fetch_trades_limit(self, method_name="fetch_trades", is_auth=False):
client = self.client_authed if is_auth else self.client
self.assertFalse(client.converter.is_use_max_limit)
# Test limit
self.assertFalse(client.use_milliseconds)
# client.use_milliseconds = False
result = getattr(client, method_name)(self.testing_symbol, 2)
self.assertGoodResult(result)
self.assertEqual(len(result), 2)
# (Test use_milliseconds)
self.assertLess(result[0].timestamp, time.time())
# Test is_use_max_limit (with limit param)
client.use_milliseconds = True
client.converter.is_use_max_limit = True
result = getattr(client, method_name)(self.testing_symbol, 2)
self.assertGoodResult(result)
self.assertEqual(len(result), 2)
# (Test use_milliseconds)
self.assertGreater(result[0].timestamp, time.time())
# (Get default item count)
result = getattr(client, method_name)(self.testing_symbol)
self.assertGoodResult(result)
default_item_count = len(result)
# Test is_use_max_limit (without limit param)
client.converter.is_use_max_limit = True
result = getattr(client, method_name)(self.testing_symbol)
self.assertGoodResult(result)
self.assertGreaterEqual(len(result), default_item_count, "Sometimes needs retry (for BitMEX, for example)")
for item in result:
self.assertTradeIsValid(item)
self.assertRightSymbols(result)
def test_fetch_trades_limit_is_too_big(self, method_name="fetch_trades", is_auth=False):
client = self.client_authed if is_auth else self.client
# Test limit is too big
too_big_limit = 1000000
result = getattr(client, method_name)(self.testing_symbol, too_big_limit)
self.assertIsNotNone(result)
if self.has_limit_error:
self.assertIsInstance(result, Error)
self.assertErrorResult(result, ErrorCode.WRONG_LIMIT)
else:
self.assertGoodResult(result)
self.assertGreater(len(result), 10)
self.assertLess(len(result), too_big_limit)
for item in result:
self.assertTradeIsValid(item)
self.assertRightSymbols(result)
max_limit_count = len(result)
# Test is_use_max_limit uses the maximum possible limit
client.converter.is_use_max_limit = True
result = getattr(client, method_name)(self.testing_symbol)
self.assertEqual(len(result), max_limit_count, "is_use_max_limit doesn't work")
def test_fetch_trades_sorting(self, method_name="fetch_trades", is_auth=False):
if not self.is_sorting_supported:
self.skipTest("Sorting is not supported by platform.")
client = self.client_authed if is_auth else self.client
self.assertEqual(client.converter.sorting, Sorting.DESCENDING)
# Test descending (default) sorting
result = getattr(client, method_name)(self.testing_symbol)
self.assertGoodResult(result)
self.assertGreater(len(result), 2)
self.assertGreater(result[0].timestamp, result[-1].timestamp)
# Test ascending sorting
client.converter.sorting = Sorting.ASCENDING
result2 = getattr(client, method_name)(self.testing_symbol)
self.assertGoodResult(result2)
self.assertGreater(len(result2), 2)
self.assertLess(result2[0].timestamp, result2[-1].timestamp)
# (not necessary)
# print("TEMP timestamps:", result[0].timestamp, result[-1].timestamp)
# print("TEMP timestamps:", result2[0].timestamp, result2[-1].timestamp)
# # Test that it is the same items for both sorting types
# self.assertGreaterEqual(result2[0].timestamp, result[-1].timestamp)
# self.assertGreaterEqual(result[0].timestamp, result2[-1].timestamp)
# Test that interval of items sorted ascending is far before the interval of descending
self.assertLess(result2[0].timestamp, result[-1].timestamp)
self.assertLess(result2[0].timestamp, result[0].timestamp)
# Other public methods
def test_fetch_candles(self):
client = self.client
testing_interval = Interval.DAY_3
# Error
result = client.fetch_candles(None, None)
self.assertErrorResult(result)
result = client.fetch_candles(self.testing_symbol, None)
self.assertErrorResult(result)
# Good
result = client.fetch_candles(self.testing_symbol, testing_interval)
self.assertGoodResult(result)
for item in result:
self.assertCandleIsValid(item, self.testing_symbol)
self.assertEqual(item.interval, testing_interval)
# todo test from_, to_, and limit
def test_fetch_ticker(self):
client = self.client
# Error
# Good
# Empty params
result = client.fetch_ticker(None)
self.assertGoodResult(result)
self.assertGreater(len(result), 2)
for item in result:
self.assertTickerIsValid(item)
# Full params
result = client.fetch_ticker(self.testing_symbol)
self.assertGoodResult(result, False)
self.assertTickerIsValid(result, self.testing_symbol)
def test_fetch_tickers(self):
client = self.client
# Error
# Good
# Empty params
result = client.fetch_tickers()
self.assertGoodResult(result)
self.assertGreater(len(result), 2)
for item in result:
self.assertTickerIsValid(item)
# Full params
result = client.fetch_tickers(self.testing_symbols)
self.assertGoodResult(result)
self.assertEqual(len(result), len(self.testing_symbols))
for item in result:
self.assertTickerIsValid(item, self.testing_symbols)
def test_fetch_order_book(self):
client = self.client
# Error
# Empty params
result = client.fetch_order_book()
self.assertErrorResult(result)
# Good
# Full params
result = client.fetch_order_book(self.testing_symbol)
self.assertGoodResult(result, False)
self.assertOrderBookIsValid(result)
# todo test limit and is_use_max_limit
# Private API methods
def test_fetch_account_info(self):
client = self.client_authed
# Error
# Good
# Empty params # Full params
result = client.fetch_account_info()
self.assertGoodResult(result, is_iterable=False)
self.assertAccountIsValid(result)
def test_fetch_my_trades(self):
client = self.client_authed
# Error
# Empty params
result = client.fetch_my_trades(None)
self.assertErrorResult(result)
# Good
# Full params
result = client.fetch_my_trades(self.testing_symbol)
NO_ITEMS_FOR_ACCOUNT = True
self.assertGoodResult(result, not NO_ITEMS_FOR_ACCOUNT)
for item in result:
self.assertMyTradeIsValid(item, self.testing_symbols)
# Limit
result = client.fetch_my_trades(self.testing_symbol, 1)
self.assertGoodResult(result, not NO_ITEMS_FOR_ACCOUNT)
self.assertLessEqual(len(result), 1)
result = client.fetch_my_trades(self.testing_symbol, 7)
self.assertGoodResult(result, not NO_ITEMS_FOR_ACCOUNT)
self.assertLessEqual(len(result), 7)
if len(result) < 7:
logging.warning("You have not enough my trades to test limit for sure.")
for item in result:
self.assertMyTradeIsValid(item, self.testing_symbols)
def test_create_order(self):
client = self.client_authed
# Error
# Empty params
result = client.create_order(None, None, None, None, None)
self.assertErrorResult(result)
# Good
# Sell, limit
result = client.create_order(self.testing_symbol, **self.order_sell_limit_params, is_test=True)
self.assertGoodResult(result)
cancel_result = client.cancel_order(result)
self.assertOrderIsValid(result, self.testing_symbol)
self.assertEqual(result.order_type, self.order_sell_limit_params.get(ParamName.ORDER_TYPE))
self.assertEqual(result.direction, self.order_sell_limit_params.get(ParamName.DIRECTION))
self.assertEqual(result.price, self.order_sell_limit_params.get(ParamName.PRICE))
self.assertEqual(result.amount, self.order_sell_limit_params.get(ParamName.AMOUNT))
self._check_canceled(cancel_result)
IS_REAL_MONEY = True
if IS_REAL_MONEY:
return
# Full params
# Buy, market
result = client.create_order(self.testing_symbol, **self.order_buy_market_params, is_test=True)
self.assertGoodResult(result, is_iterable=False)
cancel_result = client.cancel_order(result) # May be not already filled
self.assertOrderIsValid(result, self.testing_symbol)
self.assertEqual(result.order_type, self.order_buy_market_params.get(ParamName.ORDER_TYPE))
self.assertEqual(result.direction, self.order_buy_market_params.get(ParamName.DIRECTION))
self.assertEqual(result.price, self.order_buy_market_params.get(ParamName.PRICE))
self.assertEqual(result.amount, self.order_buy_market_params.get(ParamName.AMOUNT))
self._check_canceled(cancel_result)
# Sell, market - to revert buy-market order
result = client.create_order(self.testing_symbol, **self.order_sell_market_params, is_test=True)
self.assertGoodResult(result, is_iterable=False)
cancel_result = client.cancel_order(result)
self.assertOrderIsValid(result, self.testing_symbol)
self.assertEqual(result.order_type, self.order_sell_market_params.get(ParamName.ORDER_TYPE))
self.assertEqual(result.direction, self.order_sell_market_params.get(ParamName.DIRECTION))
self.assertEqual(result.price, self.order_sell_market_params.get(ParamName.PRICE))
self.assertEqual(result.amount, self.order_sell_market_params.get(ParamName.AMOUNT))
self._check_canceled(cancel_result)
def _create_order(self):
client = self.client_authed
order = client.create_order(self.testing_symbol, **self.order_sell_limit_params, is_test=False)
self.assertOrderIsValid(order)
# Add for canceling in tearDown
if not self.created_orders:
self.created_orders = []
self.created_orders.append(order)
return order
def _check_canceled(self, cancel_result):
self.assertGoodResult(cancel_result, False, "IMPORTANT! Order was created during tests, but not canceled!")
def assertCanceledOrder(self, order, symbol, item_id):
self.assertItemIsValid(order, symbol)
self.assertIsInstance(order, Order)
self.assertEqual(order.item_id, item_id)
def test_cancel_order(self):
client = self.client_authed
# Error
# Empty params
result = client.cancel_order(None)
self.assertErrorResult(result)
# Good
# Full params
order = self._create_order()
result = client.cancel_order(order, "some")
self._check_canceled(result)
# self.assertGoodResult(result)
self.assertNotEqual(result, order)
self.assertCanceledOrder(result, order.symbol, order.item_id)
# Same by item_id and symbol
order = self._create_order()
result = client.cancel_order(order.item_id, order.symbol)
self._check_canceled(result)
# self.assertGoodResult(result)
self.assertIsNot(result, order)
self.assertEqual(result, order)
# self.assertNotEqual(result, order)
self.assertOrderIsValid(result)
self.assertCanceledOrder(result, order.symbol, order.item_id)
def test_check_order(self):
client = self.client_authed
# Error
# Empty params
result = client.check_order(None)
self.assertErrorResult(result)
# temp
result = client.check_order("someid", "somesymb")
# Good
# Full params
order = self._create_order()
result = client.check_order(order, "some")
self.assertGoodResult(result)
self.assertEqual(order, result)
self.assertOrderIsValid(result)
# Same by item_id and symbol
result = client.check_order(order.item_id, order.symbol)
self.assertGoodResult(result)
self.assertEqual(order, result)
self.assertOrderIsValid(result)
cancel_result = client.cancel_order(order)
self._check_canceled(cancel_result)
def test_fetch_orders(self):
client = self.client_authed
# Error
# Good
order = None
order = self._create_order()
# Empty params
# Commented because for Binance it has weight 40
# result = client.fetch_orders()
#
# self.assertGoodResult(result)
# self.assertGreater(len(result), 0)
# for item in result:
# self.assertOrderIsValid(item)
# All
result = client.fetch_orders(self.testing_symbol, is_open=False)
self.assertGoodResult(result)
# self.assertGreater(len(result), 0)
for item in result:
self.assertOrderIsValid(item)
# Full params
result = client.fetch_orders(self.testing_symbol, is_open=True)
self.assertGoodResult(result)
# self.assertGreater(len(result), 0)
for item in result:
self.assertOrderIsValid(item)
cancel_result = client.cancel_order(order)
self._check_canceled(cancel_result)
# All (all open are closed)
result = client.fetch_orders(self.testing_symbol, is_open=False)
self.assertGoodResult(result)
self.assertGreater(len(result), 0)
for item in result:
self.assertOrderIsValid(item)
# todo test also limit and from_item (and to_item? - for binance) for is_open=false
class TestRESTClientHistory(BaseTestRESTClient):
# Test only history methods
is_pagination_supported = True
is_to_item_supported = True
is_to_item_by_id = False
# fetch_history
def test_fetch_history_from_and_to_item(self, endpoint=Endpoint.TRADE, is_auth=True,
timestamp_param=ParamName.TIMESTAMP):
client = self.client_authed if is_auth else self.client
# Limit must be greater than max items with same timestamp (greater than 10 at least)
limit = 50
# (Get items to be used to set from_item, to_item params)
result0 = result = client.fetch_history(endpoint, self.testing_symbol,
sorting=Sorting.DESCENDING, limit=limit)
# print("\n#0", len(result), result)
self.assertGoodResult(result)
self.assertGreater(len(result), 2)
if client.converter.IS_SORTING_ENABLED:
self.assertGreater(result[0].timestamp, result[-1].timestamp)
# Test FROM_ITEM and TO_ITEM
result = client.fetch_history(endpoint, self.testing_symbol,
sorting=Sorting.DESCENDING, # limit=limit,
from_item=result0[0], to_item=result0[-1])
# print("\n#1", len(result), result)
self.assertGoodResult(result)
self.assertGreater(len(result), 2)
self.assertIn(result[0], result0, "Try restart tests.")
# self.assertIn(result[-10], result0, "Try restart tests.")
if self.is_to_item_supported:
self.assertIn(result[-1], result0, "Try restart tests.")
# self.assertEqual(len(result), len(result0))
# self.assertEqual(result, result0)
# Test FROM_ITEM and TO_ITEM in wrong order
result = client.fetch_history(endpoint, self.testing_symbol,
sorting=Sorting.DESCENDING, # limit=limit,
from_item=result0[-1], to_item=result0[0])
# print("\n#2", len(result), result)
self.assertGoodResult(result)
self.assertGreater(len(result), 2)
self.assertIn(result[0], result0, "Try restart tests.")
# self.assertIn(result[-10], result0, "Try restart tests.")
if self.is_to_item_supported:
self.assertIn(result[-1], result0, "Try restart tests.")
# self.assertEqual(len(result), len(result0))
# self.assertEqual(result, result0)
# Test FROM_ITEM and TO_ITEM in wrong order and sorted differently
result = client.fetch_history(endpoint, self.testing_symbol,
sorting=Sorting.ASCENDING, # limit=limit,
from_item=result0[-1], to_item=result0[0])
# print("\n#3", len(result), result)
self.assertGoodResult(result)
self.assertGreater(len(result), 2)
self.assertIn(result[0], result0, "Try restart tests.")
# self.assertIn(result[-10], result0, "Try restart tests.")
if self.is_to_item_supported:
self.assertIn(result[-1], result0, "Try restart tests.")
# self.assertEqual(len(result), len(result0))
# self.assertEqual(result, result0)
def test_fetch_history_with_all_params(self, endpoint=Endpoint.TRADE, is_auth=True,
timestamp_param=ParamName.TIMESTAMP):
client = self.client_authed if is_auth else self.client
# (Get items to be used to set from_item, to_item params)
# Test SYMBOL and LIMIT
self.assertEqual(client.converter.sorting, Sorting.DESCENDING)
limit = 10
result = client.fetch_history(endpoint, self.testing_symbol, limit)
self.assertGoodResult(result)
self.assertEqual(len(result), limit)
if client.converter.IS_SORTING_ENABLED:
self.assertGreater(result[0].timestamp, result[-1].timestamp)
# print("TEMP result", result)
# Test FROM_ITEM and TO_ITEM
from_item = result[1]
to_item = result[-2]
print("Get history from_item:", from_item, "to_item:", to_item)
result = client.fetch_history(endpoint, self.testing_symbol,
from_item=from_item, to_item=to_item)
# print("TEMP result:", result)
self.assertGoodResult(result)
if self.is_to_item_supported:
if self.is_to_item_by_id:
self.assertEqual(len(result), limit - 2)
self.assertEqual(result[-1].timestamp, to_item.timestamp)
# Test SORTING, get default_result_len
result = client.fetch_history(endpoint, self.testing_symbol,
sorting=Sorting.ASCENDING)
self.assertGoodResult(result)
self.assertGreater(len(result), limit)
if client.converter.IS_SORTING_ENABLED:
self.assertLess(result[0].timestamp, result[-1].timestamp)
default_result_len = len(result)
# Test IS_USE_MAX_LIMIT
result = client.fetch_history(endpoint, self.testing_symbol,
is_use_max_limit=True)
self.assertGoodResult(result)
self.assertGreaterEqual(len(result), default_result_len)
# Test SYMBOL param as a list
if self.testing_symbol:
# (Note: for Binance fetch_history(endpoint, ["some", "some"])
# sends request without 2 SYMBOL get params which cases error.)
# (Note: for BitMEX fetch_history(endpoint, [None, None])
# sends request without SYMBOL get param which is usual request - so skip here.)
result = client.fetch_history(endpoint, [self.testing_symbol, self.testing_symbol])
self.assertIsNotNone(result)
# (Bitfinex returns [] on such error)
if result:
self.assertErrorResult(result)
# fetch_trades_history
test_fetch_trades = TestRESTClient.test_fetch_trades
test_fetch_trades_errors = TestRESTClient.test_fetch_trades_errors
test_fetch_trades_limit = TestRESTClient.test_fetch_trades_limit
test_fetch_trades_limit_is_too_big = TestRESTClient.test_fetch_trades_limit_is_too_big
test_fetch_trades_sorting = TestRESTClient.test_fetch_trades_sorting
def test_fetch_trades_history(self):
self.test_fetch_trades("fetch_trades_history")
def test_fetch_trades_history_errors(self):
self.test_fetch_trades_errors("fetch_trades_history")
def test_fetch_trades_history_limit(self):
self.test_fetch_trades_limit("fetch_trades_history")
def test_fetch_trades_history_limit_is_too_big(self):
self.test_fetch_trades_limit_is_too_big("fetch_trades_history")
def test_fetch_trades_history_sorting(self):
self.test_fetch_trades_sorting("fetch_trades_history")
def test_fetch_trades_is_same_as_first_history(self):
result = self.client_authed.fetch_trades(self.testing_symbol)
result_history = self.client_authed.fetch_trades_history(self.testing_symbol)
self.assertNotIsInstance(result, Error)
self.assertGreater(len(result), 10)
# self.assertIn(result_history[0], result, "Try restart")
self.assertIn(result_history[10], result, "Try restart")
self.assertIn(result[-1], result_history)
self.assertEqual(result, result_history,
"Can fail sometimes due to item added between requests")
def test_fetch_trades_history_over_and_over(self, sorting=None):
if not self.is_pagination_supported:
self.skipTest("Pagination is not supported by current platform version.")
if self.is_sorting_supported and not sorting:
self.test_fetch_trades_history_over_and_over(Sorting.DESCENDING)
self.test_fetch_trades_history_over_and_over(Sorting.ASCENDING)
return
client = self.client_authed
client.converter.is_use_max_limit = True
print("Test trade paging with",
"sorting: " + sorting if sorting else "default_sorting: " + client.default_sorting)
if not sorting:
sorting = client.default_sorting
result = client.fetch_trades(self.testing_symbol, sorting=sorting)
self.assertGoodResult(result)
page_count = 1
print("Page:", page_count, self._result_info(result, sorting))
while result and not isinstance(result, Error):
prev_result = result
result = client.fetch_trades_history(self.testing_symbol, sorting=sorting, from_item=result[-1])
page_count += 1
self.assertGoodResult(result)
if isinstance(result, Error):
# Rate limit error!
print("Page:", page_count, "error:", result)
else:
# Check next page
print("Page:", page_count, self._result_info(result, sorting))
self.assertGreater(len(result), 2)
for item in result:
self.assertTradeIsValid(item)
self.assertRightSymbols(result)
if sorting == Sorting.ASCENDING:
# Oldest first
self.assertLess(prev_result[0].timestamp, prev_result[-1].timestamp,
"Error in sorting") # Check sorting is ok
self.assertLess(result[0].timestamp, result[-1].timestamp,
"Error in sorting") # Check sorting is ok
self.assertLessEqual(prev_result[-1].timestamp, result[0].timestamp,
"Error in paging") # Check next page
else:
# Newest first
self.assertGreater(prev_result[0].timestamp, prev_result[-1].timestamp,
"Error in sorting") # Check sorting is ok
self.assertGreater(result[0].timestamp, result[-1].timestamp,
"Error in sorting") # Check sorting is ok
self.assertGreaterEqual(prev_result[-1].timestamp, result[0].timestamp,
"Error in paging") # Check next page
if page_count > 2:
print("Break to prevent RATE_LIMIT error.")
break
print("Pages count:", page_count)
# For debugging only
def test_just_logging_for_paging(self, method_name="fetch_trades_history", is_auth=False, sorting=None):
if self.is_sorting_supported and not sorting:
self.test_just_logging_for_paging(method_name, is_auth, Sorting.DESCENDING)
self.test_just_logging_for_paging(method_name, is_auth, Sorting.ASCENDING)
return
client = self.client_authed if is_auth else self.client
print("Logging paging with",
"sorting: " + sorting if sorting else "default_sorting: " + client.converter.default_sorting)
if not sorting:
sorting = client.converter.default_sorting
print("\n==First page==")
result0 = result = getattr(client, method_name)(self.testing_symbol, sorting=sorting)
self.assertGoodResult(result)
print("_result_info:", self._result_info(result, sorting))
print("\n==Next page==")
# print("\nXXX", result0[-1].timestamp)
# result0[-1].timestamp -= 100
# print("\nXXX", result0[-1].timestamp)
result = getattr(client, method_name)(self.testing_symbol, sorting=sorting, from_item=result0[-1])
# print("\nXXX", result0[0].timestamp, result0[-1].timestamp)
# print("\nYYY", result[0].timestamp, result[-1].timestamp)
if result:
# To check rate limit error
self.assertGoodResult(result)
print("_result_info:", self._result_info(result, sorting))
print("\n==Failed page==")
result = getattr(client, method_name)(self.testing_symbol, sorting=sorting, from_item=result0[0])
self.assertGoodResult(result)
print("_result_info:", self._result_info(result, sorting))
# WebSocket
class TestWSClient(TestClient):
is_rest = False
testing_symbols = ["ETHBTC", "BTXUSD"]
received_items = None
def setUp(self):
self.skipIfBase()
super().setUp()
self.received_items = []
def on_item_received(item):
if isinstance(item, DataObject):
self.received_items.append(item)
self.client.on_item_received = on_item_received
self.client_authed.on_item_received = on_item_received
def test_trade_1_channel(self):
self._test_endpoint_channels([Endpoint.TRADE], [self.testing_symbol], self.assertTradeIsValid)
def test_trade_2_channel(self):
self._test_endpoint_channels([Endpoint.TRADE], self.testing_symbols, self.assertTradeIsValid)
def test_candle_1_channel(self):
params = {ParamName.INTERVAL: Interval.MIN_1}
self._test_endpoint_channels([Endpoint.CANDLE], [self.testing_symbol], self.assertCandleIsValid, params)
def test_candle_2_channel(self):
params = {ParamName.INTERVAL: Interval.MIN_1}
self._test_endpoint_channels([Endpoint.CANDLE], self.testing_symbols, self.assertCandleIsValid, params)
def test_ticker1_channel(self):
self._test_endpoint_channels([Endpoint.TICKER], [self.testing_symbol], self.assertTickerIsValid)
def test_ticker2_channel(self):
self._test_endpoint_channels([Endpoint.TICKER], self.testing_symbols, self.assertTickerIsValid)
def test_ticker_all_channel(self):
self._test_endpoint_channels([Endpoint.TICKER_ALL], None, self.assertTickerIsValid)
def test_order_book_1_channel(self):
params = {ParamName.LEVEL: 5}
self._test_endpoint_channels([Endpoint.ORDER_BOOK], [self.testing_symbol], self.assertOrderBookIsValid, params)
def test_order_book_2_channel(self):
params = {ParamName.LEVEL: 5}
self._test_endpoint_channels([Endpoint.ORDER_BOOK], self.testing_symbols, self.assertOrderBookIsValid, params)
def test_order_book_diff_1_channel(self):
self._test_endpoint_channels([Endpoint.ORDER_BOOK_DIFF], [self.testing_symbol], self.assertOrderBookDiffIsValid)
def test_order_book_diff_2_channel(self):
self._test_endpoint_channels([Endpoint.ORDER_BOOK_DIFF], self.testing_symbols, self.assertOrderBookDiffIsValid)
def _test_endpoint_channels(self, endpoints, symbols, assertIsValidFun, params=None, is_auth=False):
client = self.client_authed if is_auth else self.client
if not isinstance(endpoints, (list, tuple)):
endpoints = [endpoints]
if symbols and not isinstance(symbols, (list, tuple)):
symbols = [symbols]
client.subscribe(endpoints, symbols, **params or {})
# todo wait for all endpoints and all symbols?
wait_for(self.received_items, timeout_sec=10000000)
self.assertGreaterEqual(len(self.received_items), 1)
for item in self.received_items:
assertIsValidFun(item, symbols)
|
{"/hyperquant/clients/tests/test_init.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py", "/hyperquant/clients/utils.py"], "/hyperquant/clients/tests/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/tests/test_api.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/__init__.py": ["/hyperquant/api.py"], "/hyperquant/clients/tests/test_bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/tests/test_utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/utils.py"], "/run_demo.py": ["/settings.py", "/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py"], "/hyperquant/clients/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py"], "/hyperquant/clients/binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"]}
|
13,207
|
assassinen/hyperquant
|
refs/heads/master
|
/hyperquant/clients/tests/utils.py
|
import logging
import sys
import time
from unittest import TestCase
from hyperquant.api import OrderStatus, Direction, OrderType, OrderBookDirection, Interval
from hyperquant.clients import Trade, ItemObject, Candle, MyTrade, Ticker, Order, OrderBookItem, OrderBook, Account, \
Balance
# Utility
def set_up_logging(is_debug=True):
logging_format = "%(asctime)s %(levelname)s:%(name)s: %(message)s"
logging.basicConfig(level=logging.DEBUG if is_debug else logging.INFO,
stream=sys.stdout, format=logging_format)
def wait_for(value_or_callable, count=2, timeout_sec=10):
# Wait for value is of "count" length or "timeout_sec" elapsed.
start_time = time.time()
value, fun = (None, value_or_callable) if callable(value_or_callable) \
else (value_or_callable, None)
print("\n### Waiting a list for count: %s or timeout_sec: %s" % (count, timeout_sec))
while not timeout_sec or time.time() - start_time < timeout_sec:
if fun:
value = fun()
if isinstance(value, bool):
if value:
print("\n### Result is true: %s in %s seconds" % (value, time.time() - start_time))
return
else:
value_count = value if isinstance(value, int) else len(value)
if value_count >= count:
print("\n### Count reached: %s of %s in %s seconds" % (value_count, count, time.time() - start_time))
return
print("\n### Sleep... current count: %s of %s, %s seconds passed" % (value_count, count, time.time() - start_time))
time.sleep(min(1, timeout_sec / 10) if timeout_sec else 1)
print("\n### Time is out! (value)")
raise Exception("Time is out!")
def wait_for_history(history_connector, timeout_sec=10):
# Wait for item_list is of "count" length or "timeout_sec" elapsed.
start_time = time.time()
print("\n### Waiting a history_connector or timeout_sec: %s" % (timeout_sec))
while not timeout_sec or time.time() - start_time < timeout_sec:
if not history_connector.is_in_progress:
if history_connector.is_complete:
print("\n### All (or no) history retrieved in: %s seconds" % (time.time() - start_time))
else:
print("\n### All history closed complete. Worked: %s seconds" % (time.time() - start_time))
return True
time.sleep(min(3, timeout_sec / 10) if timeout_sec else 1)
print("\n### Time is out! (history_connector)")
raise Exception("Time is out!")
# return False
class AssertUtil(TestCase):
# Don't extend with this class, but use functions in your test classes
def assertItemIsValid(self, item, testing_symbol_or_symbols=None, platform_id=None,
is_with_item_id=True, is_with_timestamp=True):
self.assertIsNotNone(item)
self.assertIsInstance(item, ItemObject)
# Not empty
self.assertIsNotNone(item.platform_id)
self.assertIsNotNone(item.symbol)
if is_with_timestamp:
self.assertIsNotNone(item.timestamp)
if is_with_item_id:
self.assertIsNotNone(item.item_id) # trade_id: binance, bitfinex - int converted to str; bitmex - str
# Type
self.assertIsInstance(item.platform_id, int)
self.assertIsInstance(item.symbol, str)
if is_with_timestamp:
self.assertTrue(isinstance(item.timestamp, (float, int)))
if is_with_item_id:
self.assertIsInstance(item.item_id, str)
# Value
self.assertEqual(item.platform_id, platform_id)
if is_with_timestamp:
self.assertGreater(item.timestamp, 1000000000)
if item.is_milliseconds:
self.assertGreater(item.timestamp, 10000000000)
if testing_symbol_or_symbols:
self.assertEqual(item.symbol, item.symbol.upper())
if isinstance(testing_symbol_or_symbols, str):
self.assertEqual(item.symbol, testing_symbol_or_symbols)
else:
self.assertIn(item.symbol, testing_symbol_or_symbols)
if is_with_item_id:
self.assertGreater(len(str(item.item_id)), 0)
def assertTradeIsValid(self, trade, testing_symbol_or_symbols=None, platform_id=None, is_dict=False):
if is_dict and trade:
trade = Trade(**trade)
AssertUtil.assertItemIsValid(self, trade, testing_symbol_or_symbols, platform_id, True)
self.assertIsInstance(trade, Trade)
# Not empty
self.assertIsNotNone(trade.price)
self.assertIsNotNone(trade.amount)
# self.assertIsNotNone(trade.direction)
# Type
self.assertIsInstance(trade.price, str)
self.assertIsInstance(trade.amount, str)
if trade.direction is not None:
self.assertIsInstance(trade.direction, int)
# Value
self.assertGreater(float(trade.price), 0)
self.assertGreater(float(trade.amount), 0)
if trade.direction is not None:
self.assertIn(float(trade.direction), Direction.name_by_value)
def assertMyTradeIsValid(self, my_trade, testing_symbol_or_symbols=None, platform_id=None, is_dict=False):
if is_dict and my_trade:
my_trade = MyTrade(**my_trade)
AssertUtil.assertTradeIsValid(self, my_trade, testing_symbol_or_symbols, platform_id, True)
self.assertIsInstance(my_trade, MyTrade)
# Not empty
self.assertIsNotNone(my_trade.order_id)
# self.assertIsNotNone(my_trade.fee)
# self.assertIsNotNone(my_trade.rebate)
# Type
self.assertIsInstance(my_trade.order_id, str)
if my_trade.fee is not None:
self.assertIsInstance(my_trade.fee, str)
if my_trade.rebate is not None:
self.assertIsInstance(my_trade.rebate, str)
# Value
if my_trade.fee is not None:
self.assertGreater(float(my_trade.fee), 0)
if my_trade.rebate is not None:
self.assertGreater(float(my_trade.rebate), 0)
def assertCandleIsValid(self, candle, testing_symbol_or_symbols=None, platform_id=None, is_dict=False):
if is_dict and candle:
candle = Candle(**candle)
AssertUtil.assertItemIsValid(self, candle, testing_symbol_or_symbols, platform_id, False)
self.assertIsInstance(candle, Candle)
# Not empty
self.assertIsNotNone(candle.interval)
self.assertIsNotNone(candle.price_open)
self.assertIsNotNone(candle.price_close)
self.assertIsNotNone(candle.price_high)
self.assertIsNotNone(candle.price_low)
# Optional
# self.assertIsNotNone(candle.amount)
# self.assertIsNotNone(candle.trades_count)
# Type
self.assertIsInstance(candle.interval, str)
self.assertIsInstance(candle.price_open, str)
self.assertIsInstance(candle.price_close, str)
self.assertIsInstance(candle.price_high, str)
self.assertIsInstance(candle.price_low, str)
if candle.amount is not None:
self.assertIsInstance(candle.amount, str)
if candle.trades_count is not None:
self.assertIsInstance(candle.trades_count, int)
# Value
self.assertIn(candle.interval, Interval.ALL)
self.assertGreater(float(candle.price_open), 0)
self.assertGreater(float(candle.price_close), 0)
self.assertGreater(float(candle.price_high), 0)
self.assertGreater(float(candle.price_low), 0)
if candle.amount is not None:
self.assertGreater(float(candle.amount), 0)
if candle.trades_count is not None:
self.assertGreater(candle.trades_count, 0)
def assertTickerIsValid(self, ticker, testing_symbol_or_symbols=None, platform_id=None, is_dict=False):
if is_dict and ticker:
ticker = Ticker(**ticker)
AssertUtil.assertItemIsValid(self, ticker, testing_symbol_or_symbols, platform_id, False, False)
self.assertIsInstance(ticker, Ticker)
# Not empty
self.assertIsNotNone(ticker.price)
# Type
self.assertIsInstance(ticker.price, str)
# Value
self.assertGreater(float(ticker.price), 0)
def assertOrderBookIsValid(self, order_book, testing_symbol_or_symbols=None, platform_id=None, is_dict=False,
is_diff=False):
if is_dict and order_book:
order_book = OrderBook(**order_book)
# Assert order book
AssertUtil.assertItemIsValid(self, order_book, testing_symbol_or_symbols, platform_id, False, False)
self.assertIsInstance(order_book, OrderBook)
self.assertIsNotNone(order_book.asks)
self.assertIsNotNone(order_book.bids)
# if is_diff:
self.assertGreaterEqual(len(order_book.asks), 0)
self.assertGreaterEqual(len(order_book.bids), 0)
# For order book diff
self.assertGreater(len(order_book.asks + order_book.bids), 0)
# else:
# self.assertGreater(len(order_book.asks), 0)
# self.assertGreater(len(order_book.bids), 0)
# Assert order book items
for item in order_book.asks:
AssertUtil.assertOrderBookItemIsValid(self, item)
for item in order_book.bids:
AssertUtil.assertOrderBookItemIsValid(self, item)
def assertOrderBookDiffIsValid(self, order_book, testing_symbol_or_symbols=None, platform_id=None, is_dict=False):
AssertUtil.assertOrderBookIsValid(self, order_book, testing_symbol_or_symbols, platform_id, is_dict, is_diff=True)
def assertOrderBookItemIsValid(self, order_book_item, testing_symbol_or_symbols=None, platform_id=None, is_dict=False):
if is_dict and order_book_item:
order_book_item = OrderBookItem(**order_book_item)
# AssertUtil.assertItemIsValid(self, order_book_item, testing_symbol_or_symbols, platform_id, False)
self.assertIsInstance(order_book_item, OrderBookItem)
# Not empty
self.assertIsNotNone(order_book_item.price)
self.assertIsNotNone(order_book_item.amount)
# self.assertIsNotNone(order_book_item.direction)
# self.assertIsNotNone(order_book_item.order_count)
# Type
self.assertIsInstance(order_book_item.price, str)
self.assertIsInstance(order_book_item.amount, str)
if order_book_item.direction is not None:
self.assertIsInstance(order_book_item.direction, int)
if order_book_item.order_count is not None:
self.assertIsInstance(order_book_item.order_count, int)
# Value
self.assertGreater(float(order_book_item.price), 0)
self.assertGreaterEqual(float(order_book_item.amount), 0)
if order_book_item.direction is not None:
self.assertIn(order_book_item.direction, OrderBookDirection.name_by_value)
if order_book_item.order_count is not None:
self.assertGreater(order_book_item.order_count, 0)
def assertAccountIsValid(self, account, platform_id=None, is_dict=False):
if is_dict and account:
account = Account(**account)
self.assertIsInstance(account, Account)
# Not empty
self.assertIsNotNone(account.platform_id)
self.assertIsNotNone(account.timestamp)
self.assertIsNotNone(account.balances)
# Type
self.assertIsInstance(account.platform_id, int)
self.assertIsInstance(account.timestamp, (int, float))
self.assertIsInstance(account.balances, list)
# Value
self.assertEqual(account.platform_id, platform_id)
self.assertGreater(account.timestamp, 1000000000)
if account.is_milliseconds:
self.assertGreater(account.timestamp, 10000000000)
self.assertGreaterEqual(len(account.balances), 0)
for balance in account.balances:
AssertUtil.assertBalanceIsValid(self, balance, platform_id)
# for debug
balances_with_money = [balance for balance in account.balances if float(balance.amount_available) or float(balance.amount_reserved)]
pass
def assertBalanceIsValid(self, balance, platform_id=None, is_dict=False):
if is_dict and balance:
order = Balance(**balance)
self.assertIsInstance(balance, Balance)
# Not empty
self.assertIsNotNone(balance.platform_id)
self.assertIsNotNone(balance.symbol)
self.assertIsNotNone(balance.amount_available)
self.assertIsNotNone(balance.amount_reserved)
# Type
self.assertIsInstance(balance.platform_id, int)
self.assertIsInstance(balance.symbol, str)
self.assertIsInstance(balance.amount_available, str)
self.assertIsInstance(balance.amount_reserved, str)
# Value
self.assertEqual(balance.platform_id, platform_id)
self.assertEqual(balance.symbol, balance.symbol.upper())
self.assertGreaterEqual(float(balance.amount_available), 0)
self.assertGreaterEqual(float(balance.amount_reserved), 0)
def assertOrderIsValid(self, order, testing_symbol_or_symbols=None, platform_id=None, is_dict=False):
if is_dict and order:
order = Order(**order)
AssertUtil.assertItemIsValid(self, order, testing_symbol_or_symbols, platform_id, True)
self.assertIsInstance(order, Order)
# Not empty
self.assertIsNotNone(order.user_order_id)
self.assertIsNotNone(order.order_type)
self.assertIsNotNone(order.price)
self.assertIsNotNone(order.amount_original)
self.assertIsNotNone(order.amount_executed)
self.assertIsNotNone(order.direction)
self.assertIsNotNone(order.order_status)
# Type
self.assertIsInstance(order.user_order_id, str)
self.assertIsInstance(order.order_type, int)
self.assertIsInstance(order.price, str)
self.assertIsInstance(order.amount_original, str)
self.assertIsInstance(order.amount_executed, str)
self.assertIsInstance(order.direction, int)
self.assertIsInstance(order.order_status, int)
# Value
self.assertIn(float(order.order_type), OrderType.name_by_value)
self.assertGreater(float(order.price), 0)
self.assertGreater(float(order.amount_original), 0)
self.assertGreater(float(order.amount_executed), 0)
self.assertIn(order.direction, Direction.name_by_value)
self.assertIn(order.order_status, OrderStatus.name_by_value)
|
{"/hyperquant/clients/tests/test_init.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py", "/hyperquant/clients/utils.py"], "/hyperquant/clients/tests/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/tests/test_api.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/__init__.py": ["/hyperquant/api.py"], "/hyperquant/clients/tests/test_bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/tests/test_utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/utils.py"], "/run_demo.py": ["/settings.py", "/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py"], "/hyperquant/clients/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py"], "/hyperquant/clients/binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"]}
|
13,208
|
assassinen/hyperquant
|
refs/heads/master
|
/hyperquant/tests/test_api.py
|
from unittest import TestCase
from hyperquant.api import item_format_by_endpoint, Endpoint, Direction, convert_items_obj_to_list, \
convert_items_dict_to_list, convert_items_list_to_dict, convert_items_obj_to_dict, ParamName
from hyperquant.clients import Trade, ItemObject
class TestConverting(TestCase):
endpoint = None
item_format = None
obj_items = None
list_items = None
dict_items = None
obj_item_short = None
list_item_short = None
dict_item_short = None
def setUp(self):
super().setUp()
if not self.endpoint:
self.skipTest("Base test")
self.item_format = item_format_by_endpoint[self.endpoint]
def test_convert_items_obj_to_list(self):
# Items to items
self._test_convert_items(self.obj_items, self.list_items, convert_items_obj_to_list)
# Item to item
self._test_convert_items(self.obj_items[0], self.list_items[0], convert_items_obj_to_list)
# Check for items which are shorter than item_format (i.e. item is ItemObject, and item_format is for Trade)
self._test_convert_items(self.obj_item_short, self.list_item_short, convert_items_obj_to_list)
# Empty to empty, None to None
self._test_convert_items([], [], convert_items_obj_to_list)
self._test_convert_items([None, None], [None, None], convert_items_obj_to_list)
self._test_convert_items(None, None, convert_items_obj_to_list)
def test_convert_items_dict_to_list(self):
self._test_convert_items(self.dict_items, self.list_items, convert_items_dict_to_list)
self._test_convert_items(self.dict_items[0], self.list_items[0], convert_items_dict_to_list)
self._test_convert_items(self.dict_item_short, self.list_item_short, convert_items_dict_to_list)
self._test_convert_items([], [], convert_items_dict_to_list)
self._test_convert_items([None, None], [None, None], convert_items_dict_to_list)
self._test_convert_items(None, None, convert_items_dict_to_list)
def test_convert_items_list_to_dict(self):
self._test_convert_items(self.list_items, self.dict_items, convert_items_list_to_dict)
self._test_convert_items(self.list_items[0], self.dict_items[0], convert_items_list_to_dict)
self._test_convert_items(self.list_item_short, self.dict_item_short, convert_items_list_to_dict)
self._test_convert_items([], [], convert_items_list_to_dict)
self._test_convert_items([None, None], [None, None], convert_items_list_to_dict)
self._test_convert_items(None, None, convert_items_list_to_dict)
def test_convert_items_obj_to_dict(self):
self._test_convert_items(self.obj_items, self.dict_items, convert_items_obj_to_dict)
self._test_convert_items(self.obj_items[0], self.dict_items[0], convert_items_obj_to_dict)
self._test_convert_items(self.obj_item_short, self.dict_item_short, convert_items_obj_to_dict)
self._test_convert_items([], [], convert_items_obj_to_dict)
self._test_convert_items([None, None], [None, None], convert_items_obj_to_dict)
self._test_convert_items(None, None, convert_items_obj_to_dict)
def _test_convert_items(self, items, expected, fun):
result = fun(items, self.item_format)
self.assertEqual(expected, result)
class TestConvertingTrade(TestConverting):
endpoint = Endpoint.TRADE
obj_item1 = Trade()
obj_item1.platform_id = None # None needed to test convert_items_list_to_dict() with 1 item in params
obj_item1.symbol = "ETHUSD"
obj_item1.timestamp = 143423531
obj_item1.item_id = "14121214"
obj_item1.price = "23424546543.3"
obj_item1.amount = "1110.0034"
obj_item1.direction = Direction.SELL
obj_item2 = Trade()
obj_item2.platform_id = 2
obj_item2.symbol = "BNBUSD"
obj_item2.timestamp = 143423537
obj_item2.item_id = 15121215
obj_item2.price = 23.235656723
obj_item2.amount = "0.0034345452"
obj_item2.direction = Direction.BUY
obj_items = [obj_item1, obj_item2]
list_items = [[None, "ETHUSD", 143423531, "14121214", "23424546543.3", "1110.0034", Direction.SELL],
[2, "BNBUSD", 143423537, 15121215, 23.235656723, "0.0034345452", Direction.BUY]]
dict_items = [{ParamName.PLATFORM_ID: None, ParamName.SYMBOL: "ETHUSD",
ParamName.TIMESTAMP: 143423531, ParamName.ITEM_ID: "14121214",
ParamName.PRICE: "23424546543.3", ParamName.AMOUNT: "1110.0034", ParamName.DIRECTION: 1},
{ParamName.PLATFORM_ID: 2, ParamName.SYMBOL: "BNBUSD",
ParamName.TIMESTAMP: 143423537, ParamName.ITEM_ID: 15121215,
ParamName.PRICE: 23.235656723, ParamName.AMOUNT: "0.0034345452", ParamName.DIRECTION: 2}]
obj_item_short = ItemObject()
obj_item_short.platform_id = None # None needed to test convert_items_list_to_dict() with 1 item in params
obj_item_short.symbol = "ETHUSD"
obj_item_short.timestamp = 143423531
obj_item_short.item_id = "14121214"
list_item_short = [None, "ETHUSD", 143423531, "14121214"]
dict_item_short = {ParamName.PLATFORM_ID: None, ParamName.SYMBOL: "ETHUSD",
ParamName.TIMESTAMP: 143423531, ParamName.ITEM_ID: "14121214"}
|
{"/hyperquant/clients/tests/test_init.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py", "/hyperquant/clients/utils.py"], "/hyperquant/clients/tests/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/tests/test_api.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/__init__.py": ["/hyperquant/api.py"], "/hyperquant/clients/tests/test_bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/tests/test_utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/utils.py"], "/run_demo.py": ["/settings.py", "/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py"], "/hyperquant/clients/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py"], "/hyperquant/clients/binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"]}
|
13,209
|
assassinen/hyperquant
|
refs/heads/master
|
/hyperquant/clients/tests/test_binance.py
|
from hyperquant.api import Platform
from hyperquant.clients import Error, ErrorCode
from hyperquant.clients.binance import BinanceRESTClient, BinanceRESTConverterV1, BinanceWSClient, BinanceWSConverterV1
from hyperquant.clients.tests.test_init import TestRESTClient, TestWSClient, TestConverter, TestRESTClientHistory
# REST
class TestBinanceRESTConverterV1(TestConverter):
converter_class = BinanceRESTConverterV1
class TestBinanceRESTClientV1(TestRESTClient):
platform_id = Platform.BINANCE
# version = "1"
class TestBinanceRESTClientHistoryV1(TestRESTClientHistory):
platform_id = Platform.BINANCE
# version = "1"
is_to_item_by_id = True
def test_just_logging_for_paging(self, method_name="fetch_trades_history", is_auth=False, sorting=None):
super().test_just_logging_for_paging(method_name, True, sorting)
def test_fetch_trades_history_errors(self):
super().test_fetch_trades_history_errors()
# Testing create_rest_client() which must set api_key for Binance
result = self.client.fetch_trades_history(self.testing_symbol)
self.assertIsNotNone(result)
self.assertGoodResult(result)
# Note: for Binance to get trades history you must send api_key
self.client.set_credentials(None, None)
result = self.client.fetch_trades_history(self.testing_symbol)
self.assertIsNotNone(result)
self.assertIsInstance(result, Error)
self.assertEqual(result.code, ErrorCode.UNAUTHORIZED)
# WebSocket
class TestBinanceWSConverterV1(TestConverter):
converter_class = BinanceWSConverterV1
class TestBinanceWSClientV1(TestWSClient):
platform_id = Platform.BINANCE
# version = "1"
|
{"/hyperquant/clients/tests/test_init.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py", "/hyperquant/clients/utils.py"], "/hyperquant/clients/tests/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/tests/test_api.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/__init__.py": ["/hyperquant/api.py"], "/hyperquant/clients/tests/test_bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/tests/test_utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/utils.py"], "/run_demo.py": ["/settings.py", "/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py"], "/hyperquant/clients/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py"], "/hyperquant/clients/binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"]}
|
13,210
|
assassinen/hyperquant
|
refs/heads/master
|
/hyperquant/clients/bitmex.py
|
import hashlib
import hmac
import json
import time
import urllib
from hyperquant.api import Platform, Sorting, Direction
from hyperquant.clients import WSClient, Trade, Error, ErrorCode, Endpoint, \
ParamName, WSConverter, RESTConverter, PlatformRESTClient, PrivatePlatformRESTClient, ItemObject
# REST
class BitMEXRESTConverterV1(RESTConverter):
"""
Go https://www.bitmex.com/api/v1/schema for whole API schema with param types keys
which help to distinguish items from each other (for updates and removing).
"""
# Main params:
base_url = "https://www.bitmex.com/api/v{version}"
IS_SORTING_ENABLED = True
# Settings:
# Converting info:
# For converting to platform
endpoint_lookup = {
Endpoint.TRADE: "trade",
Endpoint.TRADE_HISTORY: "trade",
}
param_name_lookup = {
ParamName.LIMIT: "count",
ParamName.SORTING: "reverse",
ParamName.FROM_ITEM: "startTime",
ParamName.TO_ITEM: "endTime",
ParamName.FROM_TIME: "startTime",
ParamName.TO_TIME: "endTime",
}
param_value_lookup = {
Sorting.ASCENDING: "false",
Sorting.DESCENDING: "true",
Sorting.DEFAULT_SORTING: Sorting.ASCENDING,
}
max_limit_by_endpoint = {
Endpoint.TRADE: 500,
Endpoint.TRADE_HISTORY: 500,
}
# For parsing
param_lookup_by_class = {
Error: {
"name": "code",
"message": "message",
},
Trade: {
"trdMatchID": ParamName.ITEM_ID,
"timestamp": ParamName.TIMESTAMP,
"symbol": ParamName.SYMBOL,
"price": ParamName.PRICE,
"size": ParamName.AMOUNT,
"side": ParamName.DIRECTION,
},
}
error_code_by_platform_error_code = {
# "": ErrorCode.UNAUTHORIZED,
"Unknown symbol": ErrorCode.WRONG_SYMBOL,
# "ERR_RATE_LIMIT": ErrorCode.RATE_LIMIT,
}
error_code_by_http_status = {
400: ErrorCode.WRONG_PARAM,
401: ErrorCode.UNAUTHORIZED,
429: ErrorCode.RATE_LIMIT, #?
}
# For converting time
is_source_in_timestring = True
timestamp_platform_names = ["startTime", "endTime"]
def _process_param_value(self, name, value):
if name == ParamName.FROM_ITEM or name == ParamName.TO_ITEM:
if isinstance(value, ItemObject):
timestamp = value.timestamp
if name == ParamName.TO_ITEM:
# Make to_item an including param (for BitMEX it's excluding)
timestamp += (1000 if value.is_milliseconds else 1)
return timestamp
return super()._process_param_value(name, value)
def _parse_item(self, endpoint, item_data):
result = super()._parse_item(endpoint, item_data)
# (For Trade)
if hasattr(result, ParamName.SYMBOL) and result.symbol[0] == ".":
# # ".ETHUSD" -> "ETHUSD"
# result.symbol = result.symbol[1:]
# https://www.bitmex.com/api/explorer/#!/Trade/Trade_get Please note
# that indices (symbols starting with .) post trades at intervals to
# the trade feed. These have a size of 0 and are used only to indicate
# a changing price.
return None
# Convert direction
if result and isinstance(result, Trade):
result.direction = Direction.BUY if result.direction == "Buy" else (
Direction.SELL if result.direction == "Sell" else None)
result.price = str(result.price)
result.amount = str(result.amount)
return result
def parse_error(self, error_data=None, response=None):
if error_data and "error" in error_data:
error_data = error_data["error"]
if "Maximum result count is 500" in error_data["message"]:
error_data["name"] = ErrorCode.WRONG_LIMIT
result = super().parse_error(error_data, response)
return result
class BitMEXRESTClient(PrivatePlatformRESTClient):
platform_id = Platform.BITMEX
version = "1" # Default version
IS_NONE_SYMBOL_FOR_ALL_SYMBOLS = True
_converter_class_by_version = {
"1": BitMEXRESTConverterV1,
}
def _on_response(self, response, result):
# super()._on_response(response)
if not response.ok and "Retry-After" in response.headers:
self.delay_before_next_request_sec = int(response.headers["Retry-After"])
else:
# "x-ratelimit-limit": 300
# "x-ratelimit-remaining": 297
# "x-ratelimit-reset": 1489791662
try:
ratelimit = int(response.headers["x-ratelimit-limit"])
remaining_requests = float(response.headers["x-ratelimit-remaining"])
reset_ratelimit_timestamp = int(response.headers["x-ratelimit-reset"])
if remaining_requests < ratelimit * 0.1:
precision_sec = 1 # Current machine time may not precise which can cause ratelimit error
self.delay_before_next_request_sec = reset_ratelimit_timestamp - time.time() + precision_sec
else:
self.delay_before_next_request_sec = 0
self.logger.debug("Ratelimit info. remaining_requests: %s/%s delay: %s",
remaining_requests, ratelimit, self.delay_before_next_request_sec)
except Exception as error:
self.logger.exception("Error while defining delay_before_next_request_sec.", error)
def get_symbols(self, version=None):
# BitMEX has no get_symbols method in API,
# and None means "all symbols" if defined as symbol param.
return None
# If symbol not specified all symbols will be returned
# todo fetch_latest_trades()
def fetch_trades(self, symbol=None, limit=None, **kwargs):
# symbol = None
return super().fetch_trades(symbol, limit, **kwargs)
# If symbol not specified all symbols will be returned
def fetch_trades_history(self, symbol=None, limit=None, from_item=None,
sorting=None, from_time=None, to_time=None, **kwargs):
# Note: from_item used automatically for paging; from_time and to_time - used for custom purposes
return super().fetch_trades_history(symbol, limit, from_item, sorting=sorting,
from_time=from_time, to_time=to_time, **kwargs)
# tickers are in instruments
# WebSockets
class BitMEXWSConverterV1(WSConverter):
# Main params:
base_url = "wss://www.bitmex.com/realtime"
IS_SUBSCRIPTION_COMMAND_SUPPORTED = True
# # symbol_endpoints = ["execution", "instrument", "order", "orderBookL2", "position", "quote", "trade"]
# # supported_endpoints = symbolSubs + ["margin"]
# supported_endpoints = [Endpoint.TRADE]
# symbol_endpoints = [Endpoint.TRADE]
# Settings:
# Converting info:
# For converting to platform
endpoint_lookup = {
Endpoint.TRADE: "trade:{symbol}",
# Endpoint.TRADE: lambda params: "trade:" + params[Param.SYMBOL] if Param.SYMBOL in params else "trade",
}
# For parsing
param_lookup_by_class = {
Error: {
"status": "code",
"error": "message",
},
Trade: {
"trdMatchID": ParamName.ITEM_ID,
"timestamp": ParamName.TIMESTAMP,
"symbol": ParamName.SYMBOL,
"price": ParamName.PRICE,
"size": ParamName.AMOUNT,
"side": ParamName.DIRECTION,
},
}
event_type_param = "table"
# error_code_by_platform_error_code = {
# # # "": ErrorCode.UNAUTHORIZED,
# # "Unknown symbol": ErrorCode.WRONG_SYMBOL,
# # # "ERR_RATE_LIMIT": ErrorCode.RATE_LIMIT,
# }
# For converting time
is_source_in_timestring = True
# timestamp_platform_names = []
def parse(self, endpoint, data):
if data:
endpoint = data.get(self.event_type_param)
if "error" in data:
result = self.parse_error(data)
if "request" in data:
result.message += "request: " + json.dumps(data["request"])
return result
if "data" in data:
data = data["data"]
return super().parse(endpoint, data)
def _parse_item(self, endpoint, item_data):
result = super()._parse_item(endpoint, item_data)
# (For Trade)
if hasattr(result, ParamName.SYMBOL) and result.symbol[0] == ".":
# # ".ETHUSD" -> "ETHUSD"
# result.symbol = result.symbol[1:]
# https://www.bitmex.com/api/explorer/#!/Trade/Trade_get Please note
# that indices (symbols starting with .) post trades at intervals to
# the trade feed. These have a size of 0 and are used only to indicate
# a changing price.
return None
# Convert direction
if result and isinstance(result, Trade):
result.direction = Direction.BUY if result.direction == "Buy" else (
Direction.SELL if result.direction == "Sell" else None)
result.price = str(result.price)
result.amount = str(result.amount)
return result
class BitMEXWSClient(WSClient):
platform_id = Platform.BITMEX
version = "1" # Default version
_converter_class_by_version = {
"1": BitMEXWSConverterV1,
}
@property
def url(self):
self.is_subscribed_with_url = True
params = {"subscribe": ",".join(self.current_subscriptions)}
url, platform_params = self.converter.make_url_and_platform_params(params=params, is_join_get_params=True)
return url
@property
def headers(self):
result = super().headers or []
# Return auth headers
if self._api_key:
self.logger.info("Authenticating with API Key.")
# To auth to the WS using an API key, we generate
# a signature of a nonce and the WS API endpoint.
expire = generate_nonce()
result += [
"api-expires: " + str(expire),
]
if self._api_key and self._api_secret:
signature = generate_signature(self._api_secret, "GET", "/realtime", expire, "")
result += [
"api-signature: " + signature,
"api-key: " + self._api_key,
]
else:
self.logger.info("Not authenticating by headers because api_key is not set.")
return result
# def _on_message(self, message):
# """Handler for parsing WS messages."""
# self.logger.debug(message)
# message = json.loads(message)
# def on_item_received(self, item):
# super().on_item_received(item)
#
# # table = message["table"] if "table" in message else None
# # action = message["action"] if "action" in message else None
# # try:
# # if "subscribe" in message:
# # self.logger.debug("Subscribed to %s." % message["subscribe"])
# # elif action:
# #
# # if table not in self.data:
# # self.data[table] = []
# #
# # # There are four possible actions from the WS:
# # # "partial" - full table image
# # # "insert" - new row
# # # "update" - update row
# # # "delete" - delete row
# # if action == "partial":
# # self.logger.debug("%s: partial" % table)
# # self.data[table] += message["data"]
# # # Keys are communicated on partials to let you know how to uniquely identify
# # # an item. We use it for updates.
# # self.keys[table] = message["keys"]
# # elif action == "insert":
# # self.logger.debug("%s: inserting %s" % (table, message["data"]))
# # self.data[table] += message["data"]
# #
# # # Limit the max length of the table to avoid excessive memory usage.
# # # Don't trim orders because we'll lose valuable state if we do.
# # if table not in ["order", "orderBookL2"] and len(self.data[table]) > BitMEXWebsocket.MAX_TABLE_LEN:
# # self.data[table] = self.data[table][int(BitMEXWebsocket.MAX_TABLE_LEN / 2):]
# #
# # elif action == "update":
# # self.logger.debug("%s: updating %s" % (table, message["data"]))
# # # Locate the item in the collection and update it.
# # for updateData in message["data"]:
# # item = findItemByKeys(self.keys[table], self.data[table], updateData)
# # if not item:
# # return # No item found to update. Could happen before push
# # item.update(updateData)
# # # Remove cancelled / filled orders
# # if table == "order" and item["leavesQty"] <= 0:
# # self.data[table].remove(item)
# # elif action == "delete":
# # self.logger.debug("%s: deleting %s" % (table, message["data"]))
# # # Locate the item in the collection and remove it.
# # for deleteData in message["data"]:
# # item = findItemByKeys(self.keys[table], self.data[table], deleteData)
# # self.data[table].remove(item)
# # else:
# # raise Exception("Unknown action: %s" % action)
# # except:
# # self.logger.error(traceback.format_exc())
# def get_instrument(self):
# """Get the raw instrument data for this symbol."""
# # Turn the "tickSize" into "tickLog" for use in rounding
# instrument = self.data["instrument"][0]
# instrument["tickLog"] = int(math.fabs(math.log10(instrument["tickSize"])))
# return instrument
#
# def get_ticker(self):
# """Return a ticker object. Generated from quote and trade."""
# lastQuote = self.data["quote"][-1]
# lastTrade = self.data["trade"][-1]
# ticker = {
# "last": lastTrade["price"],
# "buy": lastQuote["bidPrice"],
# "sell": lastQuote["askPrice"],
# "mid": (float(lastQuote["bidPrice"] or 0) + float(lastQuote["askPrice"] or 0)) / 2
# }
#
# # The instrument has a tickSize. Use it to round values.
# instrument = self.data["instrument"][0]
# return {k: round(float(v or 0), instrument["tickLog"]) for k, v in ticker.items()}
#
# def funds(self):
# """Get your margin details."""
# return self.data["margin"][0]
#
# def market_depth(self):
# """Get market depth (orderbook). Returns all levels."""
# return self.data["orderBookL2"]
#
# def open_orders(self, clOrdIDPrefix):
# """Get all your open orders."""
# orders = self.data["order"]
# # Filter to only open orders (leavesQty > 0) and those that we actually placed
# return [o for o in orders if str(o["clOrdID"]).startswith(clOrdIDPrefix) and o["leavesQty"] > 0]
#
# def recent_trades(self):
# """Get recent trades."""
# return self.data["trade"]
def _send_subscribe(self, subscriptions):
self._send_command("subscribe", subscriptions)
def _send_unsubscribe(self, subscriptions):
self._send_command("unsubscribe", subscriptions)
def _send_command(self, command, params=None):
if params is None:
params = []
self._send({"op": command, "args": list(params)})
# Utility
def generate_nonce():
return int(round(time.time() + 3600))
def generate_signature(secret, method, url, nonce, data):
"""
Generates an API signature compatible with BitMEX..
A signature is HMAC_SHA256(secret, method + path + nonce + data), hex encoded.
Verb must be uppercased, url is relative, nonce must be an increasing 64-bit integer
and the data, if present, must be JSON without whitespace between keys.
For example, in pseudocode (and in real code below):
method=POST
url=/api/v1/order
nonce=1416993995705
data={"symbol":"XBTZ14","quantity":1,"price":395.01}
signature = HEX(HMAC_SHA256(secret, 'POST/api/v1/order1416993995705{"symbol":"XBTZ14","amount":1,"price":395.01}'))
"""
# Parse the url so we can remove the base and extract just the path.
parsed_url = urllib.parse.urlparse(url)
path = parsed_url.path
if parsed_url.query:
path = path + '?' + parsed_url.query
# print "Computing HMAC: %s" % verb + path + str(nonce) + data
message = (method + path + str(nonce) + data).encode('utf-8')
signature = hmac.new(secret.encode('utf-8'), message, digestmod=hashlib.sha256).hexdigest()
return signature
|
{"/hyperquant/clients/tests/test_init.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py", "/hyperquant/clients/utils.py"], "/hyperquant/clients/tests/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/tests/test_api.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/__init__.py": ["/hyperquant/api.py"], "/hyperquant/clients/tests/test_bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/tests/test_utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/utils.py"], "/run_demo.py": ["/settings.py", "/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py"], "/hyperquant/clients/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py"], "/hyperquant/clients/binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"]}
|
13,211
|
assassinen/hyperquant
|
refs/heads/master
|
/hyperquant/clients/tests/test_bitfinex.py
|
from hyperquant.api import Platform
from hyperquant.clients.bitfinex import BitfinexRESTClient, BitfinexWSClient, \
BitfinexRESTConverterV2, BitfinexRESTConverterV1, BitfinexWSConverterV1, BitfinexWSConverterV2
from hyperquant.clients.tests.test_init import TestRESTClient, TestWSClient, TestConverter, TestRESTClientHistory
# REST
class TestBitfinexRESTConverterV1(TestConverter):
converter_class = BitfinexRESTConverterV1
class TestBitfinexRESTConverterV2(TestConverter):
converter_class = BitfinexRESTConverterV2
class TestBitfinexRESTClientV1(TestRESTClient):
platform_id = Platform.BITFINEX
version = "1"
has_limit_error = False
is_symbol_case_sensitive = False
class TestBitfinexRESTClientHistoryV1(TestRESTClientHistory):
platform_id = Platform.BITFINEX
version = "1"
has_limit_error = False
is_symbol_case_sensitive = False
is_pagination_supported = False
is_to_item_supported = False
class TestBitfinexRESTClientV2(TestRESTClient):
client_class = BitfinexRESTClient
version = "2"
testing_symbol = "ETHUSD"
is_sorting_supported = True
has_limit_error = True
is_symbol_case_sensitive = True
def test_fetch_trades_errors(self, method_name="fetch_trades", is_auth=False):
client = self.client_authed if is_auth else self.client
# Wrong symbol
result = getattr(client, method_name)(self.wrong_symbol)
# Empty list instead of error
# (todo check, may be we should create error for each empty list returned +++ yes, we should!)
self.assertEqual(result, [])
class TestBitfinexRESTClientHistoryV2(TestRESTClientHistory):
client_class = BitfinexRESTClient
version = "2"
testing_symbol = "ETHUSD"
is_sorting_supported = True
has_limit_error = True
is_symbol_case_sensitive = True
def test_fetch_trades_errors(self, method_name="fetch_trades", is_auth=False):
client = self.client_authed if is_auth else self.client
# Wrong symbol
result = getattr(client, method_name)(self.wrong_symbol)
# Empty list instead of error
# (todo check, may be we should create error for each empty list returned +++ yes, we should!)
self.assertEqual(result, [])
# WebSocket
class TestBitfinexWSConverterV1(TestConverter):
converter_class = BitfinexWSConverterV1
class TestBitfinexWSConverterV2(TestConverter):
converter_class = BitfinexWSConverterV2
class TestBitfinexWSClientV1(TestWSClient):
platform_id = Platform.BITFINEX
version = "1"
class TestBitfinexWSClientV2(TestBitfinexWSClientV1):
version = "2"
|
{"/hyperquant/clients/tests/test_init.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py", "/hyperquant/clients/utils.py"], "/hyperquant/clients/tests/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/tests/test_api.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/__init__.py": ["/hyperquant/api.py"], "/hyperquant/clients/tests/test_bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/tests/test_utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/utils.py"], "/run_demo.py": ["/settings.py", "/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py"], "/hyperquant/clients/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py"], "/hyperquant/clients/binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"]}
|
13,212
|
assassinen/hyperquant
|
refs/heads/master
|
/hyperquant/clients/__init__.py
|
import json
import logging
import time
from datetime import datetime
from operator import itemgetter
from threading import Thread
from urllib.parse import urljoin, urlencode
import requests
from dateutil import parser
from websocket import WebSocketApp
from hyperquant.api import ParamName, ParamValue, ErrorCode, Endpoint, Platform, Sorting, OrderType
"""
API clients for various trading platforms: REST and WebSocket.
Some documentation:
https://docs.google.com/document/d/1U3kuokpeNSzxSbXhXJ3XnNYbfZaK5nY3_tAL-Uk0wKQ
"""
# Value objects
class ValueObject:
pass
# WS
class Info(ValueObject):
code = None
message = None
# WS
class Channel(ValueObject):
channel_id = None
channel = None
symbol = None
class Error(ValueObject):
code = None
message = None
def __str__(self) -> str:
return "[Trading-Error code: %s msg: %s]" % (self.code, self.message)
class DataObject(ValueObject):
pass
is_milliseconds = False
class ItemObject(DataObject):
# (Note: Order is from abstract to concrete)
platform_id = None
symbol = None
timestamp = None # Unix timestamp in milliseconds
item_id = None # There is no item_id for candle, ticker, bookticker, only for trade, mytrade and order
def __init__(self, platform_id=None, symbol=None, timestamp=None, item_id=None, is_milliseconds=False) -> None:
super().__init__()
self.platform_id = platform_id
self.symbol = symbol
self.timestamp = timestamp
self.item_id = item_id
self.is_milliseconds = is_milliseconds
def __eq__(self, o: object) -> bool:
# Identifying params:
return o and \
self.platform_id == o.platform_id and \
self.item_id == o.item_id and \
self.timestamp == o.timestamp and \
self.symbol == o.symbol
def __hash__(self) -> int:
return hash((self.platform_id, self.item_id, self.timestamp))
def __repr__(self) -> str:
platform_name = Platform.get_platform_name_by_id(self.platform_id)
timestamp_s = self.timestamp / 1000 if self.is_milliseconds else self.timestamp
timestamp_iso = datetime.utcfromtimestamp(timestamp_s).isoformat() if timestamp_s else timestamp_s
return "[Item-%s id:%s time:%s symbol:%s]" % (platform_name, self.item_id, timestamp_iso, self.symbol)
class Trade(ItemObject):
# Trade data:
price = None
amount = None
# Not for all platforms or versions:
direction = None
def __init__(self, platform_id=None, symbol=None, timestamp=None, item_id=None,
price=None, amount=None, direction=None, is_milliseconds=False) -> None:
super().__init__(platform_id, symbol, timestamp, item_id, is_milliseconds)
self.price = price
self.amount = amount
self.direction = direction
class MyTrade(Trade):
order_id = None
# Optional (not for all platforms):
fee = None # Комиссия биржи # must be always positive; 0 if not supported
rebate = None # Возврат денег, скидка после покупки # must be always positive; 0 if not supported
# fee_symbol = None # Currency symbol, by default, it's the same as for price
# Note: volume = price * amount, total = volume - fee + rebate
def __init__(self, platform_id=None, symbol=None, timestamp=None, item_id=None, price=None, amount=None,
direction=None, order_id=None, fee=None, rebate=None, is_milliseconds=False) -> None:
super().__init__(platform_id, symbol, timestamp, item_id, price, amount, direction, is_milliseconds)
self.order_id = order_id
self.fee = fee
self.rebate = rebate
class Candle(ItemObject):
# platform_id = None
# symbol = None
# timestamp = None # open_timestamp
interval = None
price_open = None
price_close = None
price_high = None
price_low = None
amount = None
# Optional
trades_count = None
def __init__(self, platform_id=None, symbol=None, timestamp=None, interval=None,
price_open=None, price_close=None, price_high=None, price_low=None,
amount=None, trades_count=None, is_milliseconds=False) -> None:
super().__init__(platform_id, symbol, timestamp, None, is_milliseconds)
self.interval = interval
self.price_open = price_open
self.price_close = price_close
self.price_high = price_high
self.price_low = price_low
self.amount = amount
self.trades_count = trades_count
class Ticker(ItemObject):
# platform_id = None
# symbol = None
# timestamp = None
price = None
def __init__(self, platform_id=None, symbol=None, timestamp=None, price=None, is_milliseconds=False) -> None:
super().__init__(platform_id, symbol, timestamp, None, is_milliseconds)
self.price = price
# class BookTicker(DataObject):
# symbol = None
# price_bid = None
# bid_amount = None
# price_ask = None
# ask_amount = None
class OrderBook(ItemObject):
asks = None
bids = None
def __init__(self, platform_id=None, symbol=None, timestamp=None, item_id=None, is_milliseconds=False,
asks=None, bids=None) -> None:
super().__init__(platform_id, symbol, timestamp, item_id, is_milliseconds)
self.asks = asks
self.bids = bids
class OrderBookItem(ItemObject):
# platform_id = None
# order_book_item_id = None # item_id = None
# symbol = None
price = None
amount = None
direction = None
# Optional
order_count = None
def __init__(self, platform_id=None, symbol=None, timestamp=None, item_id=None, is_milliseconds=False,
price=None, amount=None, direction=None, order_count=None) -> None:
super().__init__(platform_id, symbol, timestamp, item_id, is_milliseconds)
self.price = price
self.amount = amount
self.direction = direction
self.order_count = order_count
class Account(DataObject):
platform_id = None
timestamp = None
balances = None
# Binance other params:
# "makerCommission": 15,
# "takerCommission": 15,
# "buyerCommission": 0,
# "sellerCommission": 0,
# "canTrade": true,
# "canWithdraw": true,
# "canDeposit": true,
def __init__(self, platform_id=None, timestamp=None, balances=None) -> None:
super().__init__()
self.platform_id = platform_id
self.timestamp = timestamp
self.balances = balances
class Balance(ValueObject):
# Asset, currency
platform_id = None
symbol = None
amount_available = None
amount_reserved = None
def __init__(self, platform_id=None, symbol=None, amount_available=None, amount_reserved=None) -> None:
super().__init__()
self.platform_id = platform_id
self.symbol = symbol
self.amount_available = amount_available
self.amount_reserved = amount_reserved
class Order(ItemObject):
# platform_id = None
# item_id = None
# symbol = None
# timestamp = None # (transact timestamp)
user_order_id = None
order_type = None # limit and market
price = None
amount_original = None
amount_executed = None
direction = None
order_status = None # open and close
def __init__(self, platform_id=None, symbol=None, timestamp=None, item_id=None, is_milliseconds=False,
user_order_id=None, order_type=None, price=None,
amount_original=None, amount_executed=None, direction=None, order_status=None) -> None:
super().__init__(platform_id, symbol, timestamp, item_id, is_milliseconds)
self.user_order_id = user_order_id
self.order_type = order_type
self.price = price
self.amount_original = amount_original
self.amount_executed = amount_executed
self.direction = direction
self.order_status = order_status
# Base
class ProtocolConverter:
"""
Contains all the info and logic to convert data between
our library API and remote platform API.
"""
# Main params:
# (Set by client or set it by yourself in subclass)
platform_id = None
version = None
# (Define in subclass)
base_url = None
# Settings:
is_use_max_limit = False
# Converting info:
# Our endpoint to platform_endpoint
endpoint_lookup = None # {"endpoint": "platform_endpoint", ...}
# Our param_name to platform_param_name
param_name_lookup = None # {ParamName.FROM_TIME: "start", "not_supported": None, ...}
# Our param_value to platform_param_value
param_value_lookup = None # {Sorting.ASCENDING: 0}
max_limit_by_endpoint = None
# For parsing
item_class_by_endpoint = {
Endpoint.TRADE: Trade,
Endpoint.TRADE_HISTORY: Trade,
Endpoint.TRADE_MY: MyTrade,
Endpoint.CANDLE: Candle,
Endpoint.TICKER: Ticker,
Endpoint.ORDER_BOOK: OrderBook,
Endpoint.ORDER_BOOK_DIFF: OrderBook,
# Private
Endpoint.ACCOUNT: Account,
Endpoint.ORDER: Order,
Endpoint.ORDER_CURRENT: Order,
Endpoint.ORDER_MY: Order,
}
# {Trade: {ParamName.ITEM_ID: "tid", ...}} - omitted properties won't be set
param_lookup_by_class = None
error_code_by_platform_error_code = None
error_code_by_http_status = None
# For converting time
use_milliseconds = False # todo always use milliseconds
is_source_in_milliseconds = False
is_source_in_timestring = False
timestamp_platform_names = None # ["startTime", "endTime"]
# (If platform api is not consistent)
timestamp_platform_names_by_endpoint = None # {Endpoint.TRADE: ["start", "end"]}
ITEM_TIMESTAMP_ATTR = ParamName.TIMESTAMP
def __init__(self, platform_id=None, version=None):
if platform_id is not None:
self.platform_id = platform_id
if version is not None:
self.version = version
# Create logger
platform_name = Platform.get_platform_name_by_id(self.platform_id)
self.logger = logging.getLogger("%s.%s.v%s" % ("Converter", platform_name, self.version))
# Convert to platform format
def make_url_and_platform_params(self, endpoint=None, params=None, is_join_get_params=False, version=None):
# Apply version on base_url
version = version or self.version
url = self.base_url.format(version=version) if self.base_url and version else self.base_url
# Prepare path and params
url_resources, platform_params = self.prepare_params(endpoint, params)
# Make resulting URL
# url=ba://se_url/resou/rces?p=ar&am=s
if url_resources and url:
url = urljoin(url + "/", "/".join(url_resources))
if platform_params and is_join_get_params:
url = url + "?" + urlencode(platform_params)
return url, platform_params
def prepare_params(self, endpoint=None, params=None):
# Override in subclasses if it is the only way to adopt client to platform
# Convert our code's names to custom platform's names
platform_params = {self._get_platform_param_name(key): self._process_param_value(key, value)
for key, value in params.items() if value is not None} if params else {}
# (Del not supported by platform params which defined in lookups as empty)
platform_params.pop("", "")
platform_params.pop(None, None)
self._convert_timestamp_values_to_platform(endpoint, platform_params)
# Endpoint.TRADE -> "trades/ETHBTC" or "trades"
platform_endpoint = self._get_platform_endpoint(endpoint, params)
# Make path part of URL (as a list) using endpoint and params
resources = [platform_endpoint] if platform_endpoint else []
return resources, platform_params
def _process_param_value(self, name, value):
# Convert values to platform values
# if name in ParamValue.param_names:
value = self._get_platform_param_value(value, name)
return value
def _get_platform_endpoint(self, endpoint, params):
# Convert our code's endpoint to custom platform's endpoint
# Endpoint.TRADE -> "trades/{symbol}" or "trades" or lambda params: "trades"
platform_endpoint = self.endpoint_lookup.get(endpoint, endpoint) if self.endpoint_lookup else endpoint
if callable(platform_endpoint):
platform_endpoint = platform_endpoint(params)
if platform_endpoint:
# "trades", {"symbol": "ETHBTC"} => "trades" (no error)
# "trades/{symbol}/hist", {"symbol": "ETHBTC"} => "trades/ETHBTC/hist"
# "trades/{symbol}/hist", {} => Error!
platform_endpoint = platform_endpoint.format(**params)
return platform_endpoint
def _get_platform_param_name(self, name):
# Convert our code's param name to custom platform's param name
return self.param_name_lookup.get(name, name) if self.param_name_lookup else name
def _get_platform_param_value(self, value, name=None):
# Convert our code's param value to custom platform's param value
lookup = self.param_value_lookup
lookup = lookup.get(name, lookup) if lookup else None
return lookup.get(value, value) if lookup else value
# Convert from platform format
def parse(self, endpoint, data):
# if not endpoint or not data:
# self.logger.warning("Some argument is empty in parse(). endpoint: %s, data: %s", endpoint, data)
# return data
if not data:
self.logger.warning("Data argument is empty in parse(). endpoint: %s, data: %s", endpoint, data)
return data
# (If list of items data, but not an item data as a list)
if isinstance(data, list): # and not isinstance(data[0], list):
result = [self._parse_item(endpoint, item_data) for item_data in data]
# (Skip empty)
result = [item for item in result if item]
return result
else:
return self._parse_item(endpoint, data)
def _parse_item(self, endpoint, item_data):
# Check item_class by endpoint
if not endpoint or not self.item_class_by_endpoint or endpoint not in self.item_class_by_endpoint:
self.logger.warning("Wrong endpoint: %s in parse_item().", endpoint)
return item_data
item_class = self.item_class_by_endpoint[endpoint]
# Create and set up item by item_data (using lookup to convert property names)
item = self._create_and_set_up_object(item_class, item_data)
item = self._post_process_item(item)
return item
def _post_process_item(self, item):
# Process parsed values (convert from platform)
# Set platform_id
if hasattr(item, ParamName.PLATFORM_ID):
item.platform_id = self.platform_id
# Stringify item_id
if hasattr(item, ParamName.ITEM_ID) and item.item_id is not None:
item.item_id = str(item.item_id)
# Convert timestamp
# (If API returns milliseconds or string date we must convert them to Unix timestamp (in seconds or ms))
# (Note: add here more timestamp attributes if you use another name in your VOs)
if hasattr(item, self.ITEM_TIMESTAMP_ATTR) and item.timestamp:
item.timestamp = self._convert_timestamp_from_platform(item.timestamp)
item.is_milliseconds = self.use_milliseconds
# Convert asks and bids to OrderBookItem type
if hasattr(item, ParamName.ASKS) and item.asks:
item.asks = [self._create_and_set_up_object(OrderBookItem, item_data)
for item_data in item.asks]
if hasattr(item, ParamName.BIDS) and item.bids:
item.bids = [self._create_and_set_up_object(OrderBookItem, item_data)
for item_data in item.bids]
# Convert items to Balance type
if hasattr(item, ParamName.BALANCES) and item.balances:
item.balances = [self._create_and_set_up_object(Balance, item_data)
for item_data in item.balances]
# Set platform_id
for balance in item.balances:
self._post_process_item(balance)
return item
def parse_error(self, error_data=None, response=None):
# (error_data=None and response!=None when REST API returns 404 and html response)
if response and response.ok:
return None
result = self._create_and_set_up_object(Error, error_data) or Error()
response_message = " (status: %s %s code: %s msg: %s)" % (
response.status_code, response.reason, result.code, result.message) if response \
else " (code: %s msg: %s)" % (result.code, result.message)
if not result.code:
result.code = response.status_code
result.code = self.error_code_by_platform_error_code.get(result.code, result.code) \
if self.error_code_by_platform_error_code else result.code
result.message = ErrorCode.get_message_by_code(result.code) + response_message
return result
def _create_and_set_up_object(self, object_class, data):
if not object_class or not data:
return None
obj = object_class()
lookup = self.param_lookup_by_class.get(object_class) if self.param_lookup_by_class else None
if not lookup:
# self.logger.error("There is no lookup for %s in %s", object_class, self.__class__)
raise Exception("There is no lookup for %s in %s" % (object_class, self.__class__))
# (Lookup is usually a dict, but can be a list when item_data is a list)
key_pair = lookup.items() if isinstance(lookup, dict) else enumerate(lookup)
for platform_key, key in key_pair:
if key and (not isinstance(data, dict) or platform_key in data):
setattr(obj, key, data[platform_key])
return obj
# Convert from and to platform
def _convert_timestamp_values_to_platform(self, endpoint, platform_params):
if not platform_params:
return
timestamp_platform_names = self.timestamp_platform_names_by_endpoint.get(
endpoint, self.timestamp_platform_names) \
if self.timestamp_platform_names_by_endpoint else self.timestamp_platform_names
if not timestamp_platform_names:
return
for name in timestamp_platform_names:
if name in platform_params:
value = platform_params[name]
if isinstance(value, ValueObject):
value = getattr(value, self.ITEM_TIMESTAMP_ATTR, value)
platform_params[name] = self._convert_timestamp_to_platform(value)
def _convert_timestamp_to_platform(self, timestamp):
if not timestamp:
return timestamp
if self.use_milliseconds:
timestamp /= 1000
if self.is_source_in_milliseconds:
timestamp *= 1000
elif self.is_source_in_timestring:
dt = datetime.utcfromtimestamp(timestamp)
timestamp = dt.isoformat()
return timestamp
def _convert_timestamp_from_platform(self, timestamp):
if not timestamp:
return timestamp
if self.is_source_in_milliseconds:
timestamp /= 1000
# if int(timestamp) == timestamp:
# timestamp = int(timestamp)
elif self.is_source_in_timestring:
timestamp = parser.parse(timestamp).timestamp()
if self.use_milliseconds:
timestamp = int(timestamp * 1000)
return timestamp
class BaseClient:
"""
All time params are unix timestamps in seconds (float or int).
"""
# Main params
_log_prefix = "Client"
platform_id = None
version = None
_api_key = None
_api_secret = None
default_converter_class = ProtocolConverter
_converter_class_by_version = None
_converter_by_version = None
# If True then if "symbol" param set to None that will return data for "all symbols"
IS_NONE_SYMBOL_FOR_ALL_SYMBOLS = False
@property
def headers(self):
# Usually returns auth and other headers (Don't return None)
# (as a dict for requests (REST) and a list for WebSockets (WS))
return []
@property
def use_milliseconds(self):
return self.converter.use_milliseconds
@use_milliseconds.setter
def use_milliseconds(self, value):
self.converter.use_milliseconds = value
def __init__(self, version=None, **kwargs) -> None:
super().__init__()
if version is not None:
self.version = str(version)
# Set up settings
for key, value in kwargs.items():
setattr(self, key, value)
# Create logger
platform_name = Platform.get_platform_name_by_id(self.platform_id)
self.logger = logging.getLogger("%s.%s.v%s" % (self._log_prefix, platform_name, self.version))
# self.logger.debug("Create %s client for %s platform. url+params: %s",
# self._log_prefix, platform_name, self.make_url_and_platform_params())
# Create converter
self.converter = self.get_or_create_converter()
if not self.converter:
raise Exception("There is no converter_class in %s for version: %s" % (self.__class__, self.version))
def set_credentials(self, api_key, api_secret):
self._api_key = api_key
self._api_secret = api_secret
def get_or_create_converter(self, version=None):
# Converter stores all the info about a platform
# Note: Using version to get converter at any time allows us to easily
# switch version for just one request or for all further requests
# (used for bitfinex, for example, to get symbols which enabled only for v1)
if not version:
version = self.version
version = str(version)
if not self._converter_by_version:
self._converter_by_version = {}
if version in self._converter_by_version:
return self._converter_by_version[version]
# Get class
converter_class = self._converter_class_by_version.get(version) \
if self._converter_class_by_version else self.default_converter_class
# Note: platform_id could be set in converter or in client
if not self.platform_id:
self.platform_id = converter_class.platform_id
# Create and store
converter = converter_class(self.platform_id, version) if converter_class else None
self._converter_by_version[version] = converter
return converter
def close(self):
pass
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
# REST
class RESTConverter(ProtocolConverter):
# sorting values: ASCENDING, DESCENDING (newest first), None
# DEFAULT_SORTING = Param.ASCENDING # Const for current platform. See in param_name_lookup
IS_SORTING_ENABLED = False # False - SORTING param is not supported for current platform
sorting = Sorting.DESCENDING # Choose default sorting for all requests
secured_endpoints = [Endpoint.ACCOUNT, Endpoint.TRADE_MY,
Endpoint.ORDER, Endpoint.ORDER_TEST, Endpoint.ORDER_MY, Endpoint.ORDER_CURRENT]
# endpoint -> endpoint (if has different endpoint for history)
history_endpoint_lookup = {
Endpoint.TRADE: Endpoint.TRADE_HISTORY,
}
# endpoint -> platform_endpoint
endpoint_lookup = None
max_limit_by_endpoint = None
@property
def default_sorting(self):
# Default sorting for current platform if no sorting param is specified
return self._get_platform_param_value(Sorting.DEFAULT_SORTING)
def preprocess_params(self, endpoint, params):
self._process_limit_param(endpoint, params)
self._process_sorting_param(endpoint, params)
# Must be after sorting added
self._process_from_item_param(endpoint, params)
return params
def _process_limit_param(self, endpoint, params):
# (If LIMIT param is set to None (expected, but not defined))
is_use_max_limit = self.is_use_max_limit or (params.get(ParamName.IS_USE_MAX_LIMIT, False) if params else False)
is_limit_supported_here = params and ParamName.LIMIT in params
if is_use_max_limit and is_limit_supported_here and params[ParamName.LIMIT] is None:
value = self.max_limit_by_endpoint.get(endpoint, 1000000) if self.max_limit_by_endpoint else None
if value is not None:
# Set limit to maximum supported by a platform
params[ParamName.LIMIT] = value
def _process_sorting_param(self, endpoint, params):
# (Add only if a platform supports it, and it is not already added)
if not self.IS_SORTING_ENABLED and ParamName.SORTING in params:
del params[ParamName.SORTING]
elif self.IS_SORTING_ENABLED and not params.get(ParamName.SORTING):
params[ParamName.SORTING] = self.sorting
def _get_real_sorting(self, params):
sorting = params.get(ParamName.SORTING) if params else None
return sorting or self.default_sorting
def _process_from_item_param(self, endpoint, params):
from_item = params.get(ParamName.FROM_ITEM)
if not from_item or not params: # or not self.IS_SORTING_ENABLED:
return
to_item = params.get(ParamName.TO_ITEM)
is_descending = self._get_real_sorting(params) == Sorting.DESCENDING
# (from_item <-> to_item)
# is_from_newer_than_to = getattr(from_item, self.ITEM_TIMESTAMP_ATTR, 0) > \
# getattr(to_item, self.ITEM_TIMESTAMP_ATTR, 0)
is_from_newer_than_to = (from_item.timestamp or 0) > (to_item.timestamp or 0)
if from_item and to_item and is_from_newer_than_to:
params[ParamName.FROM_ITEM] = to_item
params[ParamName.TO_ITEM] = from_item
# (from_item -> to_item)
if is_descending and not to_item:
params[ParamName.TO_ITEM] = from_item
del params[ParamName.FROM_ITEM]
def process_secured(self, endpoint, platform_params, api_key, api_secret):
if endpoint in self.secured_endpoints:
platform_params = self._generate_and_add_signature(platform_params, api_key, api_secret)
return platform_params
def _generate_and_add_signature(self, platform_params, api_key, api_secret):
# Generate and add signature here
return platform_params
def post_process_result(self, method, endpoint, params, result):
# Process result using request data
if isinstance(result, Error):
return result
# (Symbol and interval are often not returned in response, so we have to set it here)
# symbol = params.get(ParamName.SYMBOL) if params else None
# if symbol:
# if isinstance(result, list):
# for item in result:
# if hasattr(item, ParamName.SYMBOL):
# item.symbol = symbol
# else:
# if hasattr(result, ParamName.SYMBOL):
# result.symbol = symbol
self._propagate_param_to_result(ParamName.SYMBOL, params, result)
self._propagate_param_to_result(ParamName.INTERVAL, params, result)
return result
def _propagate_param_to_result(self, param_name, params, result):
value = params.get(param_name) if params else None
if value:
if isinstance(result, list):
for item in result:
if hasattr(item, param_name):
setattr(item, param_name, value)
else:
if hasattr(result, param_name):
setattr(result, param_name, value)
class BaseRESTClient(BaseClient):
# Settings:
_log_prefix = "RESTClient"
default_converter_class = RESTConverter
# State:
delay_before_next_request_sec = 0
session = None
_last_response_for_debugging = None
@property
def headers(self):
return {
"Accept": "application/json",
"User-Agent": "client/python",
}
def __init__(self, version=None, **kwargs) -> None:
super().__init__(version, **kwargs)
self.session = requests.session()
def close(self):
if self.session:
self.session.close()
def _send(self, method, endpoint, params=None, version=None, **kwargs):
converter = self.get_or_create_converter(version)
# Prepare
params = dict(**kwargs, **(params or {}))
params = converter.preprocess_params(endpoint, params)
url, platform_params = converter.make_url_and_platform_params(endpoint, params, version=version)
platform_params = converter.process_secured(endpoint, platform_params, self._api_key, self._api_secret)
if not url:
return None
# Send
kwargs = {"headers": self.headers}
params_name = "params" if method.lower() == "get" else "data"
kwargs[params_name] = platform_params
self.logger.info("Send: %s %s %s", method, url, platform_params)
response = self.session.request(method, url, **kwargs)
# Parse
self._last_response_for_debugging = response
if response.ok:
result = converter.parse(endpoint, response.json())
result = converter.post_process_result(method, endpoint, params, result)
else:
is_json = "json" in response.headers.get("content-type", "")
result = converter.parse_error(response.json() if is_json else None, response)
self.logger.info("Response: %s Parsed result: %s %s", response,
len(result) if isinstance(result, list) else "",
str(result)[:100] + " ... " + str(result)[-100:])
self._on_response(response, result)
# Return parsed value objects or Error instance
return result
def _on_response(self, response, result):
pass
class PlatformRESTClient(BaseRESTClient):
"""
Important! Behavior when some param is None or for any other case should be same for all platforms.
Important! from and to params must be including: [from, to], not [from, to) or (from, to).
Закомментированные методы скорее всего не понадобятся, но на всякий случай они добавлены,
чтобы потом не возвращаться и не думать заново.
"""
_server_time_diff_s = None
def ping(self, version=None, **kwargs):
endpoint = Endpoint.PING
return self._send("GET", endpoint, version=version, **kwargs)
def get_server_timestamp(self, force_from_server=False, version=None, **kwargs):
endpoint = Endpoint.SERVER_TIME
if not force_from_server and self._server_time_diff_s is not None:
# (Calculate using time difference with server taken from previous call)
result = self._server_time_diff_s + time.time()
return int(result * 1000) if self.use_milliseconds else result
time_before = time.time()
result = self._send("GET", endpoint, version=version, **kwargs)
if isinstance(result, Error):
return result
# (Update time diff)
self._server_time_diff_s = (result / 1000 if self.use_milliseconds else result) - time_before
return result
def get_symbols(self, version=None, **kwargs):
endpoint = Endpoint.SYMBOLS
return self._send("GET", endpoint, version=version, **kwargs)
def fetch_history(self, endpoint, symbol, limit=None, from_item=None, to_item=None,
sorting=None, is_use_max_limit=False, from_time=None, to_time=None,
version=None, **kwargs):
# Common method for fetching history for any endpoint. Used in REST connector.
# (Convert endpoint to history endpoint if they differ)
history_endpoint_lookup = self.converter.history_endpoint_lookup
endpoint = history_endpoint_lookup.get(endpoint, endpoint) if history_endpoint_lookup else endpoint
params = {
ParamName.SYMBOL: symbol,
ParamName.LIMIT: limit,
ParamName.FROM_ITEM: from_item,
ParamName.TO_ITEM: to_item,
ParamName.SORTING: sorting,
ParamName.IS_USE_MAX_LIMIT: is_use_max_limit,
ParamName.FROM_TIME: from_time,
ParamName.TO_TIME: to_time,
}
self.logger.debug("fetch_history from: %s to: %s", from_item or from_time, to_item or to_time)
result = self._send("GET", endpoint, params, version, **kwargs)
return result
# Trade
def fetch_trades(self, symbol, limit=None, version=None, **kwargs):
# Fetch current (last) trades to display at once.
endpoint = Endpoint.TRADE
params = {
ParamName.SYMBOL: symbol,
ParamName.LIMIT: limit,
}
result = self._send("GET", endpoint, params, version, **kwargs)
return result
def fetch_trades_history(self, symbol, limit=None, from_item=None, to_item=None,
sorting=None, is_use_max_limit=False, from_time=None, to_time=None,
version=None, **kwargs):
# Fetching whole trades history as much as possible.
# from_time and to_time used along with from_item and to_item as we often need to fetch
# history by time and only Binance (as far as I know) doesn't support that (only by id)
return self.fetch_history(Endpoint.TRADE, symbol, limit, from_item, to_item,
sorting, is_use_max_limit, from_time, to_time,
version, **kwargs)
# Candle
def fetch_candles(self, symbol, interval, limit=None, from_time=None, to_time=None,
is_use_max_limit=False, version=None, **kwargs):
endpoint = Endpoint.CANDLE
params = {
ParamName.SYMBOL: symbol,
ParamName.INTERVAL: interval,
ParamName.LIMIT: limit,
ParamName.FROM_TIME: from_time,
ParamName.TO_TIME: to_time,
ParamName.IS_USE_MAX_LIMIT: is_use_max_limit,
}
result = self._send("GET", endpoint, params, version, **kwargs)
return result
# Ticker
def fetch_ticker(self, symbol=None, version=None, **kwargs):
endpoint = Endpoint.TICKER
params = {
ParamName.SYMBOL: symbol,
}
result = self._send("GET", endpoint, params, version, **kwargs)
return result
def fetch_tickers(self, symbols=None, version=None, **kwargs):
endpoint = Endpoint.TICKER
# (Send None for all symbols)
# params = {
# ParamName.SYMBOLS: None,
# }
result = self._send("GET", endpoint, None, version, **kwargs)
if symbols:
# Filter result for symbols defined
symbols = [symbol.upper() if symbol else symbol for symbol in symbols]
return [item for item in result if item.symbol in symbols]
return result
# Order Book
def fetch_order_book(self, symbol=None, limit=None, is_use_max_limit=False,
version=None, **kwargs):
# Level 2 (price-aggregated) order book for a particular symbol.
endpoint = Endpoint.ORDER_BOOK
params = {
ParamName.SYMBOL: symbol,
ParamName.LIMIT: limit,
}
result = self._send("GET", endpoint, params, version, **kwargs)
return result
# def fetch_order_book_L2_L3(self, symbol=None, limit=None, version=None, **kwargs):
# # Fetch L2/L3 order book (with all orders enlisted) for a particular market trading symbol.
# pass
class PrivatePlatformRESTClient(PlatformRESTClient):
def __init__(self, api_key=None, api_secret=None, version=None, **kwargs) -> None:
super().__init__(version=version, **kwargs)
self._api_key = api_key
self._api_secret = api_secret
# Trades
def fetch_account_info(self, version=None, **kwargs):
# Balance included to account
endpoint = Endpoint.ACCOUNT
params = {}
result = self._send("GET", endpoint, params, version or "3", **kwargs)
return result
def fetch_my_trades(self, symbol, limit=None, version=None, **kwargs):
endpoint = Endpoint.TRADE_MY
params = {
ParamName.SYMBOL: symbol,
ParamName.LIMIT: limit,
}
result = self._send("GET", endpoint, params, version or "3", **kwargs)
return result
# def fetch_my_trades_history(self, symbol, limit=None, from_item=None, to_item=None,
# sorting=None, is_use_max_limit=False, version=None, **kwargs):
# pass
# Order (private)
def create_order(self, symbol, order_type, direction, price=None, amount=None, is_test=False,
version=None, **kwargs):
endpoint = Endpoint.ORDER_TEST if is_test else Endpoint.ORDER
# if order_type != OrderType.MARKET:
# price = None
params = {
ParamName.SYMBOL: symbol,
ParamName.ORDER_TYPE: order_type,
ParamName.DIRECTION: direction,
ParamName.PRICE: price if order_type == OrderType.LIMIT else None,
ParamName.AMOUNT: amount,
}
result = self._send("POST", endpoint, params, version=version or "3", **kwargs)
return result
def cancel_order(self, order, symbol=None, version=None, **kwargs):
endpoint = Endpoint.ORDER
params = {
# ParamName.ORDER_ID: order.item_id if isinstance(order, Order) else order,
ParamName.ORDER_ID: order,
ParamName.SYMBOL: symbol, # move to converter(?): or (order.symbol if hasattr(order, ParamName.SYMBOL) else None),
}
result = self._send("DELETE", endpoint, params, version or "3", **kwargs)
return result
# was fetch_order
def check_order(self, order, symbol=None, version=None, **kwargs): # , direction=None
# item_id should be enough, but some platforms also need symbol and direction
endpoint = Endpoint.ORDER
params = {
ParamName.SYMBOL: symbol,
ParamName.ORDER_ID: order,
# ParamName.: ,
}
result = self._send("GET", endpoint, params, version or "3", **kwargs)
return result
def fetch_orders(self, symbol=None, limit=None, from_item=None, is_open=False,
version=None, **kwargs): # , order_status=None
endpoint = Endpoint.ORDER_CURRENT if is_open else Endpoint.ORDER_MY
params = {
ParamName.SYMBOL: symbol,
# ParamName.: ,
ParamName.LIMIT: limit,
ParamName.FROM_ITEM: from_item,
# ParamName.: ,
}
result = self._send("GET", endpoint, params, version or "3", **kwargs)
return result
# WebSocket
class WSConverter(ProtocolConverter):
# Main params:
# False - Subscribing by connecting URL: BitMEX, Binance.
# True - Subscribing by command: Bitfinex (v1, v2).
IS_SUBSCRIPTION_COMMAND_SUPPORTED = True
# supported_endpoints = None
# symbol_endpoints = None # In subclass you can call REST API to get symbols
supported_endpoints = [Endpoint.TRADE, Endpoint.CANDLE, Endpoint.TICKER, Endpoint.TICKER_ALL,
Endpoint.ORDER_BOOK, Endpoint.ORDER_BOOK_DIFF]
symbol_endpoints = [Endpoint.TRADE, Endpoint.CANDLE,
Endpoint.TICKER, # can be used as symbol and as generic endpoint
Endpoint.ORDER_BOOK, Endpoint.ORDER_BOOK_DIFF]
# generic_endpoints = None # = supported_endpoints.difference(symbol_endpoints)
supported_symbols = None
# Converting info:
# For converting to platform
# For parsing from platform
event_type_param = None
endpoint_by_event_type = None
item_class_by_endpoint = dict(**ProtocolConverter.item_class_by_endpoint, **{
# # Item class by event type
# "error": Error,
# "info": Info,
# "subscribed": Channel,
})
# For converting time
@property
def generic_endpoints(self):
# Non-symbol endpoints
return self.supported_endpoints.difference(self.symbol_endpoints or set()) \
if self.supported_endpoints else set()
def generate_subscriptions(self, endpoints, symbols, **params):
result = set()
for endpoint in endpoints:
if endpoint in self.symbol_endpoints:
if symbols:
for symbol in symbols:
result.add(self._generate_subscription(endpoint, symbol, **params))
else:
result.add(self._generate_subscription(endpoint, None, **params))
else:
result.add(self._generate_subscription(endpoint, **params))
return result
def _generate_subscription(self, endpoint, symbol=None, **params):
channel = self._get_platform_endpoint(endpoint, {ParamName.SYMBOL: symbol, **params})
return channel
def parse(self, endpoint, data):
# (Get endpoint from event type)
if not endpoint and data and isinstance(data, dict) and self.event_type_param:
event_type = data.get(self.event_type_param, endpoint)
endpoint = self.endpoint_by_event_type.get(event_type, event_type) \
if self.endpoint_by_event_type else event_type
# if not endpoint:
# self.logger.error("Cannot find event type by name: %s in data: %s", self.event_type_param, data)
# self.logger.debug("Endpoint: %s by name: %s in data: %s", endpoint, self.event_type_param, data)
return super().parse(endpoint, data)
class WSClient(BaseClient):
"""
Using:
client = WSClient(api_key, api_secret)
client.subscribe([Endpoint.TRADE], ["ETHUSD", "ETHBTC"])
# (Will reconnect for platforms which needed that)
client.subscribe([Endpoint.TRADE], ["ETHBTC", "ETHUSD"])
# Resulting subscriptions: [Endpoint.TRADE] channel for symbols:
# ["ETHUSD", "ETHBTC", "ETHBTC", "ETHUSD"]
"""
# Settings:
_log_prefix = "WSClient"
default_converter_class = WSConverter
is_auto_reconnect = True
reconnect_delay_sec = 3
reconnect_count = 3
on_connect = None
on_data = None
on_data_item = None
on_disconnect = None
# State:
# Subscription sets
endpoints = None
symbols = None
# endpoints + symbols = subscriptions
current_subscriptions = None
pending_subscriptions = None
successful_subscriptions = None
failed_subscriptions = None
is_subscribed_with_url = False
# Connection
is_started = False
_is_reconnecting = True
_reconnect_tries = 0
ws = None
thread = None
_data_buffer = None
@property
def url(self):
# Override if you need to introduce some get params
# (Set self.is_subscribed_with_url=True if subscribed in here in URL)
url, platform_params = self.converter.make_url_and_platform_params()
return url if self.converter else ""
@property
def is_connected(self):
return self.ws.sock.connected if self.ws and self.ws.sock else False
def __init__(self, api_key=None, api_secret=None, version=None, **kwargs) -> None:
super().__init__(version, **kwargs)
self._api_key = api_key
self._api_secret = api_secret
# (For convenience)
self.IS_SUBSCRIPTION_COMMAND_SUPPORTED = self.converter.IS_SUBSCRIPTION_COMMAND_SUPPORTED
# Subscription
def subscribe(self, endpoints=None, symbols=None, **params):
"""
Subscribe and connect.
None means all: all previously subscribed or (if none) all supported.
subscribe() # subscribe to all supported endpoints (currently only generic ones)
unsubscribe() # unsubscribe all
subscribe(symbols=["BTCUSD"]) # subscribe to all supported endpoints for "BTCUSD"
unsubscribe(endpoints=["TRADE"]) # unsubscribe all "TRADE" channels - for all symbols
unsubscribe() # unsubscribe all (except "TRADE" which has been already unsubscribed before)
subscribe(endpoints=["TRADE"], symbols=["BTCUSD"]) # subscribe to all supported endpoints for "BTCUSD"
unsubscribe() # unsubscribe all "TRADE" channels
subscribe() # subscribe to all "TRADE" channels back because it was directly
unsubscribe(endpoints=["TRADE"]) # unsubscribe all "TRADE" channels directly (currently only for "BTCUSD")
subscribe() # subscribe all supported channels for symbol "BTCUSD" (as this symbol wasn't unsubscribed directly)
unsubscribe(symbols=["BTCUSD"]) # unsubscribe all channels for "BTCUSD"
:param endpoints:
:param symbols:
:return:
"""
self.logger.debug("Subscribe on endpoints: %s and symbols: %s prev: %s %s",
endpoints, symbols, self.endpoints, self.symbols)
# if not endpoints and not symbols:
# subscriptions = self.prev_subscriptions
# else:
if not endpoints:
endpoints = self.endpoints or self.converter.supported_endpoints
else:
endpoints = set(endpoints).intersection(self.converter.supported_endpoints)
self.endpoints = self.endpoints.union(endpoints) if self.endpoints else endpoints
if not symbols:
symbols = self.symbols or self.converter.supported_symbols
else:
self.symbols = self.symbols.union(symbols) if self.symbols else set(symbols)
if not endpoints:
return
subscriptions = self.converter.generate_subscriptions(endpoints, symbols, **params)
self.current_subscriptions = self.current_subscriptions.union(subscriptions) \
if self.current_subscriptions else subscriptions
self._subscribe(subscriptions)
def unsubscribe(self, endpoints=None, symbols=None, **params):
# None means "all"
self.logger.debug("Subscribe from endpoints: %s and symbols: %s", endpoints, symbols)
subscribed = self.pending_subscriptions.union(self.successful_subscriptions or set()) \
if self.pending_subscriptions else set()
if not endpoints and not symbols:
subscriptions = self.current_subscriptions.copy()
# if self.current_subscriptions:
# self.prev_subscriptions = self.current_subscriptions
self.current_subscriptions.clear()
self.failed_subscriptions.clear()
self.pending_subscriptions.clear()
self.successful_subscriptions.clear()
else:
if not endpoints:
endpoints = self.endpoints
else:
self.endpoints = self.endpoints.difference(endpoints) if self.endpoints else set()
if not symbols:
symbols = self.symbols
else:
self.symbols = self.symbols.difference(symbols) if self.symbols else set()
if not endpoints:
return
subscriptions = self.converter.generate_subscriptions(endpoints, symbols, **params)
self.current_subscriptions = self.current_subscriptions.difference(subscriptions)
self.failed_subscriptions = self.failed_subscriptions.difference(subscriptions)
self.pending_subscriptions = self.pending_subscriptions.difference(subscriptions)
self.successful_subscriptions = self.successful_subscriptions.difference(subscriptions)
self._unsubscribe(subscriptions.intersection(subscribed))
def resubscribe(self):
self.logger.debug("Resubscribe all current subscriptions")
# Unsubscribe & subscribe all
if self.IS_SUBSCRIPTION_COMMAND_SUPPORTED:
# Send unsubscribe all and subscribe all back again not interrupting a connection
self.unsubscribe()
self.subscribe()
else:
# Platforms which subscribe in WS URL need reconnection
self.reconnect()
def _subscribe(self, subscriptions):
# Call subscribe command with "subscriptions" param or reconnect with
# "self.current_subscriptions" in URL - depending on platform
self.logger.debug(" Subscribe to subscriptions: %s", subscriptions)
if not self.is_started or not self.IS_SUBSCRIPTION_COMMAND_SUPPORTED:
# Connect on first subscribe() or reconnect on the further ones
self.reconnect()
else:
self._send_subscribe(subscriptions)
def _unsubscribe(self, subscriptions):
# Call unsubscribe command with "subscriptions" param or reconnect with
# "self.current_subscriptions" in URL - depending on platform
self.logger.debug(" Subscribe from subscriptions: %s", subscriptions)
if not self.is_started or not self.IS_SUBSCRIPTION_COMMAND_SUPPORTED:
self.reconnect()
else:
self._send_unsubscribe(subscriptions)
def _send_subscribe(self, subscriptions):
# Implement in subclass
pass
def _send_unsubscribe(self, subscriptions):
# Implement in subclass
pass
# Connection
def connect(self, version=None):
# Check ready
if not self.current_subscriptions:
self.logger.warning("Please subscribe before connect.")
return
# Do nothing if was called before
if self.ws and self.is_started:
self.logger.warning("WebSocket is already started.")
return
# Connect
if not self.ws:
self.ws = WebSocketApp(self.url, header=self.headers,
on_open=self._on_open,
on_message=self._on_message,
on_error=self._on_error,
on_close=self._on_close)
else:
self.ws.url = self.url
self.ws.header = self.headers
# (run_forever() will raise an exception if previous socket is still not closed)
self.logger.debug("Start WebSocket with url: %s" % self.ws.url)
self.is_started = True
self.thread = Thread(target=self.ws.run_forever)
self.thread.daemon = True
self.thread.start()
def reconnect(self):
self.logger.debug("Reconnect WebSocket")
self.close()
self.connect()
def close(self):
if not self.is_started:
# Nothing to close
return
self.logger.debug("Close WebSocket")
# (If called directly or from _on_close())
self.is_started = False
if self.is_connected:
# (If called directly)
self.ws.close()
super().close()
def _on_open(self):
self.logger.debug("On open. %s", "Connected." if self.is_connected else "NOT CONNECTED. It's impossible!")
# (Stop reconnecting)
self._is_reconnecting = False
self._reconnect_tries = 0
if self.on_connect:
self.on_connect()
# Subscribe by command on connect
if self.IS_SUBSCRIPTION_COMMAND_SUPPORTED and not self.is_subscribed_with_url:
self.subscribe()
def _on_message(self, message):
self.logger.debug("On message: %s", message[:200])
# str -> json
try:
data = json.loads(message)
except json.JSONDecodeError:
self.logger.error("Wrong JSON is received! Skipped. message: %s", message)
return
# json -> items
result = self._parse(None, data)
# Process items
self._data_buffer = []
if result and isinstance(result, list):
for item in result:
self.on_item_received(item)
else:
self.on_item_received(result)
if self.on_data and self._data_buffer:
self.on_data(self._data_buffer)
def _parse(self, endpoint, data):
if data and isinstance(data, list):
return [self.converter.parse(endpoint, data_item) for data_item in data]
return self.converter.parse(endpoint, data)
def on_item_received(self, item):
# To skip empty and unparsed data
if self.on_data_item and isinstance(item, DataObject):
self.on_data_item(item)
self._data_buffer.append(item)
def _on_error(self, error_exc):
self.logger.exception("On error exception from websockets: %s", error_exc)
pass
def _on_close(self):
self.logger.info("On WebSocket close")
if self.on_disconnect:
self.on_disconnect()
if self.is_started or (self._is_reconnecting and self._reconnect_tries < self.reconnect_count):
self._is_reconnecting = True
if self._reconnect_tries == 0:
# Don't wait before the first reconnection try
time.sleep(self.reconnect_delay_sec)
self._reconnect_tries += 1
self.reconnect()
return
self._is_reconnecting = False
self.close()
def _send(self, data):
if not data:
return
message = json.dumps(data)
self.logger.debug("Send message: %s", message)
self.ws.send(message)
# Processing
|
{"/hyperquant/clients/tests/test_init.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py", "/hyperquant/clients/utils.py"], "/hyperquant/clients/tests/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/tests/test_api.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/__init__.py": ["/hyperquant/api.py"], "/hyperquant/clients/tests/test_bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/tests/test_utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/utils.py"], "/run_demo.py": ["/settings.py", "/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py"], "/hyperquant/clients/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py"], "/hyperquant/clients/binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"]}
|
13,213
|
assassinen/hyperquant
|
refs/heads/master
|
/hyperquant/clients/tests/test_bitmex.py
|
from hyperquant.api import Platform
from hyperquant.clients.bitmex import BitMEXRESTConverterV1, BitMEXRESTClient, BitMEXWSClient, BitMEXWSConverterV1
from hyperquant.clients.tests.test_init import TestRESTClient, TestWSClient, TestConverter, TestRESTClientHistory
# TODO check https://www.bitmex.com/app/restAPI "Обратите внимание: все суммы в биткойнах при
# возврате запроса указываются в Satoshi: 1 XBt (Satoshi) = 0,00000001 XBT (биткойн)."
# REST
class TestBitMEXRESTConverterV1(TestConverter):
converter_class = BitMEXRESTConverterV1
class TestBitMEXRESTClientV1(TestRESTClient):
platform_id = Platform.BITMEX
version = "1"
# testing_symbol = "XBTUSD"
testing_symbol = None # BitMEX returns all symbols if symbol param is not specified
testing_symbol2 = "XBTUSD"
is_sorting_supported = True
has_limit_error = True
is_symbol_case_sensitive = True
class TestBitMEXRESTClientHistoryV1(TestRESTClientHistory):
platform_id = Platform.BITMEX
version = "1"
# testing_symbol = "XBTUSD"
testing_symbol = None # BitMEX returns all symbols if symbol param is not specified
testing_symbol2 = "XBTUSD"
is_sorting_supported = True
has_limit_error = True
is_symbol_case_sensitive = True
def test_fetch_trades_errors(self, method_name="fetch_trades", is_auth=False):
client = self.client_authed if is_auth else self.client
# Wrong symbol
result = getattr(client, method_name)(self.wrong_symbol)
# Empty list instead of error (todo check, may be we should create error for each empty list returned)
self.assertEqual(result, [])
if self.is_symbol_case_sensitive:
# Symbol in lower case as wrong symbol
result = getattr(client, method_name)(self.testing_symbol2.lower())
self.assertIsNotNone(result)
self.assertEqual(result, [])
# WebSocket
class TestBitMEXWSConverterV1(TestConverter):
converter_class = BitMEXWSConverterV1
class TestBitMEXWSClientV1(TestWSClient):
platform_id = Platform.BITMEX
version = "1"
testing_symbol = "XBTUSD"
testing_symbols = ["ETHUSD", "XBTUSD"]
|
{"/hyperquant/clients/tests/test_init.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py", "/hyperquant/clients/utils.py"], "/hyperquant/clients/tests/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/tests/test_api.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/__init__.py": ["/hyperquant/api.py"], "/hyperquant/clients/tests/test_bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/tests/test_utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/utils.py"], "/run_demo.py": ["/settings.py", "/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py"], "/hyperquant/clients/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py"], "/hyperquant/clients/binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"]}
|
13,214
|
assassinen/hyperquant
|
refs/heads/master
|
/hyperquant/api.py
|
from collections import Iterable
from decimal import Decimal
from clickhouse_driver.errors import ServerException
from dateutil import parser
from django.http import JsonResponse
"""
Common out API format is defined here.
When we calling any other platform API like Binance or Bitfinex we convert
all response data to this format.
When anyone calling our REST API this format is used too.
"""
# Trading platforms, REST API, and DB:
# Constants
class Platform:
BINANCE = 1
BITFINEX = 2
BITMEX = 3
name_by_id = {
1: "BINANCE",
2: "BITFINEX",
3: "BITMEX",
}
id_by_name = {v: k for k, v in name_by_id.items()}
@classmethod
def get_platform_name_by_id(cls, platform_id):
return cls.name_by_id.get(platform_id)
@classmethod
def get_platform_id_by_name(cls, platform, is_check_valid_id=False):
# platform - name or id, all other values will be converted to None
if isinstance(platform, str) and platform.isnumeric():
platform = int(platform)
return cls.id_by_name.get(str(platform).upper(),
platform if not is_check_valid_id or platform in cls.name_by_id else None)
class Endpoint:
# Note: you can use any value, but remember they will be used in all our APIs,
# and they must differ from each other
# ALL = "*" # Used by WS Client
# For all platforms and our REST API (except *_HISTORY)
PING = "ping"
SERVER_TIME = "time"
SYMBOLS = "symbols"
TRADE = "trade"
TRADE_HISTORY = "trade/history"
TRADE_MY = "trade/my" # Private
CANDLE = "candle"
# CANDLE_HISTORY = "candle/history"
TICKER = "ticker"
TICKER_ALL = "ticker_all"
# TICKER_HISTORY = "ticker/history"
ORDER_BOOK = "orderbook"
# ORDER_BOOK_HISTORY = "orderbook/history"
ORDER_BOOK_DIFF = "orderbook" # WS
# Private
ACCOUNT = "account"
ORDER = "order"
ORDER_TEST = "order/test"
ORDER_CURRENT = "order/current"
ORDER_MY = "order/my"
# ORDER_HISTORY = "order/history"
# For our REST API only
ITEM = ""
HISTORY = "/history"
FORMAT = "/format"
ALL = [SERVER_TIME, SYMBOLS, TRADE, TRADE_HISTORY, TRADE_MY, CANDLE, TICKER, TICKER_ALL,
ORDER_BOOK, ORDER_BOOK_DIFF, ACCOUNT, ORDER, ORDER_TEST, ORDER_CURRENT, ORDER_MY,
ITEM, HISTORY, FORMAT]
class ParamName:
# Stores names which are used:
# 1. in params of client.send() method;
# 2. in value object classes!;
# 3. field names in DB;
# 4. in our REST APIs.
ID = "id"
ITEM_ID = "item_id"
TRADE_ID = "trade_id"
ORDER_ID = "order_id"
USER_ORDER_ID = "user_order_id"
SYMBOL = "symbol"
SYMBOLS = "symbols" # For our REST API only
LIMIT = "limit"
IS_USE_MAX_LIMIT = "is_use_max_limit" # used in clients only
LIMIT_SKIP = "limit_skip"
PAGE = "page" # instead of LIMIT_SKIP
SORTING = "sorting"
INTERVAL = "interval"
DIRECTION = "direction" # Sell/buy or ask/bid
ORDER_TYPE = "order_type"
ORDER_STATUS = "order_status"
LEVEL = "level" # For order book (WS)
TRADES_COUNT = "trades_count"
TIMESTAMP = "timestamp"
FROM_ITEM = "from_item"
TO_ITEM = "to_item"
FROM_TIME = "from_time"
TO_TIME = "to_time"
FROM_PRICE = "from_price"
TO_PRICE = "to_price"
FROM_AMOUNT = "from_amount"
TO_AMOUNT = "to_amount"
PRICE_OPEN = "price_open"
PRICE_CLOSE = "price_close"
PRICE_HIGH = "price_high"
PRICE_LOW = "price_low"
PRICE = "price"
AMOUNT_ORIGINAL = "amount_original"
AMOUNT_EXECUTED = "amount_executed"
AMOUNT_AVAILABLE = "amount_available"
AMOUNT_RESERVED = "amount_reserved"
AMOUNT = "amount"
FEE = "fee"
REBATE = "rebate"
BALANCES = "balances"
ASKS = "asks"
BIDS = "bids"
# For our REST API only
PLATFORM_ID = "platform_id"
PLATFORM = "platform" # (alternative)
PLATFORMS = "platforms" # (alternative)
# ENDPOINT = "endpoint"
IS_SHORT = "is_short"
ALL = [ID, ITEM_ID, TRADE_ID, ORDER_ID, USER_ORDER_ID,
LIMIT, IS_USE_MAX_LIMIT, LIMIT_SKIP, PAGE, SORTING,
SYMBOL, SYMBOLS, DIRECTION, INTERVAL, ORDER_TYPE, LEVEL,
TIMESTAMP, FROM_ITEM, TO_ITEM, FROM_TIME, TO_TIME,
FROM_PRICE, TO_PRICE, FROM_AMOUNT, TO_AMOUNT,
PRICE_OPEN, PRICE_CLOSE, PRICE_HIGH, PRICE_LOW, PRICE,
AMOUNT_ORIGINAL, AMOUNT_EXECUTED, AMOUNT, FEE, REBATE, BIDS, ASKS,
PLATFORM_ID, PLATFORM, PLATFORMS, IS_SHORT]
_timestamp_names = (TIMESTAMP, FROM_TIME, TO_TIME)
_decimal_names = (PRICE, FROM_PRICE, TO_PRICE, AMOUNT, FROM_AMOUNT, TO_AMOUNT)
@classmethod
def is_timestamp(cls, name):
return name in cls._timestamp_names
@classmethod
def is_decimal(cls, name):
return name in cls._decimal_names
class ParamValue:
# todo remove sometimes
# param_names = [ParamName.SORTING]
# For limit
MIN = "min"
MAX = "max"
ALL = "all"
UNDEFINED = None
class Sorting:
ASCENDING = "asc" # Oldest first
DESCENDING = "desc" # Newest first, usually default
DEFAULT_SORTING = "default_sorting" # (For internal uses only)
class Interval:
# For candles
MIN_1 = "1m"
MIN_3 = "3m"
MIN_5 = "5m"
MIN_15 = "15m"
MIN_30 = "30m"
HRS_1 = "1h"
HRS_2 = "2h"
HRS_4 = "4h"
HRS_6 = "6h"
HRS_8 = "8h"
HRS_12 = "12h"
DAY_1 = "1d"
DAY_3 = "3d"
WEEK_1 = "1w"
MONTH_1 = "1M"
ALL = [MIN_1, MIN_3, MIN_5, MIN_15, MIN_30,
HRS_1, HRS_2, HRS_4, HRS_6, HRS_8, HRS_12,
DAY_1, DAY_3, WEEK_1, MONTH_1]
class Direction:
# (trade, order)
SELL = 1
BUY = 2
# (for our REST API as alternative values)
SELL_NAME = "sell"
BUY_NAME = "buy"
name_by_value = {
SELL: SELL_NAME,
BUY: BUY_NAME,
}
value_by_name = {v: k for k, v in name_by_value.items()}
@classmethod
def get_direction_value(cls, direction, is_check_valid_id=True):
return cls.value_by_name.get(str(direction).upper(),
direction if not is_check_valid_id or direction in cls.name_by_value else None)
class OrderBookDirection:
# Direction for order book (same as sell/buy but with different names)
ASK = 1 # Same as sell
BID = 2 # Same as buy
# (for our REST API as alternative values)
ASK_NAME = "ask"
BID_NAME = "bid"
name_by_value = {
ASK: ASK_NAME,
BID: BID_NAME,
}
value_by_name = {v: k for k, v in name_by_value.items()}
class OrderType:
LIMIT = 1
MARKET = 2
# (for our REST API)
LIMIT_NAME = "limit"
MARKET_NAME = "market"
name_by_value = {
LIMIT: LIMIT_NAME,
MARKET: MARKET_NAME,
}
value_by_name = {v: k for k, v in name_by_value.items()}
class OrderStatus:
OPEN = 1
CLOSED = 0
NEW = 2
PARTIALLY_FILLED = 3
FILLED = 4
# PENDING_CANCEL = 5
CANCELED = 6
REJECTED = 7
EXPIRED = 8
# (for our REST API)
OPEN_NAME = "open"
CLOSED_NAME = "closed"
NEW_NAME = "new"
PARTIALLY_FILLED_NAME = "partially_filled"
FILLED_NAME = "filled"
# PENDING_CANCEL_NAME = "pending_cancel"
CANCELED_NAME = "canceled"
REJECTED_NAME = "rejected"
EXPIRED_NAME = "expired"
name_by_value = {
OPEN: OPEN_NAME,
CLOSED: CLOSED_NAME,
NEW: NEW_NAME,
PARTIALLY_FILLED: PARTIALLY_FILLED_NAME,
FILLED: FILLED_NAME,
# PENDING_CANCEL: PENDING_CANCEL_NAME,
CANCELED: CANCELED_NAME,
REJECTED: REJECTED_NAME,
EXPIRED: EXPIRED_NAME,
}
value_by_name = {v: k for k, v in name_by_value.items()}
class ErrorCode:
# Provides same error codes and messages for all trading platforms
# Надо накопить достаточно типов ошибок, систематизировать их и дать им числовые коды,
# которые будет легко мнемонически запомнить, чтобы поотм легко можно было определить ошибку по ее коду
UNAUTHORIZED = "any1"
RATE_LIMIT = "any:ratelim"
IP_BAN = "any:ipban"
WRONG_SYMBOL = "any:wrsymbol"
WRONG_LIMIT = "any:wrlimit"
WRONG_PARAM = "any:wrparval"
APP_ERROR = "any:apperr"
APP_DB_ERROR = "any:appdberr"
message_by_code = {
UNAUTHORIZED: "Unauthorized. May be wrong api_key or api_secret or not defined at all.",
RATE_LIMIT: "Rate limit reached. We must make a delay for a while.",
WRONG_SYMBOL: "Wrong symbol. May be this symbol is not supported by platform or its name is wrong.",
WRONG_LIMIT: "Wrong limit. May be too big.",
WRONG_PARAM: "Wrong param value.",
APP_ERROR: "App error!",
APP_DB_ERROR: "App error! It's likely that app made wrong request to DB.",
}
@classmethod
def get_message_by_code(cls, code, default=None, **kwargs):
return cls.message_by_code[code].format_map(kwargs) if code in cls.message_by_code else default or "(no message: todo)"
# For DB, REST API
item_format_by_endpoint = {
Endpoint.TRADE: [
ParamName.PLATFORM_ID, ParamName.SYMBOL, ParamName.TIMESTAMP, ParamName.ITEM_ID,
ParamName.PRICE, ParamName.AMOUNT, ParamName.DIRECTION
],
}
# REST API:
# Parse request
def parse_platform_id(params):
param_names = [ParamName.PLATFORM, ParamName.PLATFORMS, ParamName.PLATFORM_ID]
for name in param_names:
value = params.get(name)
if value:
return _convert_platform_id(value)
return None
def parse_platform_ids(params):
platforms = params.get(ParamName.PLATFORMS, None) or params.get(ParamName.PLATFORM)
platforms = platforms.split(",") if isinstance(platforms, str) else platforms
return [_convert_platform_id(p) for p in platforms] if platforms else None
def _convert_platform_id(platform):
if platform is None:
return None
return int(platform) if platform.isnumeric() else Platform.id_by_name.get(platform.upper())
def parse_symbols(params):
# None -> None
# "xxxzzz,yyyZZZ" -> ["XXXZZZ", "YYYZZZ"]
symbols = params.get(ParamName.SYMBOLS) or params.get(ParamName.SYMBOL)
if symbols is None:
return None
return symbols.upper().split(",") if isinstance(symbols, str) else symbols
def parse_direction(params):
# None -> None
# "Sell" -> 1
# "BUY" -> 2
direction = params.get(ParamName.DIRECTION)
if direction is None:
return None
direction = int(direction) if direction.isnumeric() else \
Direction.value_by_name.get(direction.lower())
return direction if direction in (Direction.SELL, Direction.BUY) else None
def parse_timestamp(params, name):
# Any time value to Unix timestamp in seconds
time = params.get(name)
if time is None:
return None
if time.isnumeric():
return int(time)
try:
return float(time)
except ValueError:
return parser.parse(time).timestamp()
def parse_decimal(params, name):
value = params.get(name)
return Decimal(str(value)) if value is not None else None
def parse_limit(params, DEFAULT_LIMIT, MIN_LIMIT, MAX_LIMIT):
limit = int(params.get(ParamName.LIMIT, DEFAULT_LIMIT))
return min(MAX_LIMIT, max(MIN_LIMIT, limit))
def parse_sorting(params, DEFAULT_SORTING):
sorting = params.get(ParamName.SORTING, DEFAULT_SORTING)
return sorting
# sorting = params.get(ParamName.SORTING)
# # (Any wrong value treated as default)
# is_descending = sorting == (Sorting.ASCENDING if DEFAULT_SORTING == Sorting.DESCENDING else Sorting.DESCENDING)
# return Sorting.DESCENDING if is_descending else Sorting.ASCENDING
def sort_from_to_params(from_value, to_value):
# Swap if from_value > to_value
return (to_value, from_value) if from_value is not None and to_value is not None \
and from_value > to_value else (from_value, to_value)
# Prepare response
def make_data_response(data, item_format, is_convert_to_list=True):
result = None
if data:
if isinstance(data, Exception):
return make_error_response(exception=data)
if not isinstance(data, list) or not isinstance(data[0], list):
# {"param1": "prop1", "param2": "prop2"} -> [{"param1": "prop1", "param2": "prop2"}]
# ["prop1", "prop2"] -> [["prop1", "prop2"]]
data = [data]
if isinstance(data[0], list):
# [["prop1", "prop2"], ["prop1", "prop2"]] -> same
result = data if is_convert_to_list else convert_items_list_to_dict(data, item_format)
elif isinstance(data[0], dict):
# [{"param1": "prop1", "param2": "prop2"}] -> [["prop1", "prop2"]]
result = convert_items_dict_to_list(data, item_format) if is_convert_to_list else data
# elif isinstance(data[0], DataObject):
else:
result = convert_items_obj_to_list(data, item_format) if is_convert_to_list else \
convert_items_obj_to_dict(data, item_format)
return JsonResponse({
"data": result if result else [],
})
def make_error_response(error_code=None, exception=None, **kwargs):
if not error_code and exception:
if isinstance(exception, ServerException):
error_code = ErrorCode.APP_DB_ERROR
else:
error_code = ErrorCode.APP_ERROR
return JsonResponse({"error": {
"code": error_code,
"message": ErrorCode.get_message_by_code(error_code, **kwargs)
}})
def make_format_response(item_format):
values = {
ParamName.PLATFORM_ID: Platform.name_by_id,
# ParamName.PLATFORM: Platform.name_by_id,
ParamName.DIRECTION: Direction.name_by_value,
}
return JsonResponse({
"item_format": item_format,
"values": {k: v for k, v in values.items() if k in item_format},
"example_item": {"data": [[name + "X" for name in item_format]]},
# "example_item": {"data": [name + "X" for name in item_format]}, # ?
"example_history": {"data": [[name + str(i) for name in item_format] for i in range(3)]},
"example_error": {"error": {"code": 1, "message": "Error description."}},
})
# Utility:
# Convert items
def convert_items_obj_to_list(item_or_items, item_format):
if not item_or_items:
return item_or_items
return _convert_item_or_items_with_fun(item_or_items, item_format, _convert_items_obj_to_list)
def convert_items_dict_to_list(item_or_items, item_format):
if not item_or_items:
return item_or_items
return _convert_item_or_items_with_fun(item_or_items, item_format, _convert_items_dict_to_list)
def convert_items_list_to_dict(item_or_items, item_format):
if not item_or_items:
return item_or_items
return _convert_item_or_items_with_fun(item_or_items, item_format, _convert_items_list_to_dict)
def convert_items_obj_to_dict(item_or_items, item_format):
if not item_or_items:
return item_or_items
return _convert_item_or_items_with_fun(item_or_items, item_format, _convert_items_obj_to_dict)
def _convert_item_or_items_with_fun(item_or_items, item_format, fun):
# Input item - output item,
# input items - output items
if not item_format:
raise Exception("item_format cannot be None!")
is_list = isinstance(item_or_items, (list, tuple))
if is_list:
for element in item_or_items:
if element:
# Check the first not None element is not an item
# (list, dict (iterable but not a str) or object (has __dict__))
if isinstance(element, str) or not isinstance(element, Iterable) and \
not hasattr(element, "__dict__"):
is_list = False
break
items = item_or_items if is_list else [item_or_items]
# Convert
result = fun(items, item_format) if items else []
return result if is_list else result[0]
def _convert_items_obj_to_list(items, item_format):
return [[getattr(item, p) for p in item_format if hasattr(item, p)] if item is not None else None
for item in items] if items else []
def _convert_items_dict_to_list(items, item_format):
return [[item[p] for p in item_format if p in item] if item is not None else None
for item in items] if items else []
def _convert_items_list_to_dict(items, item_format):
index_property_list = list(enumerate(item_format))
return [{p: item[i] for i, p in index_property_list if i < len(item)} if item is not None else None
for item in items] if items else []
def _convert_items_obj_to_dict(items, item_format):
return [{p: getattr(item, p) for p in item_format if hasattr(item, p)} if item is not None else None
for item in items] if items else []
|
{"/hyperquant/clients/tests/test_init.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py", "/hyperquant/clients/utils.py"], "/hyperquant/clients/tests/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/tests/test_api.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/__init__.py": ["/hyperquant/api.py"], "/hyperquant/clients/tests/test_bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/tests/test_utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/utils.py"], "/run_demo.py": ["/settings.py", "/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py"], "/hyperquant/clients/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py"], "/hyperquant/clients/binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"]}
|
13,215
|
assassinen/hyperquant
|
refs/heads/master
|
/hyperquant/clients/tests/test_utils.py
|
import unittest
from hyperquant.api import Platform
from hyperquant.clients.binance import BinanceRESTClient, BinanceWSClient
from hyperquant.clients.bitfinex import BitfinexRESTClient, BitfinexWSClient
from hyperquant.clients.bitmex import BitMEXRESTClient, BitMEXWSClient
from hyperquant.clients.utils import create_rest_client, create_ws_client
class TestCreateClient(unittest.TestCase):
def test_create_rest_client(self):
self._test_create_client()
def test_create_ws_client(self):
self._test_create_client(False)
def test_create_rest_client_private(self):
self._test_create_client(is_private=True)
def test_create_ws_client_private(self):
self._test_create_client(False, is_private=True)
def _test_create_client(self, is_rest=True, is_private=False):
create_client = create_rest_client if is_rest else create_ws_client
# Binance
client = create_client(Platform.BINANCE, is_private)
self.assertIsInstance(client, BinanceRESTClient if is_rest else BinanceWSClient)
self.assertEqual(client.version, BinanceRESTClient.version)
if not is_private:
self.assertIsNotNone(client._api_key,
"For Binance, api_key must be set even for public API (for historyTrades endponit)")
self.assertIsNone(client._api_secret)
else:
self.assertIsNotNone(client._api_key)
self.assertIsNotNone(client._api_secret)
# Bitfinex
client = create_client(Platform.BITFINEX, is_private)
self.assertIsInstance(client, BitfinexRESTClient if is_rest else BitfinexWSClient)
self.assertEqual(client.version, BitfinexRESTClient.version)
if not is_private:
self.assertIsNone(client._api_key)
self.assertIsNone(client._api_secret)
else:
self.assertIsNotNone(client._api_key)
self.assertIsNotNone(client._api_secret)
# Testing version
client = create_client(Platform.BITFINEX, is_private, version="1")
self.assertIsInstance(client, BitfinexRESTClient if is_rest else BitfinexWSClient)
self.assertEqual(client.version, "1")
self.assertNotEqual(client.version, BitfinexRESTClient.version)
if not is_private:
self.assertIsNone(client._api_key)
self.assertIsNone(client._api_secret)
else:
self.assertIsNotNone(client._api_key)
self.assertIsNotNone(client._api_secret)
# BitMEX
client = create_client(Platform.BITMEX, is_private)
self.assertIsInstance(client, BitMEXRESTClient if is_rest else BitMEXWSClient)
self.assertEqual(client.version, BitMEXRESTClient.version)
if not is_private:
self.assertIsNone(client._api_key)
self.assertIsNone(client._api_secret)
else:
self.assertIsNotNone(client._api_key)
self.assertIsNotNone(client._api_secret)
|
{"/hyperquant/clients/tests/test_init.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py", "/hyperquant/clients/utils.py"], "/hyperquant/clients/tests/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/tests/test_api.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/__init__.py": ["/hyperquant/api.py"], "/hyperquant/clients/tests/test_bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/tests/test_utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/utils.py"], "/run_demo.py": ["/settings.py", "/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py"], "/hyperquant/clients/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py"], "/hyperquant/clients/binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"]}
|
13,216
|
assassinen/hyperquant
|
refs/heads/master
|
/run_demo.py
|
import time
from django.conf import settings
import settings as hqlib_settings
from hyperquant.api import Interval
from hyperquant.clients import (
utils, Endpoint, Platform
)
from hyperquant.clients.tests.utils import set_up_logging
settings.configure(DEBUG=True, default_settings=hqlib_settings)
# Enable logging if needed
# set_up_logging()
# Change to Platform.BINANCE to see example
TEST_PLATFORM = Platform.BINANCE
TEST_SYMBOLS = {
Platform.BINANCE: ['ETHBTC', 'BTCUSDT'],
# Platform.OKEX: ['eth_btc', 'btc_usdt'],
}
client = utils.create_rest_client(platform_id=TEST_PLATFORM)
print('\n\nTrade history\n\n')
print(client.fetch_trades_history(TEST_SYMBOLS[TEST_PLATFORM][0], limit=10))
print('\n\n---------------------')
print('\n\nCandles\n\n')
print(client.fetch_candles(TEST_SYMBOLS[TEST_PLATFORM][0], Interval.MIN_1, limit=10))
print('\n\n---------------------')
# client = utils.create_ws_client(platform_id=TEST_PLATFORM)
# client.on_data_item = lambda item: print(item) # print received parsed objects
# client.subscribe(endpoints=[Endpoint.TRADE, Endpoint.CANDLE], symbols=TEST_SYMBOLS[TEST_PLATFORM],
# interval=Interval.MIN_1)
#
# print('\n\nWebsocket data\n\n')
# # Sleep to display incoming websocket items from separate thread
# time.sleep(15)
|
{"/hyperquant/clients/tests/test_init.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py", "/hyperquant/clients/utils.py"], "/hyperquant/clients/tests/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/tests/test_api.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/__init__.py": ["/hyperquant/api.py"], "/hyperquant/clients/tests/test_bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/tests/test_utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/utils.py"], "/run_demo.py": ["/settings.py", "/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py"], "/hyperquant/clients/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py"], "/hyperquant/clients/binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"]}
|
13,217
|
assassinen/hyperquant
|
refs/heads/master
|
/settings.py
|
# Django settings for testing clients
CREDENTIALS_BY_PLATFORM = {
"BINANCE": ("rlvKnLAocc9R4HLU8q51elHte7WCqRwXAHuQ6p1ltKmMkQc2QCah8aSo9p3SDoOG",
"", # "MvO6MAerLLi715qKGBRoKOSNAJXnAJpxfMHOU5uEAv6Yw5QyVJnFFQmjGTX7ZKNr"
),
"BITFINEX": ("",
""),
"BITMEX": ("",
""),
# ("zt2U_wjwvPPbPE3T6nRTzVKr",
# "3p-tCyGeFJc6-_RL-Q_hnn9NPowI-zTkhOtcZZipHihzG1Qy"),
}
SECRET_KEY = "ddd"
|
{"/hyperquant/clients/tests/test_init.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py", "/hyperquant/clients/utils.py"], "/hyperquant/clients/tests/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/tests/test_api.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/__init__.py": ["/hyperquant/api.py"], "/hyperquant/clients/tests/test_bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/tests/test_utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/utils.py"], "/run_demo.py": ["/settings.py", "/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py"], "/hyperquant/clients/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py"], "/hyperquant/clients/binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"]}
|
13,218
|
assassinen/hyperquant
|
refs/heads/master
|
/hyperquant/clients/utils.py
|
from django.conf import settings
from hyperquant.api import Platform
from hyperquant.clients.binance import BinanceRESTClient, BinanceWSClient
from hyperquant.clients.bitfinex import BitfinexRESTClient, BitfinexWSClient
from hyperquant.clients.bitmex import BitMEXRESTClient, BitMEXWSClient
# temp
# if not settings.configured:
# # todo add default credentials
# print("settings.configure() for clients")
# settings.configure(base)
_rest_client_class_by_platform_id = {
Platform.BINANCE: BinanceRESTClient,
Platform.BITFINEX: BitfinexRESTClient,
Platform.BITMEX: BitMEXRESTClient,
}
_ws_client_class_by_platform_id = {
Platform.BINANCE: BinanceWSClient,
Platform.BITFINEX: BitfinexWSClient,
Platform.BITMEX: BitMEXWSClient,
}
_rest_client_by_platform_id = {}
_private_rest_client_by_platform_id = {}
_ws_client_by_platform_id = {}
_private_ws_client_by_platform_id = {}
def create_rest_client(platform_id, is_private=False, version=None):
return _create_client(platform_id, True, is_private, version)
def get_or_create_rest_client(platform_id, is_private=False):
return _get_or_create_client(platform_id, True, is_private)
def create_ws_client(platform_id, is_private=False, version=None):
return _create_client(platform_id, False, is_private, version)
def get_or_create_ws_client(platform_id, is_private=False):
return _get_or_create_client(platform_id, False, is_private)
def get_credentials_for(platform_id):
platform_name = Platform.get_platform_name_by_id(platform_id)
api_key, api_secret = settings.CREDENTIALS_BY_PLATFORM.get(platform_name)
return api_key, api_secret
def _create_client(platform_id, is_rest, is_private=False, version=None):
# Create
class_lookup = _rest_client_class_by_platform_id if is_rest else _ws_client_class_by_platform_id
client_class = class_lookup.get(platform_id)
if is_private:
api_key, api_secret = get_credentials_for(platform_id)
client = client_class(api_key, api_secret, version)
client.platform_id = platform_id # If not set in class
else:
client = client_class(version=version)
client.platform_id = platform_id # If not set in class
# For Binance's "historicalTrades" endpoint
if platform_id == Platform.BINANCE:
api_key, _ = get_credentials_for(platform_id)
client.set_credentials(api_key, None)
return client
def _get_or_create_client(platform_id, is_rest, is_private=False):
# Get
if is_rest:
lookup = _private_rest_client_by_platform_id if is_private else _rest_client_by_platform_id
else:
lookup = _private_ws_client_by_platform_id if is_private else _ws_client_by_platform_id
client = lookup.get(platform_id)
if client:
return client
# Create
lookup[platform_id] = client = _create_client(platform_id, is_rest, is_private)
return client
|
{"/hyperquant/clients/tests/test_init.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py", "/hyperquant/clients/utils.py"], "/hyperquant/clients/tests/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/tests/test_api.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/__init__.py": ["/hyperquant/api.py"], "/hyperquant/clients/tests/test_bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/tests/test_utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/utils.py"], "/run_demo.py": ["/settings.py", "/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py"], "/hyperquant/clients/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py"], "/hyperquant/clients/binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"]}
|
13,219
|
assassinen/hyperquant
|
refs/heads/master
|
/hyperquant/clients/binance.py
|
import hashlib
import hmac
from operator import itemgetter
from hyperquant.api import Platform, Sorting, Interval, Direction, OrderType
from hyperquant.clients import WSClient, Endpoint, Trade, Error, ErrorCode, \
ParamName, WSConverter, RESTConverter, PrivatePlatformRESTClient, MyTrade, Candle, Ticker, OrderBookItem, Order, \
OrderBook, Account, Balance
# REST
# TODO check getting trades history from_id=1
class BinanceRESTConverterV1(RESTConverter):
# Main params:
base_url = "https://api.binance.com/api/v{version}/"
# Settings:
# Converting info:
# For converting to platform
endpoint_lookup = {
Endpoint.PING: "ping",
Endpoint.SERVER_TIME: "time",
Endpoint.SYMBOLS: "exchangeInfo",
Endpoint.TRADE: "trades",
Endpoint.TRADE_HISTORY: "historicalTrades",
Endpoint.TRADE_MY: "myTrades", # Private
Endpoint.CANDLE: "klines",
Endpoint.TICKER: "ticker/price",
Endpoint.ORDER_BOOK: "depth",
# Private
Endpoint.ACCOUNT: "account",
Endpoint.ORDER: "order",
Endpoint.ORDER_CURRENT: "openOrders",
Endpoint.ORDER_MY: "allOrders",
}
param_name_lookup = {
ParamName.SYMBOL: "symbol",
ParamName.LIMIT: "limit",
ParamName.IS_USE_MAX_LIMIT: None,
# ParamName.SORTING: None,
ParamName.INTERVAL: "interval",
ParamName.DIRECTION: "side",
ParamName.ORDER_TYPE: "type",
ParamName.TIMESTAMP: "timestamp",
ParamName.FROM_ITEM: "fromId",
ParamName.TO_ITEM: None,
ParamName.FROM_TIME: "startTime",
ParamName.TO_TIME: "endTime",
ParamName.PRICE: "price",
ParamName.AMOUNT: "quantity",
# -ParamName.ASKS: "asks",
# ParamName.BIDS: "bids",
}
param_value_lookup = {
# Sorting.ASCENDING: None,
# Sorting.DESCENDING: None,
Sorting.DEFAULT_SORTING: Sorting.ASCENDING,
Interval.MIN_1: "1m",
Interval.MIN_3: "3m",
Interval.MIN_5: "5m",
Interval.MIN_15: "15m",
Interval.MIN_30: "30m",
Interval.HRS_1: "1h",
Interval.HRS_2: "2h",
Interval.HRS_4: "4h",
Interval.HRS_6: "6h",
Interval.HRS_8: "8h",
Interval.HRS_12: "12h",
Interval.DAY_1: "1d",
Interval.DAY_3: "3d",
Interval.WEEK_1: "1w",
Interval.MONTH_1: "1M",
# By properties:
ParamName.DIRECTION: {
Direction.SELL: "SELL",
Direction.BUY: "BUY",
},
ParamName.ORDER_TYPE: {
OrderType.LIMIT: "LIMIT",
OrderType.MARKET: "MARKET",
},
# ParamName.ORDER_STATUS: {
# OrderStatus.: "",
# },
}
max_limit_by_endpoint = {
Endpoint.TRADE: 1000,
Endpoint.TRADE_HISTORY: 1000,
Endpoint.ORDER_BOOK: 1000,
Endpoint.CANDLE: 1000,
}
# For parsing
param_lookup_by_class = {
# Error
Error: {
"code": "code",
"msg": "message",
},
# Data
Trade: {
"time": ParamName.TIMESTAMP,
"id": ParamName.ITEM_ID,
"price": ParamName.PRICE,
"qty": ParamName.AMOUNT,
# "isBuyerMaker": "",
# "isBestMatch": "",
},
MyTrade: {
"symbol": ParamName.SYMBOL,
"time": ParamName.TIMESTAMP,
"id": ParamName.ITEM_ID,
"price": ParamName.PRICE,
"qty": ParamName.AMOUNT,
"orderId": ParamName.ORDER_ID,
"commission": ParamName.FEE,
# "commissionAsset": ParamName.FEE_SYMBOL,
# "": ParamName.REBATE,
},
Candle: [
ParamName.TIMESTAMP,
ParamName.PRICE_OPEN,
ParamName.PRICE_HIGH,
ParamName.PRICE_LOW,
ParamName.PRICE_CLOSE,
None, # ParamName.AMOUNT, # only volume present
None,
None,
ParamName.TRADES_COUNT,
# ParamName.INTERVAL,
],
Ticker: {
"symbol": ParamName.SYMBOL,
"price": ParamName.PRICE,
},
Account: {
"updateTime": ParamName.TIMESTAMP,
"balances": ParamName.BALANCES,
},
Balance: {
"asset": ParamName.SYMBOL,
"free": ParamName.AMOUNT_AVAILABLE,
"locked": ParamName.AMOUNT_RESERVED,
},
Order: {
"symbol": ParamName.SYMBOL,
"transactTime": ParamName.TIMESTAMP,
"time": ParamName.TIMESTAMP, # check "time" or "updateTime"
"updateTime": ParamName.TIMESTAMP,
"orderId": ParamName.ITEM_ID,
"clientOrderId": ParamName.USER_ORDER_ID,
"type": ParamName.ORDER_TYPE,
"price": ParamName.PRICE,
"origQty": ParamName.AMOUNT_ORIGINAL,
"executedQty": ParamName.AMOUNT_EXECUTED,
"side": ParamName.DIRECTION,
"status": ParamName.ORDER_STATUS,
},
OrderBook: {
"lastUpdateId": ParamName.ITEM_ID,
"bids": ParamName.BIDS,
"asks": ParamName.ASKS,
},
OrderBookItem: [ParamName.PRICE, ParamName.AMOUNT],
}
error_code_by_platform_error_code = {
-2014: ErrorCode.UNAUTHORIZED,
-1121: ErrorCode.WRONG_SYMBOL,
-1100: ErrorCode.WRONG_PARAM,
}
error_code_by_http_status = {
429: ErrorCode.RATE_LIMIT,
418: ErrorCode.IP_BAN,
}
# For converting time
is_source_in_milliseconds = True
# timestamp_platform_names = [ParamName.TIMESTAMP]
def _process_param_value(self, name, value):
if name == ParamName.FROM_ITEM or name == ParamName.TO_ITEM:
if isinstance(value, Trade): # ItemObject):
return value.item_id
return super()._process_param_value(name, value)
def parse(self, endpoint, data):
if endpoint == Endpoint.SERVER_TIME and data:
timestamp_ms = data.get("serverTime")
return timestamp_ms / 1000 if not self.use_milliseconds and timestamp_ms else timestamp_ms
if endpoint == Endpoint.SYMBOLS and data and ParamName.SYMBOLS in data:
exchange_info = data[ParamName.SYMBOLS]
# (There are only 2 statuses: "TRADING" and "BREAK")
# symbols = [item[ParamName.SYMBOL] for item in exchange_info if item["status"] == "TRADING"]
symbols = [item[ParamName.SYMBOL] for item in exchange_info]
return symbols
result = super().parse(endpoint, data)
return result
# def preprocess_params(self, endpoint, params):
# if endpoint in self.secured_endpoints:
# params[ParamName.TIMESTAMP] = int(time.time() * 1000)
#
# return super().preprocess_params(endpoint, params)
def _generate_and_add_signature(self, platform_params, api_key, api_secret):
if not api_key or not api_secret:
self.logger.error("Empty api_key or api_secret. Cannot generate signature.")
return None
ordered_params_list = self._order_params(platform_params)
# print("ordered_platform_params:", ordered_params_list)
query_string = "&".join(["{}={}".format(d[0], d[1]) for d in ordered_params_list])
# print("query_string:", query_string)
m = hmac.new(api_secret.encode("utf-8"), query_string.encode("utf-8"), hashlib.sha256)
signature = m.hexdigest()
# Add
# platform_params["signature"] = signature # no need
# if ordered_params_list and ordered_params_list[-1][0] != "signature":
ordered_params_list.append(("signature", signature))
return ordered_params_list
def _order_params(self, platform_params):
# Convert params to sorted list with signature as last element.
params_list = [(key, value) for key, value in platform_params.items() if key != "signature"]
# Sort parameters by key
params_list.sort(key=itemgetter(0))
# Append signature to the end if present
if "signature" in platform_params:
params_list.append(("signature", platform_params["signature"]))
return params_list
class BinanceRESTClient(PrivatePlatformRESTClient):
# Settings:
platform_id = Platform.BINANCE
version = "1" # Default version
_converter_class_by_version = {
"1": BinanceRESTConverterV1,
"3": BinanceRESTConverterV1, # Only for some methods (same converter used)
}
# State:
ratelimit_error_in_row_count = 0
@property
def headers(self):
result = super().headers
result["X-MBX-APIKEY"] = self._api_key
result["Content-Type"] = "application/x-www-form-urlencoded"
return result
def _on_response(self, response, result):
# super()._on_response(response, result)
self.delay_before_next_request_sec = 0
if isinstance(result, Error):
if result.code == ErrorCode.RATE_LIMIT:
self.ratelimit_error_in_row_count += 1
self.delay_before_next_request_sec = 60 * 2 * self.ratelimit_error_in_row_count # some number - change
elif result.code == ErrorCode.IP_BAN:
self.ratelimit_error_in_row_count += 1
self.delay_before_next_request_sec = 60 * 5 * self.ratelimit_error_in_row_count # some number - change
else:
self.ratelimit_error_in_row_count = 0
else:
self.ratelimit_error_in_row_count = 0
def fetch_history(self, endpoint, symbol, limit=None, from_item=None, to_item=None, sorting=None,
is_use_max_limit=False, from_time=None, to_time=None,
version=None, **kwargs):
if from_item is None:
from_item = 0
return super().fetch_history(endpoint, symbol, limit, from_item, to_item, sorting, is_use_max_limit, from_time,
to_time, **kwargs)
def fetch_order_book(self, symbol=None, limit=None, is_use_max_limit=False, version=None, **kwargs):
LIMIT_VALUES = [5, 10, 20, 50, 100, 500, 1000]
if limit not in LIMIT_VALUES:
self.logger.error("Limit value %s not in %s", limit, LIMIT_VALUES)
return super().fetch_order_book(symbol, limit, is_use_max_limit, **kwargs)
def fetch_tickers(self, symbols=None, version=None, **kwargs):
items = super().fetch_tickers(symbols, version or "3", **kwargs)
# (Binance returns timestamp only for /api/v1/ticker/24hr which has weight of 40.
# /api/v3/ticker/price - has weight 2.)
timestamp = self.get_server_timestamp(version)
for item in items:
item.timestamp = timestamp
item.use_milliseconds = self.use_milliseconds
return items
def fetch_account_info(self, version=None, **kwargs):
return super().fetch_account_info(version or "3", **kwargs)
def create_order(self, symbol, order_type, direction, price=None, amount=None, is_test=False, version=None,
**kwargs):
if order_type == OrderType.LIMIT:
# (About values:
# https://www.reddit.com/r/BinanceExchange/comments/8odvs4/question_about_time_in_force_binance_api/)
kwargs["timeInForce"] = "GTC"
return super().create_order(symbol, order_type, direction, price, amount, is_test, version, **kwargs)
def cancel_order(self, order, symbol=None, version=None, **kwargs):
if hasattr(order, ParamName.SYMBOL) and order.symbol:
symbol = order.symbol
return super().cancel_order(order, symbol, version, **kwargs)
def check_order(self, order, symbol=None, version=None, **kwargs):
if hasattr(order, ParamName.SYMBOL) and order.symbol:
symbol = order.symbol
return super().check_order(order, symbol, version, **kwargs)
# def fetch_orders(self, symbol=None, limit=None, from_item=None, is_open=False, version=None, **kwargs):
# return super().fetch_orders(symbol, limit, from_item, is_open, version, **kwargs)
def _send(self, method, endpoint, params=None, version=None, **kwargs):
if endpoint in self.converter.secured_endpoints:
server_timestamp = self.get_server_timestamp()
params[ParamName.TIMESTAMP] = server_timestamp if self.use_milliseconds else int(server_timestamp * 1000)
return super()._send(method, endpoint, params, version, **kwargs)
# WebSocket
class BinanceWSConverterV1(WSConverter):
# Main params:
base_url = "wss://stream.binance.com:9443/"
IS_SUBSCRIPTION_COMMAND_SUPPORTED = False
# supported_endpoints = [Endpoint.TRADE]
# symbol_endpoints = [Endpoint.TRADE]
# supported_symbols = None
# Settings:
# Converting info:
# For converting to platform
endpoint_lookup = {
Endpoint.TRADE: "{symbol}@trade",
Endpoint.CANDLE: "{symbol}@kline_{interval}",
Endpoint.TICKER: "{symbol}@miniTicker",
Endpoint.TICKER_ALL: "!miniTicker@arr",
Endpoint.ORDER_BOOK: "{symbol}@depth{level}",
Endpoint.ORDER_BOOK_DIFF: "{symbol}@depth",
}
# For parsing
param_lookup_by_class = {
# Error
Error: {
# "code": "code",
# "msg": "message",
},
# Data
Trade: {
"s": ParamName.SYMBOL,
"T": ParamName.TIMESTAMP,
"t": ParamName.ITEM_ID,
"p": ParamName.PRICE,
"q": ParamName.AMOUNT,
# "m": "",
},
Candle: {
"s": ParamName.SYMBOL,
"t": ParamName.TIMESTAMP,
"i": ParamName.INTERVAL,
"o": ParamName.PRICE_OPEN,
"c": ParamName.PRICE_CLOSE,
"h": ParamName.PRICE_HIGH,
"l": ParamName.PRICE_LOW,
"": ParamName.AMOUNT, # only volume present
"n": ParamName.TRADES_COUNT,
},
Ticker: {
"s": ParamName.SYMBOL,
"E": ParamName.TIMESTAMP,
"c": ParamName.PRICE, # todo check to know for sure
},
OrderBook: {
# Partial Book Depth Streams
"lastUpdateId": ParamName.ITEM_ID,
"asks": ParamName.ASKS,
"bids": ParamName.BIDS,
# Diff. Depth Stream
"s": ParamName.SYMBOL,
"E": ParamName.TIMESTAMP,
"u": ParamName.ITEM_ID,
"b": ParamName.BIDS,
"a": ParamName.ASKS,
},
OrderBookItem: [ParamName.PRICE, ParamName.AMOUNT],
}
event_type_param = "e"
endpoint_by_event_type = {
"trade": Endpoint.TRADE,
"kline": Endpoint.CANDLE,
"24hrMiniTicker": Endpoint.TICKER,
"24hrTicker": Endpoint.TICKER,
"depthUpdate": Endpoint.ORDER_BOOK,
# "depthUpdate": Endpoint.ORDER_BOOK_DIFF,
}
# https://github.com/binance-exchange/binance-official-api-docs/blob/master/errors.md
error_code_by_platform_error_code = {
# -2014: ErrorCode.UNAUTHORIZED,
# -1121: ErrorCode.WRONG_SYMBOL,
# -1100: ErrorCode.WRONG_PARAM,
}
error_code_by_http_status = {}
# For converting time
is_source_in_milliseconds = True
def _generate_subscription(self, endpoint, symbol=None, **params):
return super()._generate_subscription(endpoint, symbol.lower() if symbol else symbol, **params)
def parse(self, endpoint, data):
if "data" in data:
# stream = data["stream"] # no need
data = data["data"]
return super().parse(endpoint, data)
def _parse_item(self, endpoint, item_data):
if endpoint == Endpoint.CANDLE and "k" in item_data:
item_data = item_data["k"]
return super()._parse_item(endpoint, item_data)
class BinanceWSClient(WSClient):
platform_id = Platform.BINANCE
version = "1" # Default version
_converter_class_by_version = {
"1": BinanceWSConverterV1,
}
@property
def url(self):
# Generate subscriptions
if not self.current_subscriptions:
self.logger.warning("Making URL while current_subscriptions are empty. "
"There is no sense to connect without subscriptions.")
subscriptions = ""
# # There is no sense to connect without subscriptions
# return None
elif len(self.current_subscriptions) > 1:
subscriptions = "stream?streams=" + "/".join(self.current_subscriptions)
else:
subscriptions = "ws/" + "".join(self.current_subscriptions)
self.is_subscribed_with_url = True
return super().url + subscriptions
def subscribe(self, endpoints=None, symbols=None, **params):
self._check_params(endpoints, symbols, **params)
super().subscribe(endpoints, symbols, **params)
def unsubscribe(self, endpoints=None, symbols=None, **params):
self._check_params(endpoints, symbols, **params)
super().unsubscribe(endpoints, symbols, **params)
def _check_params(self, endpoints=None, symbols=None, **params):
LEVELS_AVAILABLE = [5, 10, 20]
if endpoints and Endpoint.ORDER_BOOK in endpoints and ParamName.LEVEL in params and \
params.get(ParamName.LEVEL) not in LEVELS_AVAILABLE:
self.logger.error("For %s endpoint %s param must be of values: %s, but set: %s",
Endpoint.ORDER_BOOK, ParamName.LEVEL, LEVELS_AVAILABLE,
params.get(ParamName.LEVEL))
|
{"/hyperquant/clients/tests/test_init.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py", "/hyperquant/clients/utils.py"], "/hyperquant/clients/tests/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/tests/test_api.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/__init__.py": ["/hyperquant/api.py"], "/hyperquant/clients/tests/test_bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/tests/test_utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/utils.py"], "/run_demo.py": ["/settings.py", "/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py"], "/hyperquant/clients/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py"], "/hyperquant/clients/binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"]}
|
13,220
|
assassinen/hyperquant
|
refs/heads/master
|
/hyperquant/clients/bitfinex.py
|
import hashlib
import hmac
import time
from hyperquant.api import Platform, Sorting, Direction
from hyperquant.clients import Endpoint, WSClient, Trade, ParamName, Error, \
ErrorCode, Channel, \
Info, WSConverter, RESTConverter, PlatformRESTClient, PrivatePlatformRESTClient
# https://docs.bitfinex.com/v1/docs
# https://docs.bitfinex.com/v2/docs
# REST
class BitfinexRESTConverterV1(RESTConverter):
# Main params:
base_url = "https://api.bitfinex.com/v{version}/"
IS_SORTING_ENABLED = False
# Settings:
# Converting info:
# For converting to platform
endpoint_lookup = {
Endpoint.TRADE: "trades/{symbol}",
Endpoint.TRADE_HISTORY: "trades/{symbol}", # same, not implemented for this version
}
param_name_lookup = {
ParamName.LIMIT: "limit_trades",
ParamName.IS_USE_MAX_LIMIT: None,
ParamName.SORTING: None, # not supported
ParamName.FROM_ITEM: "timestamp",
ParamName.TO_ITEM: "timestamp", # ?
ParamName.FROM_TIME: "timestamp",
ParamName.TO_TIME: None, # ?
}
param_value_lookup = {
# Sorting.ASCENDING: None,
# Sorting.DESCENDING: None,
Sorting.DEFAULT_SORTING: Sorting.DESCENDING,
}
max_limit_by_endpoint = {
Endpoint.TRADE: 1000,
Endpoint.TRADE_HISTORY: 1000, # same, not implemented for this version
}
# For parsing
param_lookup_by_class = {
Error: {
"message": "code",
# "error": "code",
# "message": "message",
},
Trade: {
"tid": ParamName.ITEM_ID,
"timestamp": ParamName.TIMESTAMP,
"price": ParamName.PRICE,
"amount": ParamName.AMOUNT,
"type": ParamName.DIRECTION,
},
}
error_code_by_platform_error_code = {
# "": ErrorCode.UNAUTHORIZED,
"Unknown symbol": ErrorCode.WRONG_SYMBOL,
# "ERR_RATE_LIMIT": ErrorCode.RATE_LIMIT,
}
error_code_by_http_status = {
429: ErrorCode.RATE_LIMIT,
}
# For converting time
# is_source_in_milliseconds = True
timestamp_platform_names = [ParamName.TIMESTAMP]
def prepare_params(self, endpoint=None, params=None):
resources, platform_params = super().prepare_params(endpoint, params)
# (SYMBOL was used in URL path) (not necessary)
if platform_params and ParamName.SYMBOL in platform_params:
del platform_params[ParamName.SYMBOL]
return resources, platform_params
def parse(self, endpoint, data):
if data and endpoint == Endpoint.SYMBOLS:
return [item.upper() for item in data]
return super().parse(endpoint, data)
def _parse_item(self, endpoint, item_data):
result = super()._parse_item(endpoint, item_data)
# Convert Trade.direction
if result and isinstance(result, Trade) and result.direction:
# (Can be of "sell"|"buy|"")
result.direction = Direction.SELL if result.direction == "sell" else \
(Direction.BUY if result.direction == "buy" else None)
return result
class BitfinexRESTConverterV2(RESTConverter):
# Main params:
base_url = "https://api.bitfinex.com/v{version}/"
IS_SORTING_ENABLED = True
# Settings:
# Converting info:
# For converting to platform
endpoint_lookup = {
Endpoint.TRADE: "trades/t{symbol}/hist", # same, not implemented for this version
Endpoint.TRADE_HISTORY: "trades/t{symbol}/hist",
}
param_name_lookup = {
ParamName.LIMIT: "limit",
ParamName.IS_USE_MAX_LIMIT: None,
ParamName.SORTING: "sort",
ParamName.FROM_ITEM: "start",
ParamName.TO_ITEM: "end",
ParamName.FROM_TIME: "start",
ParamName.TO_TIME: "end",
}
param_value_lookup = {
Sorting.ASCENDING: 1,
Sorting.DESCENDING: 0,
Sorting.DEFAULT_SORTING: Sorting.DESCENDING,
}
max_limit_by_endpoint = {
Endpoint.TRADE: 1000, # same, not implemented for this version
Endpoint.TRADE_HISTORY: 1000,
}
# For parsing
param_lookup_by_class = {
# ["error",10020,"limit: invalid"]
Error: ["", "code", "message"],
# on trading pairs (ex. tBTCUSD) [ID, MTS, AMOUNT, PRICE]
# [305430435,1539757383787,-0.086154,6760.7]
# (on funding currencies (ex. fUSD) [ID, MTS, AMOUNT, RATE, PERIOD]) - not used now
Trade: [ParamName.ITEM_ID, ParamName.TIMESTAMP, ParamName.AMOUNT, ParamName.PRICE],
}
error_code_by_platform_error_code = {
# "": ErrorCode.UNAUTHORIZED,
10020: ErrorCode.WRONG_LIMIT,
11010: ErrorCode.RATE_LIMIT,
}
error_code_by_http_status = {}
# For converting time
is_source_in_milliseconds = True
timestamp_platform_names = ["start", "end"]
def prepare_params(self, endpoint=None, params=None):
# # Symbol needs "t" prefix for trading pair
# if ParamName.SYMBOL in params:
# params[ParamName.SYMBOL] = "t" + str(params[ParamName.SYMBOL])
resources, platform_params = super().prepare_params(endpoint, params)
# (SYMBOL was used in URL path) (not necessary)
if platform_params and ParamName.SYMBOL in platform_params:
del platform_params[ParamName.SYMBOL]
return resources, platform_params
def _process_param_value(self, name, value):
# # Symbol needs "t" prefix for trading pair
# if name == ParamName.SYMBOL and value:
# return "t" + value
# elif
if name == ParamName.FROM_ITEM or name == ParamName.TO_ITEM:
if isinstance(value, Trade):
return value.timestamp
return super()._process_param_value(name, value)
def _parse_item(self, endpoint, item_data):
result = super()._parse_item(endpoint, item_data)
if result and isinstance(result, Trade):
# Determine direction
result.direction = Direction.BUY if result.amount > 0 else Direction.SELL
# Stringify and check sign
result.price = str(result.price)
result.amount = str(result.amount) if result.amount > 0 else str(-result.amount)
return result
def parse_error(self, error_data=None, response=None):
result = super().parse_error(error_data, response)
if error_data and isinstance(error_data, dict) and "error" in error_data:
if error_data["error"] == "ERR_RATE_LIMIT":
result.error_code = ErrorCode.RATE_LIMIT
result.message = ErrorCode.get_message_by_code(result.code) + result.message
return result
class BitfinexRESTClient(PrivatePlatformRESTClient):
platform_id = Platform.BITFINEX
version = "2" # Default version
_converter_class_by_version = {
"1": BitfinexRESTConverterV1,
"2": BitfinexRESTConverterV2,
}
def get_symbols(self, version=None):
self.logger.info("Note: Bitfinex supports get_symbols only in v1.")
return super().get_symbols(version="1")
# # after_timestamp param can be added for v1, and after_timestamp, before_timestamp for v2
# def fetch_trades(self, symbol, limit=None, **kwargs):
# return super().fetch_trades(symbol, limit, **kwargs)
# v1: Same as fetch_trades(), but result can be only reduced, but not extended
def fetch_trades_history(self, symbol, limit=None, from_item=None,
sorting=None, from_time=None, to_time=None, **kwargs):
if from_item and self.version == "1":
# todo check
self.logger.warning("Bitfinex v1 API has no trades-history functionality.")
return None
# return self.fetch_trades(symbol, limit, **kwargs)
return super().fetch_trades_history(symbol, limit, from_item, sorting=sorting,
from_time=from_time, to_time=to_time, **kwargs)
def _on_response(self, response, result):
# super()._on_response(response)
if not response.ok and "Retry-After" in response.headers:
self.delay_before_next_request_sec = int(response.headers["Retry-After"])
elif isinstance(result, Error):
if result.code == ErrorCode.RATE_LIMIT:
# Bitfinex API access is rate limited. The rate limit applies if an
# IP address exceeds a certain number of requests per minute. The current
# limit is between 10 and 45 to a specific REST API endpoint (ie. /ticker).
# In case a client reaches the limit, we block the requesting IP address
# for 10-60 seconds on that endpoint. The API will return the JSON response
# {"error": "ERR_RATE_LIMIT"}. These DDoS defenses may change over time to
# further improve reliability.
self.delay_before_next_request_sec = 60
else:
self.delay_before_next_request_sec = 10
# WebSocket
class BitfinexWSConverterV2(WSConverter):
# Main params:
base_url = "wss://api.bitfinex.com/ws/{version}/"
IS_SUBSCRIPTION_COMMAND_SUPPORTED = True
# supported_endpoints = [Endpoint.TRADE]
# symbol_endpoints = [Endpoint.TRADE]
# supported_symbols = None
# Settings:
# Converting info:
# For converting to platform
endpoint_lookup = {
Endpoint.TRADE: "trades",
}
# For parsing
item_class_by_endpoint = dict(**WSConverter.item_class_by_endpoint, **{
# Item class by event type
"error": Error,
"info": Info,
"subscribed": Channel,
})
param_lookup_by_class = {
Error: {
"code": "code",
"msg": "message",
},
Info: {
"code": "code",
"msg": "message",
},
Channel: {
"chanId": "channel_id",
"channel": "channel",
"pair": ParamName.SYMBOL,
},
#
Trade: [ParamName.ITEM_ID, ParamName.TIMESTAMP, ParamName.AMOUNT, ParamName.PRICE],
}
# https://docs.bitfinex.com/v2/docs/abbreviations-glossary
# 10300 : Subscription failed (generic)
# 10301 : Already subscribed
# 10302 : Unknown channel
# 10400 : Unsubscription failed (generic)
# 10401 : Not subscribed
# errors = {10000: 'Unknown event',
# 10001: 'Generic error',
# 10008: 'Concurrency error',
# 10020: 'Request parameters error',
# 10050: 'Configuration setup failed',
# 10100: 'Failed authentication',
# 10111: 'Error in authentication request payload',
# 10112: 'Error in authentication request signature',
# 10113: 'Error in authentication request encryption',
# 10114: 'Error in authentication request nonce',
# 10200: 'Error in un-authentication request',
# 10300: 'Subscription Failed (generic)',
# 10301: 'Already Subscribed',
# 10302: 'Unknown channel',
# 10400: 'Subscription Failed (generic)',
# 10401: 'Not subscribed',
# 11000: 'Not ready, try again later',
# 20000: 'User is invalid!',
# 20051: 'Websocket server stopping',
# 20060: 'Websocket server resyncing',
# 20061: 'Websocket server resync complete'
# }
error_code_by_platform_error_code = {
# 10000: ErrorCode.WRONG_EVENT,
10001: ErrorCode.WRONG_SYMBOL,
# 10305: ErrorCode.CHANNEL_LIMIT,
}
event_type_param = "event"
# For converting time
is_source_in_milliseconds = True
def __init__(self, platform_id=None, version=None):
self.channel_by_id = {}
super().__init__(platform_id, version)
def _generate_subscription(self, endpoint, symbol=None, **params):
channel = super()._generate_subscription(endpoint, symbol, **params)
return (channel, symbol)
def parse(self, endpoint, data):
# if data:
# endpoint = data.get(self.event_type_param)
# if "data" in data:
# data = data["data"]
if isinstance(data, list):
# [284792,[[306971149,1540470353199,-0.76744631,0.031213],...] (1)
# todo add tests
# or [102165,"te",[306995378,1540485961266,-0.216139,0.031165]]
# or [102165,"tu",[306995378,1540485961266,-0.216139,0.031165]] (2)
channel_id = data[0]
channel = self.channel_by_id.get(channel_id)
if channel:
# Get endpoint by channel
endpoint = None
for k, v in self.endpoint_lookup.items():
if v == channel.channel:
endpoint = k
# Parse
if data[1] == "tu":
# Skip "tu" as an item have been already added as "te"
return None
# if data[1] == "te":
# # Skip "te" as an item has no id yet, waiting for "tu" (actually there is an id already)
# return None
# (data[1] - for v1, data[1] or [data[2]] - for v2, see above (1) and (2) examples)
real_data = data[1] if isinstance(data[1], list) else [data[2]]
result = super().parse(endpoint, real_data)
# Set symbol
for item in result:
if hasattr(item, ParamName.SYMBOL):
item.symbol = channel.symbol
return result
return super().parse(endpoint, data)
def _parse_item(self, endpoint, item_data):
result = super()._parse_item(endpoint, item_data)
if isinstance(result, Channel):
self.channel_by_id[result.channel_id] = result
elif result and isinstance(result, Trade):
if result.symbol and result.symbol.begins_with("."):
return None
if not result.item_id:
result.item_id = "%s_%s_%s" % (result.timestamp, result.price, result.amount)
# Determine direction
result.direction = Direction.BUY if result.amount > 0 else Direction.SELL
# Stringify and check sign
result.price = str(result.price)
result.amount = str(result.amount) if result.amount > 0 else str(-result.amount)
return result
# (not necessary)
class BitfinexWSConverterV1(BitfinexWSConverterV2):
# Main params:
base_url = "wss://api.bitfinex.com/ws/{version}/"
# # Settings:
#
# # Converting info:
# # For converting to platform
# endpoint_lookup = {
# Endpoint.TRADE: "trades",
# }
# For parsing
param_lookup_by_class = {
Error: {
"code": "code",
"msg": "message",
},
Info: {
"code": "code",
"msg": "message",
},
Channel: {
"channel": "channel",
"chanId": "channel_id",
"pair": ParamName.SYMBOL,
},
# [ 5, "te", "1234-BTCUSD", 1443659698, 236.42, 0.49064538 ]
# Trade: ["", "", ParamName.ITEM_ID, ParamName.TIMESTAMP, ParamName.PRICE, ParamName.AMOUNT],
Trade: [ParamName.ITEM_ID, ParamName.TIMESTAMP, ParamName.PRICE, ParamName.AMOUNT],
}
# # 10300 : Subscription failed (generic)
# # 10301 : Already subscribed
# # 10302 : Unknown channel
# # 10400 : Unsubscription failed (generic)
# # 10401 : Not subscribed
# error_code_by_platform_error_code = {
# # 10000: ErrorCode.WRONG_EVENT,
# 10001: ErrorCode.WRONG_SYMBOL,
# }
#
# # For converting time
# # is_source_in_milliseconds = True
# def parse_item(self, endpoint, item_data):
# result = super().parse_item(endpoint, item_data)
#
# # Convert Channel.symbol "tXXXYYY" -> "XXXYYY"
# if result and isinstance(result, Channel) and result.symbol:
# if result.symbol[0] == "t":
# result.symbol = result.symbol[1:]
#
# return result
class BitfinexWSClient(WSClient):
# TODO consider reconnection and resubscription
# TODO consider reconnect on connection, pong and other timeouts
# Settings:
platform_id = Platform.BITFINEX
version = "2" # Default version
_converter_class_by_version = {
"1": BitfinexWSConverterV1,
"2": BitfinexWSConverterV2,
}
# State:
def _send_subscribe(self, subscriptions):
for channel, symbol in subscriptions:
trading_pair_symbol = "t" + symbol
event_data = {
"event": "subscribe",
"channel": channel,
"symbol": trading_pair_symbol}
self._send(event_data)
def _parse(self, endpoint, data):
if isinstance(data, list) and len(data) > 1 and data[1] == "hb":
# Heartbeat. skip for now...
return None
return super()._parse(endpoint, data)
# Закомментированные методы можно свободно удалять, если проще переносить код из другой библиотеки заново
# def on_item_received(self, item):
# # if isinstance(item, Channel):
# # self.channel_by_id[item.channel_id] = item
# # return
# #
# super().on_item_received(item)
#
# # # Handle data
# # if isinstance(data, dict):
# # # This is a system message
# # self._system_handler(data, received_at)
# # else:
# # # This is a list of data
# # if data[1] == 'hb':
# # self._heartbeat_handler()
# # else:
# # self._data_handler(data, received_at)
# def _system_handler(self, data, ts):
# """Distributes system messages to the appropriate handler.
# System messages include everything that arrives as a dict,
# or a list containing a heartbeat.
# :param data:
# :param ts:
# :return:
# """
# self.log.debug("_system_handler(): Received a system message: %s", data)
# # Unpack the data
# event = data.pop('event')
# if event == 'pong':
# self.log.debug("_system_handler(): Distributing %s to _pong_handler..",
# data)
# self._pong_handler()
# elif event == 'info':
# self.log.debug("_system_handler(): Distributing %s to _info_handler..",
# data)
# self._info_handler(data)
# elif event == 'error':
# self.log.debug("_system_handler(): Distributing %s to _error_handler..",
# data)
# self._error_handler(data)
# elif event in ('subscribed', 'unsubscribed', 'conf', 'auth', 'unauth'):
# self.log.debug("_system_handler(): Distributing %s to "
# "_response_handler..", data)
# self._response_handler(event, data, ts)
# else:
# self.log.error("Unhandled event: %s, data: %s", event, data)
# if event_name in ('subscribed', 'unsubscribed', 'conf', 'auth', 'unauth'):
# try:
# self._response_handlers[event_name](event_name, data, ts)
# except KeyError:
# self.log.error("Dtype '%s' does not have a response "
# "handler! (%s)", event_name, message)
# elif event_name == 'data':
# try:
# channel_id = data[0]
# if channel_id != 0:
# # Get channel type associated with this data to the
# # associated data type (from 'data' to
# # 'book', 'ticker' or similar
# channel_type, *_ = self.channel_directory[channel_id]
#
# # Run the associated data handler for this channel type.
# self._data_handlers[channel_type](channel_type, data, ts)
# # Update time stamps.
# self.update_timestamps(channel_id, ts)
# else:
# # This is data from auth channel, call handler
# self._handle_account(data=data, ts=ts)
# except KeyError:
# self.log.error("Channel ID does not have a data handler! %s",
# message)
# else:
# self.log.error("Unknown event_name on queue! %s", message)
# continue
# self._response_handlers = {'unsubscribed': self._handle_unsubscribed,
# 'subscribed': self._handle_subscribed,
# 'conf': self._handle_conf,
# 'auth': self._handle_auth,
# 'unauth': self._handle_auth}
# self._data_handlers = {'ticker': self._handle_ticker,
# 'book': self._handle_book,
# 'raw_book': self._handle_raw_book,
# 'candles': self._handle_candles,
# 'trades': self._handle_trades}
# https://github.com/Crypto-toolbox/btfxwss/blob/master/btfxwss/queue_processor.py
# def _handle_subscribed(self, dtype, data, ts,):
# """Handles responses to subscribe() commands.
# Registers a channel id with the client and assigns a data handler to it.
# :param dtype:
# :param data:
# :param ts:
# :return:
# """
# self.log.debug("_handle_subscribed: %s - %s - %s", dtype, data, ts)
# channel_name = data.pop('channel')
# channel_id = data.pop('chanId')
# config = data
#
# if 'pair' in config:
# symbol = config['pair']
# if symbol.startswith('t'):
# symbol = symbol[1:]
# elif 'symbol' in config:
# symbol = config['symbol']
# if symbol.startswith('t'):
# symbol = symbol[1:]
# elif 'key' in config:
# symbol = config['key'].split(':')[2][1:] #layout type:interval:tPair
# else:
# symbol = None
#
# if 'prec' in config and config['prec'].startswith('R'):
# channel_name = 'raw_' + channel_name
#
# self.channel_handlers[channel_id] = self._data_handlers[channel_name]
#
# # Create a channel_name, symbol tuple to identify channels of same type
# if 'key' in config:
# identifier = (channel_name, symbol, config['key'].split(':')[1])
# else:
# identifier = (channel_name, symbol)
# self.channel_handlers[channel_id] = identifier
# self.channel_directory[identifier] = channel_id
# self.channel_directory[channel_id] = identifier
# self.log.info("Subscription succesful for channel %s", identifier)
#
# def _handle_unsubscribed(self, dtype, data, ts):
# """Handles responses to unsubscribe() commands.
# Removes a channel id from the client.
# :param dtype:
# :param data:
# :param ts:
# :return:
# """
# self.log.debug("_handle_unsubscribed: %s - %s - %s", dtype, data, ts)
# channel_id = data.pop('chanId')
#
# # Unregister the channel from all internal attributes
# chan_identifier = self.channel_directory.pop(channel_id)
# self.channel_directory.pop(chan_identifier)
# self.channel_handlers.pop(channel_id)
# self.last_update.pop(channel_id)
# self.log.info("Successfully unsubscribed from %s", chan_identifier)
#
# def _handle_auth(self, dtype, data, ts):
# """Handles authentication responses.
# :param dtype:
# :param data:
# :param ts:
# :return:
# """
# # Contains keys status, chanId, userId, caps
# if dtype == 'unauth':
# raise NotImplementedError
# channel_id = data.pop('chanId')
# user_id = data.pop('userId')
#
# identifier = ('auth', user_id)
# self.channel_handlers[identifier] = channel_id
# self.channel_directory[identifier] = channel_id
# self.channel_directory[channel_id] = identifier
# def _handle_trades(self, dtype, data, ts):
# """Files trades in self._trades[chan_id].
# :param dtype:
# :param data:
# :param ts:
# :return:
# """
# self.log.debug("_handle_trades: %s - %s - %s", dtype, data, ts)
# channel_id, *data = data
# channel_identifier = self.channel_directory[channel_id]
# entry = (data, ts)
# self.trades[channel_identifier].put(entry)
def _send_auth(self):
# Generate nonce
auth_nonce = str(int(time.time() * 10000000))
# Generate signature
auth_payload = "AUTH" + auth_nonce
auth_sig = hmac.new(self._api_secret.encode(), auth_payload.encode(),
hashlib.sha384).hexdigest()
payload = {"event": "auth", "apiKey": self._api_key, "authSig": auth_sig,
"authPayload": auth_payload, "authNonce": auth_nonce}
self._send(payload)
# # Auth v1:
# import hmac
# import hashlib
# import time
#
# nonce = int(time.time() * 1000000)
# auth_payload = "AUTH" + str(nonce)
# signature = hmac.new(
# API_SECRET.encode(),
# msg = auth_payload.encode(),
# digestmod = hashlib.sha384
# ).hexdigest()
#
# payload = {
# "apiKey": API_KEY,
# "event": "auth",
# "authPayload": auth_payload,
# "authNonce": nonce,
# "authSig": signature
# }
#
# ws.send(json.dumps(payload))
# https://github.com/bitfinexcom/bitfinex-api-node
# How do te and tu messages differ?
# A te packet is sent first to the client immediately after a trade has been
# matched & executed, followed by a tu message once it has completed processing.
# During times of high load, the tu message may be noticably delayed, and as
# such only the te message should be used for a realtime feed.
|
{"/hyperquant/clients/tests/test_init.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py", "/hyperquant/clients/utils.py"], "/hyperquant/clients/tests/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/tests/test_api.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/tests/test_bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/__init__.py": ["/hyperquant/api.py"], "/hyperquant/clients/tests/test_bitmex.py": ["/hyperquant/api.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/tests/test_init.py"], "/hyperquant/clients/tests/test_utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py", "/hyperquant/clients/utils.py"], "/run_demo.py": ["/settings.py", "/hyperquant/api.py", "/hyperquant/clients/__init__.py", "/hyperquant/clients/tests/utils.py"], "/hyperquant/clients/utils.py": ["/hyperquant/api.py", "/hyperquant/clients/binance.py", "/hyperquant/clients/bitfinex.py", "/hyperquant/clients/bitmex.py"], "/hyperquant/clients/binance.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"], "/hyperquant/clients/bitfinex.py": ["/hyperquant/api.py", "/hyperquant/clients/__init__.py"]}
|
13,222
|
Derrick-Nyongesa/NewsBlitz
|
refs/heads/main
|
/tests/test_articles.py
|
import unittest
from app.models import Articles
class ArticlesTest(unittest.TestCase):
"""
Test class to test the nehaviour of the Articles class
"""
def setUp(self):
"""
Set up method that will run before every test
"""
self.new_article = Articles("Politico","By Benjamin Din", "2024 GOP contenders collect cash", "Republicans who led efforts to overturn the election results in January did especially well, according to the latest quarterly FEC filings.", "https://www.politico.com/news/2021/04/15/2024-gop-cash-fec-482240", "https://static.politico.com/90/a6/2eff74ff4d69b7aee677b55ae6e2/gettyimages-1230713929.jpg", "2021-04-16T02:10:04Z")
def test_instance(self):
self.assertTrue(isinstance(self.new_article, Articles))
|
{"/app/main/views.py": ["/app/requests.py"]}
|
13,223
|
Derrick-Nyongesa/NewsBlitz
|
refs/heads/main
|
/app/requests.py
|
import urllib.request,json
from .models import Sources, Articles
api_key = None
base_url = None
articles_base_url = None
search_url = None
def configure_request(app):
global api_key, base_url, articles_base_url, search_url
api_key = app.config['NEWS_API_KEY']
base_url = app.config['NEWS_API_BASE_URL']
articles_base_url = app.config['ARTICLES_API_BASE_URL']
search_url = app.config['SEARCH_API_BASE_URL']
def get_sources(category):
"""
function that gets response from the api call
"""
sources_url = base_url.format(category,api_key)
with urllib.request.urlopen(sources_url) as url:
sources_data = url.read()
sources_response = json.loads(sources_data)
sources_results = None
if sources_response['sources']:
sources_results_list = sources_response['sources']
sources_results = process_results(sources_results_list)
return sources_results
def process_results(sources_list):
"""
Function that processes the movie result and transform them to a list of Objects
"""
sources_results = []
for one_source in sources_list:
id = one_source.get("id")
name = one_source.get("name")
description = one_source.get("description")
url = one_source.get("url")
category = one_source.get("category")
language = one_source.get("language")
country = one_source.get("country")
source_object = Sources(id,name,description,url,category,country)
sources_results.append(source_object)
return sources_results
def get_articles(source):
"""
Function that gets the json response to our url request
"""
articles_url = articles_base_url.format(source, api_key)
with urllib.request.urlopen(articles_url) as url:
articles_data = url.read()
articles_response = json.loads(articles_data)
articles_results = None
if articles_response['articles']:
articles_list = articles_response['articles']
articles_results = process_articles(articles_list)
return articles_results
def process_articles(article_list):
articles_results = []
for article_item in article_list:
source = article_item.get("source")
author = article_item.get('author')
title = article_item.get('title')
description = article_item.get('description')
url = article_item.get('url')
urlToImage = article_item.get('urlToImage')
publishedAt = article_item.get('publishedAt')
article_object = Articles(source,author,title,description,url,urlToImage,publishedAt)
articles_results.append(article_object)
return articles_results
def search_article(article_name):
search_article_url = search_url.format(article_name,api_key)
with urllib.request.urlopen(search_article_url) as url:
search_data = url.read()
search_response = json.loads(search_data)
search_results = None
if search_response['articles']:
search_list = search_response['articles']
search_results = process_articles(search_list)
return search_results
|
{"/app/main/views.py": ["/app/requests.py"]}
|
13,224
|
Derrick-Nyongesa/NewsBlitz
|
refs/heads/main
|
/app/main/views.py
|
from flask import render_template,request,redirect,url_for
from . import main
from ..requests import get_sources, get_articles, search_article
from ..models import Sources, Articles
@main.route('/')
def index():
"""
View root page function that returns the index page and its data
"""
general_news = get_sources('general')
business_news = get_sources("business")
entertainment_news = get_sources("entertainment")
sports_news = get_sources("sports")
title = 'Home - Welcome to NewsBlitz'
return render_template('index.html',title=title,general=general_news,business=business_news,entertainment=entertainment_news,sports=sports_news )
@main.route('/articles/<id>')
def article(id):
"""
View page thar returns news articles from a source
"""
all_articles = get_articles(id)
print(all_articles)
source = id
search_article = request.args.get('article_query')
if search_article:
return redirect(url_for('search', article_name = search_article))
else:
return render_template('articles.html', articles = all_articles, source = source)
@main.route('/search/<article_name>')
def search(article_name):
"""
Function to display search results
"""
article_name_list = article_name.split(" ")
article_name_format = "+".join(article_name_list)
searched_articles = search_article(article_name_format)
return render_template('search.html', articles = searched_articles)
|
{"/app/main/views.py": ["/app/requests.py"]}
|
13,229
|
andrewfurman/tarot
|
refs/heads/master
|
/predictions/admin.py
|
from predictions.models import Prediction, Vote
from django.contrib import admin
class PredictionAdmin(admin.ModelAdmin):
list_display = ('prediction_text', 'user', 'date_predicted', 'true_date')
class VoteAdmin(admin.ModelAdmin):
list_display = ('prediction', 'user')
admin.site.register(Prediction, PredictionAdmin)
admin.site.register(Vote, VoteAdmin)
|
{"/predictions/admin.py": ["/predictions/models.py"], "/predictions/views.py": ["/predictions/models.py"]}
|
13,230
|
andrewfurman/tarot
|
refs/heads/master
|
/predictions/models.py
|
from django.db import models
from django.contrib.auth.models import User
from django.forms import ModelForm
# Create your models here.
class Prediction(models.Model):
prediction_text = models.CharField(max_length=200)
user = models.ForeignKey(User)
date_predicted = models.DateTimeField('date you predicted it')
true_date = models.DateTimeField('date it comes true')
def __unicode__(self):
return self.prediction_text
class Vote(models.Model):
prediction = models.ForeignKey(Prediction)
user = models.ForeignKey(User)
|
{"/predictions/admin.py": ["/predictions/models.py"], "/predictions/views.py": ["/predictions/models.py"]}
|
13,231
|
andrewfurman/tarot
|
refs/heads/master
|
/predictions/views.py
|
from django.http import HttpResponse
from predictions.models import Prediction, Vote
from django.contrib.auth.models import User
from django.http import Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.contrib.auth import logout
def index(request):
latest_prediction_list = Prediction.objects.all().order_by('-date_predicted')
return render_to_response('predictions/index.html', {'latest_prediction_list': latest_prediction_list})
def detail(request, prediction_id):
p = get_object_or_404(Prediction, pk=prediction_id)
return render_to_response('predictions/detail.html', {'prediction': p})
def results(request, prediction_id):
return HttpResponse("You're looking at the results of poll %s." % prediction_id)
def vote(request, prediction):
v = prediction.vote_set.create(user=user_id)
v.save()
return render_to_response('predictions/vote.html', {'prediction': prediction_id}, context_instance=RequestContext(request))
def userlist(request):
user_list = User.objects.all()
return render_to_response('predictions/users.html', {'user_list': user_list})
def userprofile(request, user_id):
u = get_object_or_404(User, pk=user_id)
users_predictions = Prediction.objects.filter(user=user_id)
points = 0
for vote_object in Vote.objects.all():
if int(vote_object.prediction.user.id) == int(user_id):
points += 1
return render_to_response('predictions/userprofile.html', {'userobject': u, 'points':points})
def logout_view(request):
logout(request)
return render_to_response('registration/logout.html')
def newprediction(request):
p = Prediction(prediction_text=prediction, user=request.user, pub_date=datetime.datetime.now(),true_date=datetime.datetime.now())
|
{"/predictions/admin.py": ["/predictions/models.py"], "/predictions/views.py": ["/predictions/models.py"]}
|
13,232
|
andrewfurman/tarot
|
refs/heads/master
|
/urls.py
|
from django.conf.urls.defaults import *
from django.conf.urls.defaults import patterns, include, url
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^predictions/$', 'predictions.views.index'),
(r'^predictions/(?P<prediction_id>\d+)/$', 'predictions.views.detail'),
(r'^predictions/(?P<prediction_id>\d+)/results/$', 'predictions.views.results'),
(r'^predictions/(?P<prediction_id>\d+)/vote/$', 'predictions.views.vote'),
(r'^predictions/new/$', 'predictions.views.newprediction'),
(r'^users/$', 'predictions.views.userlist'),
(r'^users/(?P<user_id>\d+)/$', 'predictions.views.userprofile'),
(r'^accounts/login/$', 'django.contrib.auth.views.login'),
(r'^accounts/logout/$', 'django.contrib.auth.views.logout'),
(r'^accounts/profile/$', 'predictions.views.index'),
# Examples:
# url(r'^$', 'oursite.views.home', name='home'),
# url(r'^oursite/', include('oursite.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
if settings.DEBUG:
urlpatterns += patterns('',
(r'^predictions/site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '/Users/furmanx/Desktop/oursite/predictions/static', 'show_indexes': True}),
(r'^users/site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '/Users/furmanx/Desktop/oursite/predictions/static', 'show_indexes': True}),
(r'^users/[0-9]+/site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '/Users/furmanx/Desktop/oursite/predictions/static', 'show_indexes': True}),
(r'^predictions/[0-9]+/site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '/Users/furmanx/Desktop/oursite/predictions/static', 'show_indexes': True}),
)
|
{"/predictions/admin.py": ["/predictions/models.py"], "/predictions/views.py": ["/predictions/models.py"]}
|
13,240
|
12218/Library_Website_Basic
|
refs/heads/main
|
/room/admin.py
|
from django.contrib import admin
from .models import Room, RoomType
# Register your models here.
@admin.register(RoomType)
class RoomTypeAdmin(admin.ModelAdmin):
list_display = ('id', 'type_name')
@admin.register(Room)
class RoomAdmin(admin.ModelAdmin):
list_display = ('id', 'on_off','room_user', 'user_id', 'user_passwd', 'room_name', 'room_type', 'start_time', 'end_time', 'members')
|
{"/room/admin.py": ["/room/models.py"], "/room/views.py": ["/room/models.py"]}
|
13,241
|
12218/Library_Website_Basic
|
refs/heads/main
|
/room/migrations/0001_initial.py
|
# Generated by Django 3.2.5 on 2021-07-13 22:08
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='RoomType',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('type_name', models.CharField(max_length=15)),
],
),
migrations.CreateModel(
name='Room',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('user_id', models.CharField(max_length=15)),
('user_passwd', models.CharField(max_length=15)),
('room_name', models.CharField(max_length=15)),
('start_time', models.DateTimeField()),
('end_time', models.DateTimeField()),
('members', models.TextField()),
('room_type', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='room.roomtype')),
('room_user', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)),
],
),
]
|
{"/room/admin.py": ["/room/models.py"], "/room/views.py": ["/room/models.py"]}
|
13,242
|
12218/Library_Website_Basic
|
refs/heads/main
|
/room/views.py
|
from django.shortcuts import render, get_object_or_404, redirect
from .models import Room, RoomType
from django.core.paginator import Paginator
from django.db.models import Count # 导入计数方法
from django.conf import settings
from django.contrib import auth
# Create your views here.
# 分页函数
def divid_room_pages(request, all_rooms):
paginator = Paginator(all_rooms, settings.EACH_PAGE_ROOM_NUM) # 分页,每10条分一页
page_num = request.GET.get('page', 1) # request.GET得到get请求中的内容; 此处查看get请求中有没有page这个属性,没有则为1
page_of_rooms = paginator.get_page(page_num) # 获取分页后的房间分类
current_page_num = page_of_rooms.number # 获取当前页码
# 获取当前页码及前后2页
page_range = list(range(max(current_page_num - 2, 1), current_page_num)) + \
list(range(current_page_num, min(current_page_num + 2, paginator.num_pages) + 1))
# 加上页码之间的省略号
if page_range[0] - 1 >= 2:
page_range.insert(0, '...')
if paginator.num_pages - page_range[-1] >= 2:
page_range.append('...')
# 保留首页和尾页
if page_range[0] != 1:
page_range.insert(0, 1)
if page_range[-1] != paginator.num_pages:
page_range.append(paginator.num_pages)
room_types = RoomType.objects.annotate(room_count = Count('type_name'))
context = {}
context['rooms'] = page_of_rooms
context['room_types'] = room_types
context['page_range'] = page_range
return context
# 所有房间预约信息
def room_list(request):
# context = {}
# context['rooms'] = Room.objects.all() # 获取全部房间信息
# context['room_types'] = RoomType.objects.all() # 获取全部分类
all_rooms = Room.objects.all() # 获取全部房间信息
context = divid_room_pages(request, all_rooms)
return render(request, 'room_list.html', context)
# 房间预约详情
def room_detail(request, room_pk):
context = {}
context['room_detail'] = get_object_or_404(Room, id = room_pk)
context['room_types'] = RoomType.objects.all() # 获取全部分类
context['room_type_1'] = RoomType.objects.all()[0]
context['room_type_2'] = RoomType.objects.all()[1]
context['user'] = request.user # 登录验证
return render(request, 'room_detail.html', context)
# 某房间分类列表
def room_type_list(request, type_id):
room_type = get_object_or_404(RoomType, pk = type_id)
all_rooms = Room.objects.filter(room_type = room_type)
# context = {}
# context['room_types'] = RoomType.objects.all() # 获取全部分类
# type_list = Room.objects.filter(room_type = room_type)
# context['room_type'] = room_type
# context['rooms'] = type_list
context = divid_room_pages(request, all_rooms)
context['room_type'] = room_type
return render(request, 'room_type_list.html', context)
# 用户所有预约页面
def my_page(request):
if request.user.username != '': # 如果登录成功
all_rooms = Room.objects.filter(room_user = request.user) # 获取全部房间信息
context = divid_room_pages(request, all_rooms)
context['username'] = request.user.username
context['user'] = request.user # 登录验证
else:
all_rooms = Room.objects.filter(room_user = 8) # 获取全部房间信息
context = divid_room_pages(request, all_rooms)
context['username'] = ''
context['user'] = request.user # 登录验证
return render(request, 'personal_page.html', context)
# 登录函数
def login(request):
username = request.POST.get('username', '') # 从request中取出username字段,如果没有则设为空字符串
password = request.POST.get('password', '')
user = auth.authenticate(request, username = username, password = password) # 获取登录信息
if user is not None:
auth.login(request, user)
return redirect('/') # 重定向到首页
else:
return render(request, 'error.html', {'message': '用户名或密码不正确', 'title': '登录错误'}) # 跳转错误页面
# 提交信息
def submit_info(request):
roomid = request.POST.get('roomid')
if request.POST.get('on_off', 'False') == 'False':
on_off = False
else:
on_off = True
user_id = request.POST.get('user_id', '')
user_passwd = request.POST.get('user_passwd', '')
room_name = request.POST.get('room_name', '')
room_type = request.POST.get('room_type', '')
start_time = request.POST.get('start_time', '')
end_time = request.POST.get('end_time', '')
members = request.POST.get('members', 'None')
try:
room = get_object_or_404(Room, id = roomid)
room.on_off = on_off
room.user_id = user_id
room.user_passwd = user_passwd
room.room_name = room_name
type_obj = RoomType.objects.filter(type_name = room_type)[0] # 筛选出房间类型对象
room.room_type = type_obj
room.start_time = start_time
room.end_time = end_time
room.members = members
room.save()
return redirect('/room/' + roomid) # 重定向到详情界面
except:
# return redirect('/room/' + roomid) # 重定向到详情界面
return render(request, 'error.html', {'message': '用户名或密码不正确', 'title': '登录错误'}) # 跳转错误页面
|
{"/room/admin.py": ["/room/models.py"], "/room/views.py": ["/room/models.py"]}
|
13,243
|
12218/Library_Website_Basic
|
refs/heads/main
|
/room/migrations/0003_auto_20210715_2015.py
|
# Generated by Django 3.2.5 on 2021-07-15 20:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('room', '0002_alter_room_members'),
]
operations = [
migrations.AlterField(
model_name='room',
name='end_time',
field=models.TimeField(),
),
migrations.AlterField(
model_name='room',
name='start_time',
field=models.TimeField(),
),
]
|
{"/room/admin.py": ["/room/models.py"], "/room/views.py": ["/room/models.py"]}
|
13,244
|
12218/Library_Website_Basic
|
refs/heads/main
|
/room/urls.py
|
from django.urls import path
from . import views
urlpatterns = [
path('<int:room_pk>', views.room_detail, name = 'room_detail'),
path('type/<int:type_id>', views.room_type_list, name = 'room_type_list'),
path('person/', views.my_page, name = 'my_page'),
]
|
{"/room/admin.py": ["/room/models.py"], "/room/views.py": ["/room/models.py"]}
|
13,245
|
12218/Library_Website_Basic
|
refs/heads/main
|
/room/models.py
|
from django.db import models
from django.contrib.auth.models import User
from django.db.models.deletion import DO_NOTHING
# Create your models here.
# 房间类型
class RoomType(models.Model):
type_name = models.CharField(max_length = 15)
def __str__(self) -> str:
return self.type_name # 管理员界面显示分类名称
# 设置每个房间
class Room(models.Model):
on_off = models.BooleanField(default = False) # 是否启用预约
room_user = models.ForeignKey(User, on_delete = DO_NOTHING) # 用户
user_id = models.CharField(max_length = 15) # 用户学号
user_passwd = models.CharField(max_length = 15) # 用户密码
room_name = models.CharField(max_length = 15) # 房间号
room_type = models.ForeignKey(RoomType, on_delete = models.DO_NOTHING) # 房间类型外键
start_time = models.TimeField() # 开始时间
end_time = models.TimeField() # 结束时间
members = models.TextField(default = 'None') # 研修室成员
|
{"/room/admin.py": ["/room/models.py"], "/room/views.py": ["/room/models.py"]}
|
13,246
|
12218/Library_Website_Basic
|
refs/heads/main
|
/room/migrations/0004_room_on_off.py
|
# Generated by Django 3.2.5 on 2021-07-15 20:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('room', '0003_auto_20210715_2015'),
]
operations = [
migrations.AddField(
model_name='room',
name='on_off',
field=models.BooleanField(default=False),
),
]
|
{"/room/admin.py": ["/room/models.py"], "/room/views.py": ["/room/models.py"]}
|
13,247
|
12218/Library_Website_Basic
|
refs/heads/main
|
/room/migrations/0002_alter_room_members.py
|
# Generated by Django 3.2.5 on 2021-07-14 11:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('room', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='room',
name='members',
field=models.TextField(default='None'),
),
]
|
{"/room/admin.py": ["/room/models.py"], "/room/views.py": ["/room/models.py"]}
|
13,248
|
cvra/tim561_lidar_driver
|
refs/heads/master
|
/sicktim561driver/datagram.py
|
import collections
from logging import debug
Sick561Datagram = collections.namedtuple("sick561_datagram", ["TypeOfCommand",
"Command",
"VersionNumber",
"DeviceNumber",
"SerialNumber",
"DeviceSatus1",
"DeviceSatus2",
"TelegramCounter",
"ScanCounter",
"TimeSinceStartup",
"TimeOfTransmission",
"InputStatus1",
"InputStatus2",
"OutputStatus1",
"OutputStatus2",
"ScanningFrequency",
"MeasurementFrequency",
"NumberOfEncoders",
"NumberOf16bitChannels",
"MeasuredDataContents",
"ScalingFactor",
"ScalingOffset",
"StartingAngle",
"AngularStepWidth",
"NumberOfData",
"Data"])
# "NumberOf8BitChannels",
# "Position",
# "Name",
# "Comment",
# "TimeInformation",
# "EventInformation"])
def bytes_from_socket(socket):
while True:
data = socket.recv(256)
for byte in data:
yield bytes([byte])
def datagrams_from_socket(socket):
STX = b'\x02'
ETX = b'\x03'
byte_generator = bytes_from_socket(socket)
while True:
datagram = b''
for byte in byte_generator:
if byte == STX:
break
for byte in byte_generator:
if byte == ETX:
break
datagram += byte
yield datagram
def parse_number(nbr_str):
""" decimal numbers are encoded with leading +/- """
if b'+' in nbr_str or b'-' in nbr_str:
return int(nbr_str)
else:
return int(nbr_str, 16)
def decode_datagram(datagram):
items = datagram.split(b' ')
header = {}
header['TypeOfCommand'] = items[0].decode('ascii')
if header['TypeOfCommand'] != 'sSN':
return None
header['Command'] = items[1].decode('ascii')
if header['Command'] != 'LMDscandata':
return None
header['VersionNumber'] = parse_number(items[2])
header['DeviceNumber'] = parse_number(items[3])
header['SerialNumber'] = items[4].decode('ascii')
header['DeviceStatus1'] = parse_number(items[5])
header['DeviceStatus2'] = parse_number(items[6])
if header['DeviceStatus1'] != 0 or header['DeviceStatus2'] != 0:
return None
header['TelegramCounter'] = parse_number(items[7])
header['TimeSinceStartup'] = parse_number(items[9])
header['TimeOfTransmission'] = parse_number(items[10])
header['AngularStepWidth'] = parse_number(items[24])
header['NumberOfData'] = parse_number(items[25])
header['Data'] = [parse_number(x) / 1000 for x in items[26:26+header['NumberOfData']]]
return header
|
{"/sicktim561driver/scan.py": ["/sicktim561driver/__init__.py"], "/sicktim561driver/__init__.py": ["/sicktim561driver/datagram.py"]}
|
13,249
|
cvra/tim561_lidar_driver
|
refs/heads/master
|
/setup.py
|
#!/usr/bin/env python
from setuptools import setup
args = dict(
name='tim561_lidar_driver',
version='0.1',
description='Sick TIM 561 Driver.',
packages=['sicktim561driver'],
install_requires=['zmqmsgbus'],
author='Dorian Konrad',
author_email='dorian.konrad@gmail.com',
url='https://github.com/cvra/tim561_lidar_driver',
license='BSD',
test_suite='nose.collector',
tests_require=['nose']
)
setup(**args)
|
{"/sicktim561driver/scan.py": ["/sicktim561driver/__init__.py"], "/sicktim561driver/__init__.py": ["/sicktim561driver/datagram.py"]}
|
13,250
|
cvra/tim561_lidar_driver
|
refs/heads/master
|
/sicktim561driver/scan.py
|
import socket
from sicktim561driver import *
import zmqmsgbus
import numpy as np
TIM561_START_ANGLE = 2.3561944902 # -135° in rad
TIM561_STOP_ANGLE = -2.3561944902 # 135° in rad
if __name__ == '__main__':
bus = zmqmsgbus.Bus(sub_addr='ipc://ipc/source',
pub_addr='ipc://ipc/sink')
node = zmqmsgbus.Node(bus)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("10.0.10.3", 2112))
# activate stream
s.send(b'\x02sEN LMDscandata 1\x03\0')
datagrams_generator = datagrams_from_socket(s)
while 1:
datagram = next(datagrams_generator)
decoded = decode_datagram(datagram)
if decoded is not None:
node.publish('/lidar/radius', decoded['Data'])
node.publish('/lidar/theta', np.linspace(TIM561_START_ANGLE, TIM561_STOP_ANGLE, len(decoded['Data'])).tolist())
|
{"/sicktim561driver/scan.py": ["/sicktim561driver/__init__.py"], "/sicktim561driver/__init__.py": ["/sicktim561driver/datagram.py"]}
|
13,251
|
cvra/tim561_lidar_driver
|
refs/heads/master
|
/sicktim561driver/__init__.py
|
from .datagram import *
|
{"/sicktim561driver/scan.py": ["/sicktim561driver/__init__.py"], "/sicktim561driver/__init__.py": ["/sicktim561driver/datagram.py"]}
|
13,253
|
Peacock-Blue/virtualPiano
|
refs/heads/main
|
/camera.py
|
import numpy
import cv2
import math
import mediapipe
import sound_server
drawingModule = mediapipe.solutions.drawing_utils
handsModule = mediapipe.solutions.hands
def openCamera():
vid = cv2.VideoCapture(0)
if not (vid.isOpened()):
print("Could not open video device")
vid.release()
return vid
def closeCamera(vid):
if vid == None or not vid.isOpened():
return
vid.release()
cv2.destroyAllWindows()
fingerTips = [
handsModule.HandLandmark.THUMB_TIP,
handsModule.HandLandmark.INDEX_FINGER_TIP,
handsModule.HandLandmark.MIDDLE_FINGER_TIP,
handsModule.HandLandmark.RING_FINGER_TIP,
handsModule.HandLandmark.PINKY_TIP
]
# def get_freq(x_pos, freq_offset, freq_range, n_segments):
# x_pos *
def start_capture():
capture = openCamera()
frameWidth = capture.get(cv2.CAP_PROP_FRAME_WIDTH)
frameHeight = capture.get(cv2.CAP_PROP_FRAME_HEIGHT)
ss = sound_server.SoundServer()
ss.start()
with handsModule.Hands(static_image_mode=False, min_detection_confidence=0.7, min_tracking_confidence=0.7, max_num_hands=2) as hands:
while (True):
ret, frame = capture.read()
results = hands.process(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
k = 0
if results.multi_hand_landmarks != None:
for handLandmarks in results.multi_hand_landmarks:
for point in fingerTips:
normalizedLandmark = handLandmarks.landmark[point]
if normalizedLandmark.y < 0.5:
sound_server.add_sound_async(ss,int(normalizedLandmark.x * 100 + 200))
pixelCoordinatesLandmark = drawingModule._normalized_to_pixel_coordinates(normalizedLandmark.x, normalizedLandmark.y, frameWidth, frameHeight)
cv2.circle(frame, pixelCoordinatesLandmark, 5, (11 * k, 255, 0), -1)
cv2.imshow('Test hand', frame)
if cv2.waitKey(1) == 27:
break
ss.stop_sound_server()
start_capture()
|
{"/camera.py": ["/sound_server.py"]}
|
13,254
|
Peacock-Blue/virtualPiano
|
refs/heads/main
|
/sound_server.py
|
import threading
import time
from gensound import *
import math
class SoundServer(threading.Thread):
def __init__(self, sound_duration = 0.1):
threading.Thread.__init__(self)
self.stop_sound_server_signal = threading.Event()
self.sound_lock = threading.Lock()
self.sound_to_play = []
self.sound_duration = sound_duration #seconds
def run(self):
while not self.stop_sound_server_signal.is_set():
self.sound_lock.acquire(blocking=False)
if not self.sound_lock.locked():
time.sleep(self.sound_duration)
continue
if len(self.sound_to_play) == 0:
self.sound_lock.release()
time.sleep(self.sound_duration / 100)
else:
first_pending_sound = Sine(frequency = sum(self.sound_to_play) / len(self.sound_to_play), duration = self.sound_duration * 1000)
# print("playin {}".format(first_pending_sound))
self.sound_to_play = []
self.sound_lock.release()
first_pending_sound.play(sample_rate=32000)
def stop_sound_server(self):
self.stop_sound_server_signal.set()
def add_sound_runable(self, freq):
with self.sound_lock:
if type(freq) is int:
self.sound_to_play.append(freq)
elif type(freq) is list:
self.sound_to_play += freq
else:
raise TypeError
class AAST(threading.Thread):
def __init__(self, server_obj : SoundServer, freq):
threading.Thread.__init__(self)
self.freq = freq
self.server_obj = server_obj
def run(self):
# print("aast run")
self.server_obj.sound_lock.acquire(blocking=True)
self.server_obj.sound_to_play.append(self.freq)
self.server_obj.sound_lock.release()
def add_sound_async(server_obj : SoundServer, freq):
# print("sdd_sound_async")
obj = AAST(server_obj, freq)
obj.start()
# ss = SoundServer()
# ss.start()
# add_sound_async(ss, 200)
# time.sleep(0.7)
# add_sound_async(ss, 300)
# add_sound_async(ss, 400)
# time.sleep(2)
# add_sound_async(ss, 500)
# add_sound_async(ss, 300)
# #ss.stop_sound_server()
|
{"/camera.py": ["/sound_server.py"]}
|
13,306
|
wangzaibuaiheniunai/STFAN
|
refs/heads/master
|
/config.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Developed by Shangchen Zhou <shangchenzhou@gmail.com>
from easydict import EasyDict as edict
import os
import socket
__C = edict()
cfg = __C
#
# Common
#
__C.CONST = edict()
__C.CONST.DEVICE = 'all' # '0'
__C.CONST.NUM_WORKER = 1 # number of data workers
__C.CONST.WEIGHTS = './ckpt/best-ckpt.pth.tar'
__C.CONST.TRAIN_BATCH_SIZE = 1
__C.CONST.TEST_BATCH_SIZE = 1
#
# Dataset
#
__C.DATASET = edict()
__C.DATASET.DATASET_NAME = 'VideoDeblur' # VideoDeblur, VideoDeblurReal
#
# Directories
#
__C.DIR = edict()
__C.DIR.OUT_PATH = './output'
if cfg.DATASET.DATASET_NAME == 'VideoDeblur':
__C.DIR.DATASET_JSON_FILE_PATH = './datasets/VideoDeblur.json'
__C.DIR.DATASET_ROOT = '/data/DeepVideoDeblurringDataset/'
__C.DIR.IMAGE_BLUR_PATH = os.path.join(__C.DIR.DATASET_ROOT,'%s/%s/input/%s.jpg')
__C.DIR.IMAGE_CLEAR_PATH = os.path.join(__C.DIR.DATASET_ROOT,'%s/%s/GT/%s.jpg')
# real
if cfg.DATASET.DATASET_NAME == 'VideoDeblurReal':
__C.DIR.DATASET_JSON_FILE_PATH = './datasets/VideoDeblurReal.json'
__C.DIR.DATASET_ROOT = '/data/qualitative_datasets/'
__C.DIR.IMAGE_BLUR_PATH = os.path.join(__C.DIR.DATASET_ROOT,'%s/%s/input/%s.jpg')
__C.DIR.IMAGE_CLEAR_PATH = os.path.join(__C.DIR.DATASET_ROOT,'%s/%s/input/%s.jpg')
#
# data augmentation
#
__C.DATA = edict()
__C.DATA.STD = [255.0, 255.0, 255.0]
__C.DATA.MEAN = [0.0, 0.0, 0.0]
__C.DATA.CROP_IMG_SIZE = [320, 448] # Crop image size: height, width
__C.DATA.GAUSSIAN = [0, 1e-4] # mu, std_var
__C.DATA.COLOR_JITTER = [0.2, 0.15, 0.3, 0.1] # brightness, contrast, saturation, hue
__C.DATA.SEQ_LENGTH = 20
#
# Network
#
__C.NETWORK = edict()
__C.NETWORK.DEBLURNETARCH = 'DeblurNet' # available options: DeblurNet
__C.NETWORK.LEAKY_VALUE = 0.1
__C.NETWORK.BATCHNORM = False
__C.NETWORK.PHASE = 'test' # available options: 'train', 'test', 'resume'
#
# Training
#
__C.TRAIN = edict()
__C.TRAIN.USE_PERCET_LOSS = True
__C.TRAIN.NUM_EPOCHES = 400 # maximum number of epoches
__C.TRAIN.LEARNING_RATE = 1e-4
__C.TRAIN.LR_MILESTONES = [80,160,250]
__C.TRAIN.LR_DECAY = 0.1 # Multiplicative factor of learning rate decay
__C.TRAIN.MOMENTUM = 0.9
__C.TRAIN.BETA = 0.999
__C.TRAIN.BIAS_DECAY = 0.0 # regularization of bias, default: 0
__C.TRAIN.WEIGHT_DECAY = 0.0 # regularization of weight, default: 0
__C.TRAIN.PRINT_FREQ = 10
__C.TRAIN.SAVE_FREQ = 10 # weights will be overwritten every save_freq epoch
__C.LOSS = edict()
__C.LOSS.MULTISCALE_WEIGHTS = [0.3, 0.3, 0.2, 0.1, 0.1]
#
# Testing options
#
__C.TEST = edict()
__C.TEST.VISUALIZATION_NUM = 10
__C.TEST.PRINT_FREQ = 5
if __C.NETWORK.PHASE == 'test':
__C.CONST.TEST_BATCH_SIZE = 1
|
{"/core/build.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/core/train.py", "/core/test.py", "/losses/multiscaleloss.py"], "/utils/network_utils.py": ["/config.py"], "/utils/data_loaders.py": ["/config.py", "/utils/network_utils.py"], "/core/train.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/losses/multiscaleloss.py", "/core/test.py"], "/runner.py": ["/config.py", "/core/build.py"], "/losses/multiscaleloss.py": ["/utils/network_utils.py"], "/core/test.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/losses/multiscaleloss.py"], "/utils/data_transforms.py": ["/config.py"]}
|
13,307
|
wangzaibuaiheniunai/STFAN
|
refs/heads/master
|
/core/build.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Developed by Shangchen Zhou <shangchenzhou@gmail.com>
import os
import sys
import torch.backends.cudnn
import torch.utils.data
import utils.data_loaders
import utils.data_transforms
import utils.network_utils
import models
from models.DeblurNet import DeblurNet
from datetime import datetime as dt
from tensorboardX import SummaryWriter
from core.train import train
from core.test import test
from losses.multiscaleloss import *
def bulid_net(cfg):
# Enable the inbuilt cudnn auto-tuner to find the best algorithm to use
torch.backends.cudnn.benchmark = True
# Set up data augmentation
train_transforms = utils.data_transforms.Compose([
utils.data_transforms.ColorJitter(cfg.DATA.COLOR_JITTER),
utils.data_transforms.Normalize(mean=cfg.DATA.MEAN, std=cfg.DATA.STD),
utils.data_transforms.RandomCrop(cfg.DATA.CROP_IMG_SIZE),
utils.data_transforms.RandomVerticalFlip(),
utils.data_transforms.RandomHorizontalFlip(),
utils.data_transforms.RandomColorChannel(),
utils.data_transforms.RandomGaussianNoise(cfg.DATA.GAUSSIAN),
utils.data_transforms.ToTensor(),
])
test_transforms = utils.data_transforms.Compose([
utils.data_transforms.Normalize(mean=cfg.DATA.MEAN, std=cfg.DATA.STD),
utils.data_transforms.ToTensor(),
])
# Set up data loader
dataset_loader = utils.data_loaders.DATASET_LOADER_MAPPING[cfg.DATASET.DATASET_NAME]()
# Set up networks
deblurnet = models.__dict__[cfg.NETWORK.DEBLURNETARCH].__dict__[cfg.NETWORK.DEBLURNETARCH]()
print('[DEBUG] %s Parameters in %s: %d.' % (dt.now(), cfg.NETWORK.DEBLURNETARCH,
utils.network_utils.count_parameters(deblurnet)))
# Initialize weights of networks
deblurnet.apply(utils.network_utils.init_weights_xavier)
# Set up solver
a = filter(lambda p: p.requires_grad, deblurnet.parameters())
deblurnet_solver = torch.optim.Adam(filter(lambda p: p.requires_grad, deblurnet.parameters()), lr=cfg.TRAIN.LEARNING_RATE,
betas=(cfg.TRAIN.MOMENTUM, cfg.TRAIN.BETA))
if torch.cuda.is_available():
deblurnet = torch.nn.DataParallel(deblurnet).cuda()
# Load pretrained model if exists
init_epoch = 0
Best_Epoch = -1
Best_Img_PSNR = 0
if cfg.NETWORK.PHASE in ['test','resume']:
print('[INFO] %s Recovering from %s ...' % (dt.now(), cfg.CONST.WEIGHTS))
checkpoint = torch.load(cfg.CONST.WEIGHTS)
deblurnet.load_state_dict(checkpoint['deblurnet_state_dict'])
# deblurnet_solver.load_state_dict(checkpoint['deblurnet_solver_state_dict'])
init_epoch = checkpoint['epoch_idx']+1
Best_Img_PSNR = checkpoint['Best_Img_PSNR']
Best_Epoch = checkpoint['Best_Epoch']
print('[INFO] {0} Recover complete. Current epoch #{1}, Best_Img_PSNR = {2} at epoch #{3}.' \
.format(dt.now(), init_epoch, Best_Img_PSNR, Best_Epoch))
# Set up learning rate scheduler to decay learning rates dynamically
deblurnet_lr_scheduler = torch.optim.lr_scheduler.MultiStepLR(deblurnet_solver,
milestones=cfg.TRAIN.LR_MILESTONES,
gamma=cfg.TRAIN.LR_DECAY)
# Summary writer for TensorBoard
output_dir = os.path.join(cfg.DIR.OUT_PATH, dt.now().isoformat() + '_' + cfg.NETWORK.DEBLURNETARCH, '%s')
log_dir = output_dir % 'logs'
ckpt_dir = output_dir % 'checkpoints'
train_writer = SummaryWriter(os.path.join(log_dir, 'train'))
test_writer = SummaryWriter(os.path.join(log_dir, 'test'))
print('[INFO] Output_dir: {0}'.format(output_dir[:-2]))
if cfg.NETWORK.PHASE in ['train','resume']:
train(cfg, init_epoch, dataset_loader, train_transforms, test_transforms,
deblurnet, deblurnet_solver, deblurnet_lr_scheduler,
ckpt_dir, train_writer, test_writer,
Best_Img_PSNR, Best_Epoch)
else:
if os.path.exists(cfg.CONST.WEIGHTS):
test(cfg, init_epoch, dataset_loader, test_transforms, deblurnet, test_writer)
else:
print('[FATAL] %s Please specify the file path of checkpoint.' % (dt.now()))
sys.exit(2)
|
{"/core/build.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/core/train.py", "/core/test.py", "/losses/multiscaleloss.py"], "/utils/network_utils.py": ["/config.py"], "/utils/data_loaders.py": ["/config.py", "/utils/network_utils.py"], "/core/train.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/losses/multiscaleloss.py", "/core/test.py"], "/runner.py": ["/config.py", "/core/build.py"], "/losses/multiscaleloss.py": ["/utils/network_utils.py"], "/core/test.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/losses/multiscaleloss.py"], "/utils/data_transforms.py": ["/config.py"]}
|
13,308
|
wangzaibuaiheniunai/STFAN
|
refs/heads/master
|
/utils/network_utils.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Developed by Shangchen Zhou <shangchenzhou@gmail.com>
import os
import sys
import torch
import numpy as np
from datetime import datetime as dt
from config import cfg
import torch.nn.functional as F
import cv2
def mkdir(path):
if not os.path.isdir(path):
mkdir(os.path.split(path)[0])
else:
return
os.mkdir(path)
def var_or_cuda(x):
if torch.cuda.is_available():
x = x.cuda(non_blocking=True)
return x
def init_weights_xavier(m):
if isinstance(m, torch.nn.Conv2d) or isinstance(m, torch.nn.ConvTranspose2d):
torch.nn.init.xavier_uniform_(m.weight)
if m.bias is not None:
torch.nn.init.constant_(m.bias, 0)
elif type(m) == torch.nn.BatchNorm2d or type(m) == torch.nn.InstanceNorm2d:
if m.weight is not None:
torch.nn.init.constant_(m.weight, 1)
torch.nn.init.constant_(m.bias, 0)
elif type(m) == torch.nn.Linear:
torch.nn.init.normal_(m.weight, 0, 0.01)
torch.nn.init.constant_(m.bias, 0)
def init_weights_kaiming(m):
if isinstance(m, torch.nn.Conv2d) or isinstance(m, torch.nn.ConvTranspose2d):
torch.nn.init.kaiming_normal_(m.weight)
if m.bias is not None:
torch.nn.init.constant_(m.bias, 0)
elif type(m) == torch.nn.BatchNorm2d or type(m) == torch.nn.InstanceNorm2d:
if m.weight is not None:
torch.nn.init.constant_(m.weight, 1)
torch.nn.init.constant_(m.bias, 0)
elif type(m) == torch.nn.Linear:
torch.nn.init.normal_(m.weight, 0, 0.01)
torch.nn.init.constant_(m.bias, 0)
def save_checkpoints(file_path, epoch_idx, deblurnet, deblurnet_solver, Best_Img_PSNR, Best_Epoch):
print('[INFO] %s Saving checkpoint to %s ...' % (dt.now(), file_path))
checkpoint = {
'epoch_idx': epoch_idx,
'Best_Img_PSNR': Best_Img_PSNR,
'Best_Epoch': Best_Epoch,
'deblurnet_state_dict': deblurnet.state_dict(),
'deblurnet_solver_state_dict': deblurnet_solver.state_dict(),
}
torch.save(checkpoint, file_path)
def count_parameters(model):
return sum(p.numel() for p in model.parameters())
def get_weight_parameters(model):
return [param for name, param in model.named_parameters() if ('weight' in name)]
def get_bias_parameters(model):
return [param for name, param in model.named_parameters() if ('bias' in name)]
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def __repr__(self):
return '{:.5f} ({:.5f})'.format(self.val, self.avg)
'''input Tensor: 2 H W'''
def flow2rgb(flowmap):
assert(isinstance(flowmap, torch.Tensor))
global args
_, H, W = flowmap.shape
rgb = torch.ones((3,H,W))
normalized_flow_map = flowmap / (flowmap.max())
rgb[0] += normalized_flow_map[0]
rgb[1] -= 0.5*(normalized_flow_map[0] + normalized_flow_map[1])
rgb[2] += normalized_flow_map[1]
return rgb.clamp(0,1)
def warp(x, flo):
"""
warp an image/tensor (im2) back to im1, according to the optical flow
x: [B, C, H, W] (im2)
flo: [B, 2, H, W] flow
"""
B, C, H, W = x.size()
# mesh grid
xx = torch.arange(0, W).view(1, -1).repeat(H, 1)
yy = torch.arange(0, H).view(-1, 1).repeat(1, W)
xx = xx.view(1, 1, H, W).repeat(B, 1, 1, 1)
yy = yy.view(1, 1, H, W).repeat(B, 1, 1, 1)
grid = torch.cat((xx, yy), 1).float()
mask = torch.autograd.Variable(torch.ones(x.size()))
if x.is_cuda:
grid = grid.cuda()
mask = mask.cuda()
vgrid = grid + flo
# scale grid to [-1,1]
vgrid[:, 0, :, :] = 2.0 * vgrid[:, 0, :, :] / max(W - 1, 1) - 1.0
vgrid[:, 1, :, :] = 2.0 * vgrid[:, 1, :, :] / max(H - 1, 1) - 1.0
vgrid = vgrid.permute(0, 2, 3, 1)
output = torch.nn.functional.grid_sample(x, vgrid)
mask = torch.nn.functional.grid_sample(mask, vgrid)
mask[mask < 0.9999] = 0
mask[mask > 0] = 1
return output*mask
|
{"/core/build.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/core/train.py", "/core/test.py", "/losses/multiscaleloss.py"], "/utils/network_utils.py": ["/config.py"], "/utils/data_loaders.py": ["/config.py", "/utils/network_utils.py"], "/core/train.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/losses/multiscaleloss.py", "/core/test.py"], "/runner.py": ["/config.py", "/core/build.py"], "/losses/multiscaleloss.py": ["/utils/network_utils.py"], "/core/test.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/losses/multiscaleloss.py"], "/utils/data_transforms.py": ["/config.py"]}
|
13,309
|
wangzaibuaiheniunai/STFAN
|
refs/heads/master
|
/utils/data_loaders.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Developed by Shangchen Zhou <shangchenzhou@gmail.com>
import cv2
import json
import numpy as np
import os
import io
import random
import scipy.io
import sys
import torch.utils.data.dataset
from config import cfg
from datetime import datetime as dt
from enum import Enum, unique
from utils.imgio_gen import readgen
import utils.network_utils
class DatasetType(Enum):
TRAIN = 0
TEST = 1
class VideoDeblurDataset(torch.utils.data.dataset.Dataset):
"""VideoDeblurDataset class used for PyTorch DataLoader"""
def __init__(self, file_list_with_metadata, transforms = None):
self.file_list = file_list_with_metadata
self.transforms = transforms
def __len__(self):
return len(self.file_list)
def __getitem__(self, idx):
name, seq_blur, seq_clear = self.get_datum(idx)
seq_blur, seq_clear = self.transforms(seq_blur, seq_clear)
return name, seq_blur, seq_clear
def get_datum(self, idx):
name = self.file_list[idx]['name']
length = self.file_list[idx]['length']
seq_blur_paths = self.file_list[idx]['seq_blur']
seq_clear_paths = self.file_list[idx]['seq_clear']
seq_blur = []
seq_clear = []
for i in range(length):
img_blur = readgen(seq_blur_paths[i]).astype(np.float32)
img_clear = readgen(seq_clear_paths[i]).astype(np.float32)
seq_blur.append(img_blur)
seq_clear.append(img_clear)
return name, seq_blur, seq_clear
# //////////////////////////////// = End of VideoDeblurDataset Class Definition = ///////////////////////////////// #
class VideoDeblurDataLoader:
def __init__(self):
self.img_blur_path_template = cfg.DIR.IMAGE_BLUR_PATH
self.img_clear_path_template = cfg.DIR.IMAGE_CLEAR_PATH
# Load all files of the dataset
with io.open(cfg.DIR.DATASET_JSON_FILE_PATH, encoding='utf-8') as file:
self.files_list = json.loads(file.read())
def get_dataset(self, dataset_type, transforms=None):
sequences = []
# Load data for each sequence
for file in self.files_list:
if dataset_type == DatasetType.TRAIN and file['phase'] == 'train':
name = file['name']
phase = file['phase']
samples = file['sample']
sam_len = len(samples)
seq_len = cfg.DATA.SEQ_LENGTH
seq_num = int(sam_len/seq_len)
for n in range(seq_num):
sequence = self.get_files_of_taxonomy(phase, name, samples[seq_len*n: seq_len*(n+1)])
sequences.extend(sequence)
if not seq_len%seq_len == 0:
sequence = self.get_files_of_taxonomy(phase, name, samples[-seq_len:])
sequences.extend(sequence)
seq_num += 1
print('[INFO] %s Collecting files of Taxonomy [Name = %s]' % (dt.now(), name + ': ' + str(seq_num)))
elif dataset_type == DatasetType.TEST and file['phase'] == 'test':
name = file['name']
phase = file['phase']
samples = file['sample']
sam_len = len(samples)
seq_len = cfg.DATA.SEQ_LENGTH
seq_num = int(sam_len / seq_len)
for n in range(seq_num):
sequence = self.get_files_of_taxonomy(phase, name, samples[seq_len*n: seq_len*(n+1)])
sequences.extend(sequence)
if not seq_len % seq_len == 0:
sequence = self.get_files_of_taxonomy(phase, name, samples[-seq_len:])
sequences.extend(sequence)
seq_num += 1
print('[INFO] %s Collecting files of Taxonomy [Name = %s]' % (dt.now(), name + ': ' + str(seq_num)))
print('[INFO] %s Complete collecting files of the dataset for %s. Seq Numbur: %d.\n' % (dt.now(), dataset_type.name, len(sequences)))
return VideoDeblurDataset(sequences, transforms)
def get_files_of_taxonomy(self, phase, name, samples):
n_samples = len(samples)
seq_blur_paths = []
seq_clear_paths = []
sequence = []
for sample_idx, sample_name in enumerate(samples):
# Get file path of img
img_blur_path = self.img_blur_path_template % (phase, name, sample_name)
img_clear_path = self.img_clear_path_template % (phase, name, sample_name)
if os.path.exists(img_blur_path) and os.path.exists(img_clear_path):
seq_blur_paths.append(img_blur_path)
seq_clear_paths.append(img_clear_path)
if not seq_blur_paths == [] and not seq_clear_paths == []:
if phase == 'train' and random.random() < 0.5:
# reverse
seq_blur_paths.reverse()
seq_clear_paths.reverse()
sequence.append({
'name': name,
'length': n_samples,
'seq_blur': seq_blur_paths,
'seq_clear': seq_clear_paths,
})
return sequence
# /////////////////////////////// = End of VideoDeblurDataLoader Class Definition = /////////////////////////////// #
DATASET_LOADER_MAPPING = {
'VideoDeblur': VideoDeblurDataLoader,
'VideoDeblurReal': VideoDeblurDataLoader
}
|
{"/core/build.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/core/train.py", "/core/test.py", "/losses/multiscaleloss.py"], "/utils/network_utils.py": ["/config.py"], "/utils/data_loaders.py": ["/config.py", "/utils/network_utils.py"], "/core/train.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/losses/multiscaleloss.py", "/core/test.py"], "/runner.py": ["/config.py", "/core/build.py"], "/losses/multiscaleloss.py": ["/utils/network_utils.py"], "/core/test.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/losses/multiscaleloss.py"], "/utils/data_transforms.py": ["/config.py"]}
|
13,310
|
wangzaibuaiheniunai/STFAN
|
refs/heads/master
|
/core/train.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Developed by Shangchen Zhou <shangchenzhou@gmail.com>
import os
import torch.backends.cudnn
import torch.utils.data
import utils.data_loaders
import utils.data_transforms
import utils.network_utils
import torchvision
import random
from losses.multiscaleloss import *
from time import time
from core.test import test
from models.VGG19 import VGG19
def train(cfg, init_epoch, dataset_loader, train_transforms, val_transforms,
deblurnet, deblurnet_solver, deblurnet_lr_scheduler,
ckpt_dir, train_writer, val_writer,
Best_Img_PSNR, Best_Epoch):
n_itr = 0
# Training loop
for epoch_idx in range(init_epoch, cfg.TRAIN.NUM_EPOCHES):
# Set up data loader
train_data_loader = torch.utils.data.DataLoader(
dataset=dataset_loader.get_dataset(utils.data_loaders.DatasetType.TRAIN, train_transforms),
batch_size=cfg.CONST.TRAIN_BATCH_SIZE,
num_workers=cfg.CONST.NUM_WORKER, pin_memory=True, shuffle=True)
# Tick / tock
epoch_start_time = time()
# Batch average meterics
batch_time = utils.network_utils.AverageMeter()
data_time = utils.network_utils.AverageMeter()
deblur_mse_losses = utils.network_utils.AverageMeter()
if cfg.TRAIN.USE_PERCET_LOSS == True:
deblur_percept_losses = utils.network_utils.AverageMeter()
deblur_losses = utils.network_utils.AverageMeter()
img_PSNRs = utils.network_utils.AverageMeter()
# Adjust learning rate
deblurnet_lr_scheduler.step()
print('[INFO] learning rate: {0}\n'.format(deblurnet_lr_scheduler.get_lr()))
batch_end_time = time()
seq_num = len(train_data_loader)
vggnet = VGG19()
if torch.cuda.is_available():
vggnet = torch.nn.DataParallel(vggnet).cuda()
for seq_idx, (_, seq_blur, seq_clear) in enumerate(train_data_loader):
# Measure data time
data_time.update(time() - batch_end_time)
# Get data from data loader
seq_blur = [utils.network_utils.var_or_cuda(img) for img in seq_blur]
seq_clear = [utils.network_utils.var_or_cuda(img) for img in seq_clear]
# switch models to training mode
deblurnet.train()
# Train the model
last_img_blur = seq_blur[0]
output_last_img = seq_blur[0]
output_last_fea = None
for batch_idx, [img_blur, img_clear] in enumerate(zip(seq_blur, seq_clear)):
img_blur_hold = img_blur
output_img, output_fea = deblurnet(img_blur, last_img_blur, output_last_img, output_last_fea)
# deblur loss
deblur_mse_loss = mseLoss(output_img, img_clear)
deblur_mse_losses.update(deblur_mse_loss.item(), cfg.CONST.TRAIN_BATCH_SIZE)
if cfg.TRAIN.USE_PERCET_LOSS == True:
deblur_percept_loss = perceptualLoss(output_img, img_clear, vggnet)
deblur_percept_losses.update(deblur_percept_loss.item(), cfg.CONST.TRAIN_BATCH_SIZE)
deblur_loss = deblur_mse_loss + 0.01 * deblur_percept_loss
else:
deblur_loss = deblur_mse_loss
deblur_losses.update(deblur_loss.item(), cfg.CONST.TRAIN_BATCH_SIZE)
img_PSNR = PSNR(output_img, img_clear)
img_PSNRs.update(img_PSNR.item(), cfg.CONST.TRAIN_BATCH_SIZE)
# deblurnet update
deblurnet_solver.zero_grad()
deblur_loss.backward()
deblurnet_solver.step()
# Append loss to TensorBoard
train_writer.add_scalar('STFANet/DeblurLoss_0_TRAIN', deblur_loss.item(), n_itr)
train_writer.add_scalar('STFANet/DeblurMSELoss_0_TRAIN', deblur_mse_loss.item(), n_itr)
if cfg.TRAIN.USE_PERCET_LOSS == True:
train_writer.add_scalar('STFANet/DeblurPerceptLoss_0_TRAIN', deblur_percept_loss.item(), n_itr)
n_itr = n_itr + 1
# Tick / tock
batch_time.update(time() - batch_end_time)
batch_end_time = time()
# print per batch
if (batch_idx + 1) % cfg.TRAIN.PRINT_FREQ == 0:
if cfg.TRAIN.USE_PERCET_LOSS == True:
print('[TRAIN] [Ech {0}/{1}][Seq {2}/{3}][Bch {4}/{5}] BT {6} DT {7} DeblurLoss {8} [{9}, {10}] PSNR {11}'
.format(epoch_idx + 1, cfg.TRAIN.NUM_EPOCHES, seq_idx + 1, seq_num, batch_idx + 1,
cfg.DATA.SEQ_LENGTH, batch_time, data_time,
deblur_losses, deblur_mse_losses, deblur_percept_losses, img_PSNRs))
else:
print(
'[TRAIN] [Ech {0}/{1}][Seq {2}/{3}][Bch {4}/{5}] BT {6} DT {7} DeblurLoss {8} PSNR {9}'
.format(epoch_idx + 1, cfg.TRAIN.NUM_EPOCHES, seq_idx + 1, seq_num, batch_idx + 1,
cfg.DATA.SEQ_LENGTH, batch_time, data_time, deblur_losses, img_PSNRs))
# show
if seq_idx == 0 and batch_idx < cfg.TEST.VISUALIZATION_NUM:
img_blur = img_blur[0][[2, 1, 0], :, :].cpu() + torch.Tensor(cfg.DATA.MEAN).view(3, 1, 1)
img_clear = img_clear[0][[2, 1, 0], :, :].cpu() + torch.Tensor(cfg.DATA.MEAN).view(3, 1, 1)
output_last_img = output_last_img[0][[2, 1, 0], :, :].cpu() + torch.Tensor(cfg.DATA.MEAN).view(3, 1, 1)
img_out = output_img[0][[2, 1, 0], :, :].cpu().clamp(0.0, 1.0) + torch.Tensor(cfg.DATA.MEAN).view(3, 1, 1)
result = torch.cat([torch.cat([img_blur, img_clear], 2),
torch.cat([output_last_img, img_out], 2)], 1)
result = torchvision.utils.make_grid(result, nrow=1, normalize=True)
train_writer.add_image('STFANet/TRAIN_RESULT' + str(batch_idx + 1), result, epoch_idx + 1)
# *** Update output_last_img/feature ***
last_img_blur = img_blur_hold
output_last_img = output_img.clamp(0.0, 1.0).detach()
output_last_fea = output_fea.detach()
# print per sequence
print('[TRAIN] [Epoch {0}/{1}] [Seq {2}/{3}] ImgPSNR_avg {4}\n'
.format(epoch_idx + 1, cfg.TRAIN.NUM_EPOCHES, seq_idx + 1, seq_num, img_PSNRs.avg))
# Append epoch loss to TensorBoard
train_writer.add_scalar('STFANet/EpochPSNR_0_TRAIN', img_PSNRs.avg, epoch_idx + 1)
# Tick / tock
epoch_end_time = time()
print('[TRAIN] [Epoch {0}/{1}]\t EpochTime {2}\t ImgPSNR_avg {3}\n'
.format(epoch_idx + 1, cfg.TRAIN.NUM_EPOCHES, epoch_end_time - epoch_start_time, img_PSNRs.avg))
# Validate the training models
img_PSNR = test(cfg, epoch_idx, dataset_loader, val_transforms, deblurnet, val_writer)
# Save weights to file
if (epoch_idx + 1) % cfg.TRAIN.SAVE_FREQ == 0:
if not os.path.exists(ckpt_dir):
os.makedirs(ckpt_dir)
utils.network_utils.save_checkpoints(os.path.join(ckpt_dir, 'ckpt-epoch-%04d.pth.tar' % (epoch_idx + 1)), \
epoch_idx + 1, deblurnet, deblurnet_solver, \
Best_Img_PSNR, Best_Epoch)
if img_PSNR >= Best_Img_PSNR:
if not os.path.exists(ckpt_dir):
os.makedirs(ckpt_dir)
Best_Img_PSNR = img_PSNR
Best_Epoch = epoch_idx + 1
utils.network_utils.save_checkpoints(os.path.join(ckpt_dir, 'best-ckpt.pth.tar'), \
epoch_idx + 1, deblurnet, deblurnet_solver, \
Best_Img_PSNR, Best_Epoch)
# Close SummaryWriter for TensorBoard
train_writer.close()
val_writer.close()
|
{"/core/build.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/core/train.py", "/core/test.py", "/losses/multiscaleloss.py"], "/utils/network_utils.py": ["/config.py"], "/utils/data_loaders.py": ["/config.py", "/utils/network_utils.py"], "/core/train.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/losses/multiscaleloss.py", "/core/test.py"], "/runner.py": ["/config.py", "/core/build.py"], "/losses/multiscaleloss.py": ["/utils/network_utils.py"], "/core/test.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/losses/multiscaleloss.py"], "/utils/data_transforms.py": ["/config.py"]}
|
13,311
|
wangzaibuaiheniunai/STFAN
|
refs/heads/master
|
/runner.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Developed by Shangchen Zhou <shangchenzhou@gmail.com>
import matplotlib
import os
# Fix problem: no $DISPLAY environment variable
matplotlib.use('Agg')
# Fix problem: possible deadlock in dataloader
# import cv2
# cv2.setNumThreads(0)
from argparse import ArgumentParser
from pprint import pprint
from config import cfg
from core.build import bulid_net
import torch
def get_args_from_command_line():
parser = ArgumentParser(description='Parser of Runner of Network')
parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [cuda]', default=cfg.CONST.DEVICE, type=str)
parser.add_argument('--phase', dest='phase', help='phase of CNN', default=cfg.NETWORK.PHASE, type=str)
parser.add_argument('--weights', dest='weights', help='Initialize network from the weights file', default=cfg.CONST.WEIGHTS, type=str)
parser.add_argument('--data', dest='data_path', help='Set dataset root_path', default=cfg.DIR.DATASET_ROOT, type=str)
parser.add_argument('--out', dest='out_path', help='Set output path', default=cfg.DIR.OUT_PATH)
args = parser.parse_args()
return args
def main():
# Get args from command line
args = get_args_from_command_line()
if args.gpu_id is not None:
cfg.CONST.DEVICE = args.gpu_id
if args.phase is not None:
cfg.NETWORK.PHASE = args.phase
if args.weights is not None:
cfg.CONST.WEIGHTS = args.weights
if args.data_path is not None:
cfg.DIR.DATASET_ROOT = args.data_path
if cfg.DATASET.DATASET_NAME == 'VideoDeblur':
cfg.DIR.IMAGE_BLUR_PATH = os.path.join(args.data_path,'%s/%s/input/%s.jpg')
cfg.DIR.IMAGE_CLEAR_PATH = os.path.join(args.data_path,'%s/%s/GT/%s.jpg')
if cfg.DATASET.DATASET_NAME == 'VideoDeblurReal':
cfg.DIR.IMAGE_BLUR_PATH = os.path.join(args.data_path,'%s/%s/input/%s.jpg')
cfg.DIR.IMAGE_CLEAR_PATH = os.path.join(args.data_path,'%s/%s/input/%s.jpg')
if args.out_path is not None:
cfg.DIR.OUT_PATH = args.out_path
# Print config
print('Use config:')
pprint(cfg)
# Set GPU to use
if type(cfg.CONST.DEVICE) == str and not cfg.CONST.DEVICE == 'all':
os.environ["CUDA_VISIBLE_DEVICES"] = cfg.CONST.DEVICE
print('CUDA DEVICES NUMBER: '+ str(torch.cuda.device_count()))
# Setup Network & Start train/test process
bulid_net(cfg)
if __name__ == '__main__':
main()
|
{"/core/build.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/core/train.py", "/core/test.py", "/losses/multiscaleloss.py"], "/utils/network_utils.py": ["/config.py"], "/utils/data_loaders.py": ["/config.py", "/utils/network_utils.py"], "/core/train.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/losses/multiscaleloss.py", "/core/test.py"], "/runner.py": ["/config.py", "/core/build.py"], "/losses/multiscaleloss.py": ["/utils/network_utils.py"], "/core/test.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/losses/multiscaleloss.py"], "/utils/data_transforms.py": ["/config.py"]}
|
13,312
|
wangzaibuaiheniunai/STFAN
|
refs/heads/master
|
/losses/multiscaleloss.py
|
import torch
import torch.nn as nn
from utils.network_utils import *
def mseLoss(output, target):
mse_loss = nn.MSELoss(reduction ='elementwise_mean')
MSE = mse_loss(output, target)
return MSE
def PSNR(output, target, max_val = 1.0):
output = output.clamp(0.0,1.0)
mse = torch.pow(target - output, 2).mean()
if mse == 0:
return torch.Tensor([100.0])
return 10 * torch.log10(max_val**2 / mse)
def perceptualLoss(fakeIm, realIm, vggnet):
'''
use vgg19 conv1_2, conv2_2, conv3_3 feature, before relu layer
'''
weights = [1, 0.2, 0.04]
features_fake = vggnet(fakeIm)
features_real = vggnet(realIm)
features_real_no_grad = [f_real.detach() for f_real in features_real]
mse_loss = nn.MSELoss(reduction='elementwise_mean')
loss = 0
for i in range(len(features_real)):
loss_i = mse_loss(features_fake[i], features_real_no_grad[i])
loss = loss + loss_i * weights[i]
return loss
|
{"/core/build.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/core/train.py", "/core/test.py", "/losses/multiscaleloss.py"], "/utils/network_utils.py": ["/config.py"], "/utils/data_loaders.py": ["/config.py", "/utils/network_utils.py"], "/core/train.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/losses/multiscaleloss.py", "/core/test.py"], "/runner.py": ["/config.py", "/core/build.py"], "/losses/multiscaleloss.py": ["/utils/network_utils.py"], "/core/test.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/losses/multiscaleloss.py"], "/utils/data_transforms.py": ["/config.py"]}
|
13,313
|
wangzaibuaiheniunai/STFAN
|
refs/heads/master
|
/core/test.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Developed by Shangchen Zhou <shangchenzhou@gmail.com>
import torch.backends.cudnn
import torch.utils.data
import utils.data_loaders
import utils.data_transforms
import utils.network_utils
from losses.multiscaleloss import *
import torchvision
import numpy as np
import scipy.io as io
from time import time
def mkdir(path):
if not os.path.isdir(path):
mkdir(os.path.split(path)[0])
else:
return
os.mkdir(path)
def test(cfg, epoch_idx, dataset_loader, test_transforms, deblurnet, test_writer):
# Set up data loader
test_data_loader = torch.utils.data.DataLoader(
dataset=dataset_loader.get_dataset(utils.data_loaders.DatasetType.TEST, test_transforms),
batch_size=cfg.CONST.TEST_BATCH_SIZE,
num_workers=cfg.CONST.NUM_WORKER, pin_memory=True, shuffle=False)
seq_num = len(test_data_loader)
# Batch average meterics
batch_time = utils.network_utils.AverageMeter()
test_time = utils.network_utils.AverageMeter()
data_time = utils.network_utils.AverageMeter()
img_PSNRs = utils.network_utils.AverageMeter()
batch_end_time = time()
test_psnr = dict()
g_names= 'init'
for seq_idx, (name, seq_blur, seq_clear) in enumerate(test_data_loader):
data_time.update(time() - batch_end_time)
seq_blur = [utils.network_utils.var_or_cuda(img) for img in seq_blur]
seq_clear = [utils.network_utils.var_or_cuda(img) for img in seq_clear]
seq_len = len(seq_blur)
# Switch models to training mode
deblurnet.eval()
if cfg.NETWORK.PHASE == 'test':
if not g_names == name[0]:
g_names = name[0]
save_num = 0
assert (len(name) == 1)
name = name[0]
if not name in test_psnr:
test_psnr[name] = {
'n_samples': 0,
'psnr': []
}
with torch.no_grad():
last_img_blur = seq_blur[0]
output_last_img = seq_blur[0]
output_last_fea = None
for batch_idx, [img_blur, img_clear] in enumerate(zip(seq_blur, seq_clear)):
img_blur_hold = img_blur
# Test runtime
torch.cuda.synchronize()
test_time_start = time()
# --Forwards--
output_img, output_fea = deblurnet(img_blur, last_img_blur, output_last_img, output_last_fea)
torch.cuda.synchronize()
test_time.update(time() - test_time_start)
print('[RUNING TIME] {0}'.format(test_time))
img_PSNR = PSNR(output_img, img_clear)
img_PSNRs.update(img_PSNR.item(), cfg.CONST.TRAIN_BATCH_SIZE)
batch_time.update(time() - batch_end_time)
batch_end_time = time()
# Print per batch
if (batch_idx+1) % cfg.TEST.PRINT_FREQ == 0:
print('[TEST] [Ech {0}/{1}][Seq {2}/{3}][Bch {4}/{5}] BT {6} DT {7}\t imgPSNR {8}'
.format(epoch_idx + 1, cfg.TRAIN.NUM_EPOCHES, seq_idx+1, seq_num, batch_idx + 1, seq_len, batch_time, data_time, img_PSNRs))
if seq_idx == 0 and batch_idx < cfg.TEST.VISUALIZATION_NUM and not cfg.NETWORK.PHASE == 'test':
if epoch_idx == 0 or cfg.NETWORK.PHASE in ['test','resume']:
img_blur = img_blur[0][[2, 1, 0], :, :].cpu() + torch.Tensor(cfg.DATA.MEAN).view(3, 1, 1)
img_clear = img_clear[0][[2, 1, 0], :, :].cpu() + torch.Tensor(cfg.DATA.MEAN).view(3, 1, 1)
test_writer.add_image('STFANet/IMG_BLUR' + str(batch_idx + 1), img_blur, epoch_idx + 1)
test_writer.add_image('STFANet/IMG_CLEAR' + str(batch_idx + 1), img_clear, epoch_idx + 1)
output_last_img = output_last_img[0][[2, 1, 0], :, :].cpu() + torch.Tensor(cfg.DATA.MEAN).view(3, 1, 1)
img_out = output_img[0][[2, 1, 0], :, :].cpu().clamp(0.0, 1.0) + torch.Tensor(cfg.DATA.MEAN).view(3, 1, 1)
test_writer.add_image('STFANet/LAST_IMG_OUT' +str(batch_idx + 1), output_last_img, epoch_idx + 1)
test_writer.add_image('STFANet/IMAGE_OUT' +str(batch_idx + 1), img_out, epoch_idx + 1)
if cfg.NETWORK.PHASE == 'test':
test_psnr[name]['n_samples'] += 1
test_psnr[name]['psnr'].append(img_PSNR)
img_dir = os.path.join(cfg.DIR.OUT_PATH, name)
if not os.path.isdir(img_dir):
mkdir(img_dir)
print('[TEST Saving: ]'+img_dir + '/' + str(save_num).zfill(5) + '.png')
cv2.imwrite(img_dir + '/' + str(save_num).zfill(5) + '.png',
(output_img.clamp(0.0, 1.0)[0].cpu().numpy().transpose(1, 2, 0) * 255.0).astype(
np.uint8),[int(cv2.IMWRITE_PNG_COMPRESSION), 5])
save_num = save_num + 1
# *** Update output_last_img/feature ***
last_img_blur = img_blur_hold
output_last_img = output_img.clamp(0.0, 1.0)
output_last_fea = output_fea
# Print per seq
if (batch_idx + 1) % cfg.TEST.PRINT_FREQ == 0:
print(
'[TEST] [Ech {0}/{1}][Seq {2}/{3}] BT {4} DT {5} \t ImgPSNR_avg {6}\n'
.format(epoch_idx + 1, cfg.TRAIN.NUM_EPOCHES, seq_idx + 1, seq_num, batch_time, data_time, img_PSNRs.avg))
# Output testing results
if cfg.NETWORK.PHASE == 'test':
# Output test results
print('============================ TEST RESULTS ============================')
print('[TEST] Total_Mean_PSNR:' + str(img_PSNRs.avg))
for name in test_psnr:
test_psnr[name]['psnr'] = np.mean(test_psnr[name]['psnr'], axis=0)
print('[TEST] Name: {0}\t Num: {1}\t Mean_PSNR: {2}'.format(name, test_psnr[name]['n_samples'],
test_psnr[name]['psnr']))
result_file = open(os.path.join(cfg.DIR.OUT_PATH, 'test_result.txt'), 'w')
sys.stdout = result_file
print('============================ TEST RESULTS ============================')
print('[TEST] Total_Mean_PSNR:' + str(img_PSNRs.avg))
for name in test_psnr:
print('[TEST] Name: {0}\t Num: {1}\t Mean_PSNR: {2}'.format(name, test_psnr[name]['n_samples'],
test_psnr[name]['psnr']))
result_file.close()
else:
# Output val results
print('============================ TEST RESULTS ============================')
print('[TEST] Total_Mean_PSNR:' + str(img_PSNRs.avg))
print('[TEST] [Epoch{0}]\t BatchTime_avg {1}\t DataTime_avg {2}\t ImgPSNR_avg {3}\n'
.format(cfg.TRAIN.NUM_EPOCHES, batch_time.avg, data_time.avg, img_PSNRs.avg))
# Add testing results to TensorBoard
test_writer.add_scalar('STFANet/EpochPSNR_1_TEST', img_PSNRs.avg, epoch_idx + 1)
return img_PSNRs.avg
|
{"/core/build.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/core/train.py", "/core/test.py", "/losses/multiscaleloss.py"], "/utils/network_utils.py": ["/config.py"], "/utils/data_loaders.py": ["/config.py", "/utils/network_utils.py"], "/core/train.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/losses/multiscaleloss.py", "/core/test.py"], "/runner.py": ["/config.py", "/core/build.py"], "/losses/multiscaleloss.py": ["/utils/network_utils.py"], "/core/test.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/losses/multiscaleloss.py"], "/utils/data_transforms.py": ["/config.py"]}
|
13,314
|
wangzaibuaiheniunai/STFAN
|
refs/heads/master
|
/utils/data_transforms.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Developed by Shangchen Zhou <shangchenzhou@gmail.com>
'''ref: http://pytorch.org/docs/master/torchvision/transforms.html'''
import cv2
import numpy as np
import torch
import torchvision.transforms.functional as F
from config import cfg
from PIL import Image
import random
import numbers
class Compose(object):
""" Composes several co_transforms together.
For example:
>>> transforms.Compose([
>>> transforms.CenterCrop(10),
>>> transforms.ToTensor(),
>>> ])
"""
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, seq_blur, seq_clear):
for t in self.transforms:
seq_blur, seq_clear = t(seq_blur, seq_clear)
return seq_blur, seq_clear
class ColorJitter(object):
def __init__(self, color_adjust_para):
"""brightness [max(0, 1 - brightness), 1 + brightness] or the given [min, max]"""
"""contrast [max(0, 1 - contrast), 1 + contrast] or the given [min, max]"""
"""saturation [max(0, 1 - saturation), 1 + saturation] or the given [min, max]"""
"""hue [-hue, hue] 0<= hue <= 0.5 or -0.5 <= min <= max <= 0.5"""
'''Ajust brightness, contrast, saturation, hue'''
'''Input: PIL Image, Output: PIL Image'''
self.brightness, self.contrast, self.saturation, self.hue = color_adjust_para
def __call__(self, seq_blur, seq_clear):
seq_blur = [Image.fromarray(np.uint8(img)) for img in seq_blur]
seq_clear = [Image.fromarray(np.uint8(img)) for img in seq_clear]
if self.brightness > 0:
brightness_factor = np.random.uniform(max(0, 1 - self.brightness), 1 + self.brightness)
seq_blur = [F.adjust_brightness(img, brightness_factor) for img in seq_blur]
seq_clear = [F.adjust_brightness(img, brightness_factor) for img in seq_clear]
if self.contrast > 0:
contrast_factor = np.random.uniform(max(0, 1 - self.contrast), 1 + self.contrast)
seq_blur = [F.adjust_contrast(img, contrast_factor) for img in seq_blur]
seq_clear = [F.adjust_contrast(img, contrast_factor) for img in seq_clear]
if self.saturation > 0:
saturation_factor = np.random.uniform(max(0, 1 - self.saturation), 1 + self.saturation)
seq_blur = [F.adjust_saturation(img, saturation_factor) for img in seq_blur]
seq_clear = [F.adjust_saturation(img, saturation_factor) for img in seq_clear]
if self.hue > 0:
hue_factor = np.random.uniform(-self.hue, self.hue)
seq_blur = [F.adjust_hue(img, hue_factor) for img in seq_blur]
seq_clear = [F.adjust_hue(img, hue_factor) for img in seq_clear]
seq_blur = [np.asarray(img) for img in seq_blur]
seq_clear = [np.asarray(img) for img in seq_clear]
seq_blur = [img.clip(0,255) for img in seq_blur]
seq_clear = [img.clip(0,255) for img in seq_clear]
return seq_blur, seq_clear
class RandomColorChannel(object):
def __call__(self, seq_blur, seq_clear):
random_order = np.random.permutation(3)
seq_blur = [img[:,:,random_order] for img in seq_blur]
seq_clear = [img[:,:,random_order] for img in seq_clear]
return seq_blur, seq_clear
class RandomGaussianNoise(object):
def __init__(self, gaussian_para):
self.mu = gaussian_para[0]
self.std_var = gaussian_para[1]
def __call__(self, seq_blur, seq_clear):
shape = seq_blur[0].shape
gaussian_noise = np.random.normal(self.mu, self.std_var, shape)
# only apply to blurry images
seq_blur = [img + gaussian_noise for img in seq_blur]
seq_blur = [img.clip(0, 1) for img in seq_blur]
return seq_blur, seq_clear
class Normalize(object):
def __init__(self, mean, std):
self.mean = mean
self.std = std
def __call__(self, seq_blur, seq_clear):
seq_blur = [img/self.std -self.mean for img in seq_blur]
seq_clear = [img/self.std -self.mean for img in seq_clear]
return seq_blur, seq_clear
class CenterCrop(object):
def __init__(self, crop_size):
"""Set the height and weight before and after cropping"""
self.crop_size_h = crop_size[0]
self.crop_size_w = crop_size[1]
def __call__(self, seq_blur, seq_clear):
input_size_h, input_size_w, _ = seq_blur[0].shape
x_start = int(round((input_size_w - self.crop_size_w) / 2.))
y_start = int(round((input_size_h - self.crop_size_h) / 2.))
seq_blur = [img[y_start: y_start + self.crop_size_h, x_start: x_start + self.crop_size_w] for img in seq_blur]
seq_clear = [img[y_start: y_start + self.crop_size_h, x_start: x_start + self.crop_size_w] for img in seq_clear]
return seq_blur, seq_clear
class RandomCrop(object):
def __init__(self, crop_size):
"""Set the height and weight before and after cropping"""
self.crop_size_h = crop_size[0]
self.crop_size_w = crop_size[1]
def __call__(self, seq_blur, seq_clear):
input_size_h, input_size_w, _ = seq_blur[0].shape
x_start = random.randint(0, input_size_w - self.crop_size_w)
y_start = random.randint(0, input_size_h - self.crop_size_h)
seq_blur = [img[y_start: y_start + self.crop_size_h, x_start: x_start + self.crop_size_w] for img in seq_blur]
seq_clear = [img[y_start: y_start + self.crop_size_h, x_start: x_start + self.crop_size_w] for img in seq_clear]
return seq_blur, seq_clear
class RandomHorizontalFlip(object):
"""Randomly horizontally flips the given PIL.Image with a probability of 0.5 left-right"""
def __call__(self, seq_blur, seq_clear):
if random.random() < 0.5:
'''Change the order of 0 and 1, for keeping the net search direction'''
seq_blur = [np.copy(np.fliplr(img)) for img in seq_blur]
seq_clear = [np.copy(np.fliplr(img)) for img in seq_clear]
return seq_blur, seq_clear
class RandomVerticalFlip(object):
"""Randomly vertically flips the given PIL.Image with a probability of 0.5 up-down"""
def __call__(self, seq_blur, seq_clear):
if random.random() < 0.5:
seq_blur = [np.copy(np.flipud(img)) for img in seq_blur]
seq_clear = [np.copy(np.flipud(img)) for img in seq_clear]
return seq_blur, seq_clear
class ToTensor(object):
"""Converts a numpy.ndarray (H x W x C) to a torch.FloatTensor of shape (C x H x W)."""
def __call__(self, seq_blur, seq_clear):
seq_blur = [np.transpose(img, (2, 0, 1)) for img in seq_blur]
seq_clear = [np.transpose(img, (2, 0, 1)) for img in seq_clear]
# handle numpy array
seq_blur_tensor = [torch.from_numpy(img).float() for img in seq_blur]
seq_clear_tensor = [torch.from_numpy(img).float() for img in seq_clear]
return seq_blur_tensor, seq_clear_tensor
|
{"/core/build.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/core/train.py", "/core/test.py", "/losses/multiscaleloss.py"], "/utils/network_utils.py": ["/config.py"], "/utils/data_loaders.py": ["/config.py", "/utils/network_utils.py"], "/core/train.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/losses/multiscaleloss.py", "/core/test.py"], "/runner.py": ["/config.py", "/core/build.py"], "/losses/multiscaleloss.py": ["/utils/network_utils.py"], "/core/test.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/losses/multiscaleloss.py"], "/utils/data_transforms.py": ["/config.py"]}
|
13,315
|
wangzaibuaiheniunai/STFAN
|
refs/heads/master
|
/datasets/make_json.py
|
import json
import os
import io
from utils.imgio_gen import readgen
import numpy as np
# For VideoDeblur dataset
file = io.open('VideoDeblur.json','w',encoding='utf-8')
root = '/DeepVideoDeblurringDataset'
samples = []
phase = ['train', 'test']
for ph in phase:
names = sorted(os.listdir(os.path.join(root, ph)))
for name in names:
sample_list = sorted(os.listdir(os.path.join(root, ph, name, 'input')))
sample = [sample_list[i][:-4] for i in range(len(sample_list))]
sample_sub = []
for sam in sample:
if not sam == ".DS_S":
sample_sub.append(sam)
l = {'name': name,'phase': ph,'sample': sample_sub}
samples.append(l)
js = json.dump(samples, file, sort_keys=False, indent=4)
|
{"/core/build.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/core/train.py", "/core/test.py", "/losses/multiscaleloss.py"], "/utils/network_utils.py": ["/config.py"], "/utils/data_loaders.py": ["/config.py", "/utils/network_utils.py"], "/core/train.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/losses/multiscaleloss.py", "/core/test.py"], "/runner.py": ["/config.py", "/core/build.py"], "/losses/multiscaleloss.py": ["/utils/network_utils.py"], "/core/test.py": ["/utils/data_loaders.py", "/utils/data_transforms.py", "/utils/network_utils.py", "/losses/multiscaleloss.py"], "/utils/data_transforms.py": ["/config.py"]}
|
13,319
|
AnkisCZ/terraria-bot
|
refs/heads/master
|
/command/command_map.py
|
import tshock.server_adapter as Server
import util.ip_handler as ExternalIP
_map = dict()
# [ SERVICE , IS_AUTHORIZATION_REQUIRED]
_map['!ip'] = [ExternalIP.get_my_external_ip, False]
_map['!status'] = [Server.server_status, False]
_map['!angler'] = [Server.server_clear_angler, False]
_map['!restart'] = [Server.server_restart, True]
_map['!save'] = [Server.save_world, True]
_map['!night'] = [Server.server_night_time, True]
_map['!day'] = [Server.server_day_time, True]
_map['!eclipse'] = [Server.server_eclipse, True]
_map['!fullmoon'] = [Server.server_full_moon, True]
_map['!bloodmoon'] = [Server.server_blood_moon, True]
_map['!rain'] = [Server.server_rain, True]
_map['!sandstorm'] = [Server.server_sandstorm, True]
_map['!help'] = [Server.server_help, True]
def get_command_map():
return _map
|
{"/command/command_map.py": ["/tshock/server_adapter.py", "/util/ip_handler.py"], "/bot.py": ["/command/command_map.py"]}
|
13,320
|
AnkisCZ/terraria-bot
|
refs/heads/master
|
/bot.py
|
import time
import discord
import logging.config
import command.command_map as CommandMap
LOG_COMMAND_AUTHORIZATION_GRANTED = 'Service {0}: Authorization Granted'
LOG_COMMAND_AUTHORIZATION_DENIED = 'Service {0}: Authorization Denied'
AUTHORIZATION_DENIED_MESSAGE='You do not have the permission to use this command'
LOG_COMMAND_PATTERN = 'User {0} invoked {1} command'
LOG_LOGIN_MESSAGE = 'Logged in. Name: {0} - User ID: {1}'
TOKEN = 'YOUR_TOKEN_HERE'
logging.config.fileConfig('logging.conf')
logger = logging.getLogger(__name__)
command_map = CommandMap.get_command_map()
client = discord.Client()
def _check_authorization(roles):
for role in roles:
if role.name == 'TBotAdmin':
return True
return False
def _execute_command(message):
if message.content in command_map:
logger.info(LOG_COMMAND_PATTERN.format(message.author, message.content))
service, is_authorization_required = command_map.get(message.content)
if is_authorization_required:
return _execute_role_based_service(service, message.author.roles)
else:
return service()
def _execute_role_based_service(service, roles, *args):
if _check_authorization(roles):
logger.info(LOG_COMMAND_AUTHORIZATION_GRANTED.format(service.__name__))
return service(*args)
else:
logger.info(LOG_COMMAND_AUTHORIZATION_DENIED.format(service.__name__))
return AUTHORIZATION_DENIED_MESSAGE
@client.event
async def on_message(message):
if message.author == client.user:
return
result_message = _execute_command(message)
if result_message:
await client.send_message(message.channel, result_message)
@client.event
async def on_ready():
logger.info(LOG_LOGIN_MESSAGE.format(client.user.name, client.user.id))
while True:
try:
client.loop.run_until_complete(client.start(TOKEN))
except Exception:
logger.info('Reconnecting...')
time.sleep(5)
|
{"/command/command_map.py": ["/tshock/server_adapter.py", "/util/ip_handler.py"], "/bot.py": ["/command/command_map.py"]}
|
13,321
|
AnkisCZ/terraria-bot
|
refs/heads/master
|
/tshock/server_adapter.py
|
import requests
# BASE
TOKEN = None
USERNAME = 'tbot'
PASSWORD = 'admin'
# SERVICES
SERVER_URL = 'http://127.0.0.1:7878'
RESTART_SERVER_SERVICE = SERVER_URL + '/v2/server/off'
PLAYER_LIST_SERVICE = SERVER_URL + '/v2/players/list'
TEST_TOKEN_SERVICE = SERVER_URL + '/tokentest'
SAVE_WORLD_SERVICE = SERVER_URL + '/v2/world/save'
RAW_CMD_SERVICE = SERVER_URL + '/v3/server/rawcmd'
STATUS_SERVICE = SERVER_URL + '/status'
LOGIN_SERVICE = SERVER_URL + '/v2/token/create'
# MESSAGING
SERVER_RESTARTING_MESSAGE = 'The Server is restarting...'
CRITICAL_ERROR_MESSAGE = 'Error. Please, validate with your server provider'
EMPTY_SERVER_MESSAGE = 'Empty Server'
WORLD_SAVED_MESSAGE = 'World Saved'
NIGHT_TIME_MESSAGE = 'Setting Server time to Night (19:30 PM)'
BLOOD_MOON_MESSAGE = 'The Server is now running a Blood Moon Event'
FULL_MOON_MESSAGE = 'The Server is now Full Moon Phase'
SANDSTORM_MESSAGE = 'Sandstorm: {0}'
DAY_TIME_MESSAGE = 'Setting Server time to Day (04:30 AM)'
ECLIPSE_MESSAGE = 'The Server is now running an Eclipse Event'
RESTART_MESSAGE = 'The Server will be restarted'
ANGLER_MESSAGE = 'Angler has new quests now'
GENERIC_ERROR = 'Error. Please, restart the server'
RAIN_MESSAGE = 'Raining: {0}'
STATUS_MESSAGE = 'Server Name: {0}\n' \
'Players: {1}\n' \
'Running for: {2}'
# Help Message
HELP_SERVICE_MESSAGE = 'Services:\n' \
'!ip - returns the Server IP\n' \
'!status - returns the Server Status\n' \
'!angler - reset Angler\'s Quest\n' \
'\n' \
'Admin Services:\n' \
'!bloodmoon - invoke Blood Moon event\n' \
'!sandstorm - create sandstorms\n' \
'!eclipse - invoke Eclipse event\n' \
'!restart - restart the Server\n' \
'!night - set the time to Night Time (19:30 PM)\n' \
'!save - save the World\n' \
'!rain - set weather to Rain\n' \
'!day - set time to Day Time (04:30 AM)'
# Server State
rain_state = False
sandstorm_state = False
def _consume_service(url, parameters=None):
if parameters:
return requests.get(url, params=parameters).json()
else:
return requests.get(url, params=_get_token()).json()
def _validate_response(response):
if response and 'status' in response and response['status'] == '200':
return True
else:
return False
def _get_token():
global TOKEN
if TOKEN and _validate_token():
return {'token': TOKEN}
else:
TOKEN = _consume_service(url=LOGIN_SERVICE, parameters={'username': USERNAME, 'password': PASSWORD})['token']
return {'token': TOKEN}
def _validate_token():
response = _consume_service(TEST_TOKEN_SERVICE, parameters={'token': TOKEN})
if _validate_response(response):
return True
else:
return False
def _get_player_list():
response = _consume_service(PLAYER_LIST_SERVICE)
if _validate_response(response):
player_list = list()
players = response['players']
for player in players:
player_list.append(player['nickname'])
if len(player_list) > 0:
return ', '.join(player_list)
else:
return EMPTY_SERVER_MESSAGE
else:
return GENERIC_ERROR
def server_status():
response = _consume_service(STATUS_SERVICE)
if _validate_response(response):
return STATUS_MESSAGE.format(response['world'], _get_player_list(), response['uptime'])
else:
return GENERIC_ERROR
def save_world():
response = _consume_service(SAVE_WORLD_SERVICE)
if _validate_response(response):
return WORLD_SAVED_MESSAGE
else:
return GENERIC_ERROR
def server_restart():
token_parameter = _get_token()
server_parameter = {'confirm': True, 'message': RESTART_MESSAGE, 'nosave': False}
parameters = {**token_parameter, **server_parameter}
response = _consume_service(url=RESTART_SERVER_SERVICE, parameters=parameters)
if _validate_response(response):
return SERVER_RESTARTING_MESSAGE
else:
return CRITICAL_ERROR_MESSAGE
def _invoke_raw_command(server_parameter):
token_parameter = _get_token()
parameters = {**token_parameter, **server_parameter}
return _consume_service(RAW_CMD_SERVICE, parameters=parameters)
def server_night_time():
server_parameter = {'cmd': '/time 19:30'}
response = _invoke_raw_command(server_parameter=server_parameter)
if _validate_response(response):
return NIGHT_TIME_MESSAGE
else:
return CRITICAL_ERROR_MESSAGE
def server_day_time():
server_parameter = {'cmd': '/time 04:30'}
response = _invoke_raw_command(server_parameter=server_parameter)
if _validate_response(response):
return DAY_TIME_MESSAGE
else:
return CRITICAL_ERROR_MESSAGE
def server_eclipse():
server_parameter = {'cmd': '/eclipse'}
response = _invoke_raw_command(server_parameter=server_parameter)
if _validate_response(response):
return ECLIPSE_MESSAGE
else:
return CRITICAL_ERROR_MESSAGE
def server_full_moon():
server_parameter = {'cmd': '/fullmoon'}
response = _invoke_raw_command(server_parameter=server_parameter)
if _validate_response(response):
return FULL_MOON_MESSAGE
else:
return CRITICAL_ERROR_MESSAGE
def server_rain():
global rain_state
if rain_state:
command = 'stop'
else:
command = 'start'
server_parameter = {'cmd': '/rain {0}'.format(command)}
response = _invoke_raw_command(server_parameter=server_parameter)
if _validate_response(response):
rain_state = not rain_state
return RAIN_MESSAGE.format(rain_state)
else:
return CRITICAL_ERROR_MESSAGE
def server_sandstorm():
global sandstorm_state
if sandstorm_state:
command = 'stop'
else:
command = 'start'
server_parameter = {'cmd': '/sandstorm {0}'.format(command)}
response = _invoke_raw_command(server_parameter=server_parameter)
if _validate_response(response):
sandstorm_state = not sandstorm_state
return SANDSTORM_MESSAGE.format(sandstorm_state)
else:
return CRITICAL_ERROR_MESSAGE
def server_blood_moon():
server_parameter = {'cmd': '/bloodmoon'}
response = _invoke_raw_command(server_parameter=server_parameter)
if _validate_response(response):
return BLOOD_MOON_MESSAGE
else:
return CRITICAL_ERROR_MESSAGE
def server_clear_angler():
server_parameter = {'cmd': '/clearangler'}
response = _invoke_raw_command(server_parameter=server_parameter)
if _validate_response(response):
return ANGLER_MESSAGE
else:
return CRITICAL_ERROR_MESSAGE
def server_help():
return HELP_SERVICE_MESSAGE
|
{"/command/command_map.py": ["/tshock/server_adapter.py", "/util/ip_handler.py"], "/bot.py": ["/command/command_map.py"]}
|
13,322
|
AnkisCZ/terraria-bot
|
refs/heads/master
|
/util/ip_handler.py
|
import urllib.request
def get_my_external_ip():
external_ip = urllib.request.urlopen('https://api.ipify.org').read().decode('utf8')
result = 'Server IP: {0}'.format(external_ip)
return result
|
{"/command/command_map.py": ["/tshock/server_adapter.py", "/util/ip_handler.py"], "/bot.py": ["/command/command_map.py"]}
|
13,338
|
rahulrsr/AjayTest
|
refs/heads/master
|
/pageObject/HomePage.py
|
from selenium.webdriver.common.by import By
class homepage:
def __init__(self,driver):
self.driver=driver
SignInButton=(By.XPATH,"//a[@class='login']")
def get_SignIn_Button(self):
return self.driver.find_element(*homepage.SignInButton)
|
{"/ActualTests/test_flow1.py": ["/pageObject/NewsLetter.py", "/pageObject/HomePage.py", "/pageObject/SignInPage.py", "/pageObject/CreateAccount.py"], "/pageObject/test_Run_File.py": ["/pageObject/NewsLetter.py"]}
|
13,339
|
rahulrsr/AjayTest
|
refs/heads/master
|
/pageObject/SignInPage.py
|
from selenium.webdriver.common.by import By
class SignIn:
def __init__(self,driver):
self.driver=driver
CreateAccountButton=(By.XPATH,"//button[@id='SubmitCreate']")
New_Email_Address_Field=(By.XPATH,"//input[@name='email_create']")
Login_Email_Address_Field=(By.XPATH,"//input[@id='email']")
Login_Password_Field = (By.XPATH, "// input[ @ id = 'passwd']")
SingIn_button=(By.XPATH,"//button[@id='SubmitLogin']")
Create_Account_Message=(By.XPATH,"//ol/li")
def get_CreateAccountButton(self):
return self.driver.find_element(*SignIn.CreateAccountButton)
def get_New_Email_Input_Field(self):
return self.driver.find_element(*SignIn.New_Email_Address_Field)
def get_login_Email_Input_Field(self):
return self.driver.find_element(*SignIn.Login_Email_Address_Field)
def get_login_Password_Input_Field(self):
return self.driver.find_element(*SignIn.Login_Password_Field)
def get_Sign_In_Button(self):
return self.driver.find_element(*SignIn.SingIn_button)
def get_account_creation_message(self):
return self.driver.find_element(*SignIn.Create_Account_Message)
|
{"/ActualTests/test_flow1.py": ["/pageObject/NewsLetter.py", "/pageObject/HomePage.py", "/pageObject/SignInPage.py", "/pageObject/CreateAccount.py"], "/pageObject/test_Run_File.py": ["/pageObject/NewsLetter.py"]}
|
13,340
|
rahulrsr/AjayTest
|
refs/heads/master
|
/ActualTests/test_flow1.py
|
import pytest
from pageObject.NewsLetter import NewsLetter
from pageObject.HomePage import homepage
from pageObject.SignInPage import SignIn
from pageObject.CreateAccount import Account_Creation
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
@pytest.mark.usefixtures("setup")
class TestFirst:
def test_NewsLetter_already_registered(self):
# driver = self.driver
# url = "http://automationpractice.com/index.php?"
# driver.get(url)
obj=NewsLetter(self.driver)
#obj.letter_input_field_fun.send_keys("rahul@gmail.com")
obj.letter_input_field_fun().send_keys("rahul@gmail.com")
obj.submit_btn_fun().click()
#time.sleep(5)
#driver.implicitly_wait(5)
assert obj.alert_box_existing_msg_fun().text=="Newsletter : This email address is already registered."
def test_NewsLetter_successfully_subscribed(self):
# driver = self.driver
# url = "http://automationpractice.com/index.php?"
# driver.get(url)
obj=NewsLetter(self.driver)
#obj.letter_input_field_fun.send_keys("rahul@gmail.com")
obj.letter_input_field_fun().send_keys("rahul12q34kq5q11we@gmail.com")
obj.submit_btn_fun().click()
#time.sleep(5)
#driver.implicitly_wait(5)
print(self.driver.title)
assert obj.alert_box_success_msg_fun().text=="Newsletter : You have successfully subscribed to this newsletter."
def test_signIn_New(self):
home=homepage(self.driver)
home.get_SignIn_Button().click()
signInPage=SignIn(self.driver)
signInPage.get_New_Email_Input_Field().send_keys("abc1267as@gmail.com")
#assert signInPage.CreateAccountButton()
signInPage.get_CreateAccountButton().click()
print(self.driver.title)
#//form/div[@class='account_creation'][1]/h3[@class='page-subheading']
WebDriverWait(self.driver,15).until(
EC.presence_of_element_located((By.XPATH,"//form/div[@class='account_creation'][1]/h3[@class='page-subheading']"))
)
#alert_text=signInPage.get_account_creation_message().text
#assert alert_text==""
def test_create_account(self):
CreateAccount=Account_Creation(self.driver)
CreateAccount.Radio_Button_Mr_fun().click()
CreateAccount.FirstName_fun().send_keys("TestR")
CreateAccount.LastName_fun().send_keys("TestLast")
CreateAccount.Email_address_fun().send_keys("testr@testmail.com")
CreateAccount.Password_fun().send_keys("Test@123")
CreateAccount.Day_dd_fun().select_by_visible_text('2')
CreateAccount.Month_dd_fun().select_by_value(2)
CreateAccount.years_dd_fun().select_by_value(1976)
CreateAccount.Address_FirstName_fun().send_keys("TestR")
CreateAccount.Address_LastName_fun().send_keys("TestLast")
CreateAccount.Address_Line1_fun().send_keys("TestAddress")
CreateAccount.Address_City_fun().send_keys("Juneau")
CreateAccount.Address_State_dd_fun().select_by_value('Alaska')
CreateAccount.Address_Post_Code_fun().send_keys('99501')
CreateAccount.Address_Mobile_fun().send_keys('9014568727')
CreateAccount.Address_alias_fun().send_keys('testAlaska')
CreateAccount.Register_Button_fun().click()
|
{"/ActualTests/test_flow1.py": ["/pageObject/NewsLetter.py", "/pageObject/HomePage.py", "/pageObject/SignInPage.py", "/pageObject/CreateAccount.py"], "/pageObject/test_Run_File.py": ["/pageObject/NewsLetter.py"]}
|
13,341
|
rahulrsr/AjayTest
|
refs/heads/master
|
/pageObject/CreateAccount.py
|
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
class Account_Creation:
def __init__(self,driver):
self.driver=driver
Radio_Button_Mr = (By.XPATH,"//div[@class='radio'][@id='uniform-id_gender1']")
Radio_Button_Mrs = (By.XPATH,"//div[@class='radio'][@id='uniform-id_gender2']")
FirstName=(By.ID,"customer_firstname")
LastName=(By.ID,"customer_lastname")
Email_address=(By.ID,"email")
Password=(By.ID,"passwd")
Day=(By.ID,"days") #select
Month = (By.ID, "months") #select
years=(By.ID,"years") #select
Address_FirstName=(By.ID,"firstname")
Address_LastName =(By.ID,"lastname")
Address_Line1=(By.ID,"address1")
Address_City=(By.ID,"city")
Address_State = (By.ID, "id_state")
Address_post_code=(By.ID,"postcode")
Address_Mobile=(By.ID,"phone_mobile")
Address_alias=(By.ID,"alias")
Register_Button=(By.ID,"submitAccount")
def Radio_Button_Mr_fun(self):
return self.driver.find_element(*Account_Creation.Radio_Button_Mr)
def Radio_Button_Mrs_fun(self):
return self.driver.find_element(*Account_Creation.Radio_Button_Mrs)
def FirstName_fun(self):
return self.driver.find_element(*Account_Creation.FirstName)
def LastName_fun(self):
return self.driver.find_element(*Account_Creation.LastName)
def Email_address_fun(self):
return self.driver.find_element(*Account_Creation.Email_address)
def Password_fun(self):
return self.driver.find_element(*Account_Creation.Password)
def Day_dd_fun(self):
return Select(self.driver.find_element(*Account_Creation.Day))
def Month_dd_fun(self):
return Select(self.driver.find_element(*Account_Creation.Month))
def years_dd_fun(self):
return Select(self.driver.find_element(*Account_Creation.Month))
def Address_FirstName_fun(self):
return self.driver.find_element(*Account_Creation.Address_FirstName)
def Address_LastName_fun(self):
return self.driver.find_element(*Account_Creation.Address_LastName)
def Address_Line1_fun(self):
return self.driver.find_element(*Account_Creation.Address_LastName)
def Address_City_fun(self):
return self.driver.find_element(*Account_Creation.Address_City)
def Address_State_dd_fun(self):
return Select(self.driver.find_element(*Account_Creation.Address_State))
def Address_Post_Code_fun(self):
return self.driver.find_element(*Account_Creation.Address_post_code)
def Address_Mobile_fun(self):
return self.driver.find_element(*Account_Creation.Address_Mobile)
def Address_alias_fun(self):
return self.driver.find_element(*Account_Creation.Address_alias)
def Register_Button_fun(self):
return self.driver.find_element(*Account_Creation.Register_Button)
|
{"/ActualTests/test_flow1.py": ["/pageObject/NewsLetter.py", "/pageObject/HomePage.py", "/pageObject/SignInPage.py", "/pageObject/CreateAccount.py"], "/pageObject/test_Run_File.py": ["/pageObject/NewsLetter.py"]}
|
13,342
|
rahulrsr/AjayTest
|
refs/heads/master
|
/pageObject/test_Run_File.py
|
#import pageObject.NewsLetter as N_L
from pageObject.NewsLetter import NewsLetter
from selenium import webdriver
#from selenium.webdriver impor
import time
class TestRun:
# def __init__(self):
# self.driver = webdriver.Chrome()
# self.driver.implicitly_wait(5)
def test_run(self):
driver = self.driver
url = "http://automationpractice.com/index.php?"
driver.get(url)
obj=NewsLetter(driver)
#obj.letter_input_field_fun.send_keys("rahul@gmail.com")
obj.letter_input_field_fun().send_keys("rahul@gmail.com")
obj.submit_btn_fun().click()
#time.sleep(5)
#driver.implicitly_wait(5)
assert obj.alert_box_existing_msg_fun().text=="Newsletter : This email address is already registered."
def test_success_message(self):
driver = self.driver
url = "http://automationpractice.com/index.php?"
driver.get(url)
obj=NewsLetter(driver)
#obj.letter_input_field_fun.send_keys("rahul@gmail.com")
obj.letter_input_field_fun().send_keys("rahul12@gmail.com")
obj.submit_btn_fun().click()
#time.sleep(5)
#driver.implicitly_wait(5)
assert obj.alert_box_success_msg_fun().text=="Newsletter : You have successfully subscribed to this newsletter."
if __name__ == '__main__':
t=testRun()
t.testRun()
t.test_success_message()
|
{"/ActualTests/test_flow1.py": ["/pageObject/NewsLetter.py", "/pageObject/HomePage.py", "/pageObject/SignInPage.py", "/pageObject/CreateAccount.py"], "/pageObject/test_Run_File.py": ["/pageObject/NewsLetter.py"]}
|
13,343
|
rahulrsr/AjayTest
|
refs/heads/master
|
/pageObject2/newLetter.py
|
from selenium import webdriver
import time
url="http://automationpractice.com/index.php?"
driver=webdriver.Chrome()
driver.get(url)
"""
describe('This test case describes about user subscription to newsletter', function() {
it('user should be able to subscribe himself for newsletter', async function (done) {
await AutomationPracticeHome_Page.scrollToViewHeading();
await AutomationPracticeHome_Page.enterEmailNewsLetter("chrishemsworthyz@you-spam.com");
await AutomationPracticeHome_Page.submitNewsLetterButton();
await browser.pause(3000);
await AutomationPracticeHome_Page.isSuccessAlertExists();
await AutomationPracticeHome_Page.confirmSuccessfulNewsLetterSubscription();
});
async enterEmailNewsLetter(emailAddress){
return await ((await this.newsletterInputField).setValue(emailAddress));
}
get newsletterInputField() {
return $("//input[@id='newsletter-input']");
}
async submitNewsLetterButton(){
return await (await this.submitNewsletter).click();
}
get submitNewsletter(){
return $("//button[@name='submitNewsletter']");
}
async confirmSuccessfulNewsLetterSubscription(){
var successfulSubscriptionHeader = "//p[@class='alert alert-success']";
var validateSuccessfulSubscriptionHeader = await browser.waitUntil(async function () {
return (await(await $(successfulSubscriptionHeader)).getText() == "Newsletter : You have successfully subscribed to this newsletter.")
}, 3000);
assert.equal(validateSuccessfulSubscriptionHeader, true);
}
async confirmUnSuccessfulNewsLetterSubscription(){
var unsuccessfulSubs
async confirmUnSuccessfulNewsLetterSubscription(){
var unsuccessfulSubscriptionHeader = "//p[@class='alert alert-danger']";
var validateUnsuccessfulSubscriptionHeader = await browser.waitUntil(async function () {
return (await(await $(unsuccessfulSubscriptionHeader)).getText() =="Newsletter : This email address is already registered.");
}, 3000);
assert.equal(validateUnsuccessfulSubscriptionHeader, true);
}
"""
#driver.find_element_by_id('newsletter-input')
driver.find_element_by_xpath("//input[@id='newsletter-input']").send_keys("rahul@gmail.com")
driver.find_element_by_xpath("//button[@name='submitNewsletter']").click()
time.sleep(5)
alert_box=driver.find_element_by_xpath("//p[@class='alert alert-danger']")
assert alert_box.text=="Newsletter : This email address is already registered."
|
{"/ActualTests/test_flow1.py": ["/pageObject/NewsLetter.py", "/pageObject/HomePage.py", "/pageObject/SignInPage.py", "/pageObject/CreateAccount.py"], "/pageObject/test_Run_File.py": ["/pageObject/NewsLetter.py"]}
|
13,344
|
rahulrsr/AjayTest
|
refs/heads/master
|
/pageObject/NewsLetter.py
|
from selenium.webdriver.common.by import By
class NewsLetter:
letter_input_field=(By.XPATH,"//input[@id='newsletter-input']")
submit_btn=(By.XPATH,"//button[@name='submitNewsletter']")
alert_box_existing_msg = (By.XPATH, "//p[@class='alert alert-danger']")
alert_box_success_msg = (By.XPATH, "//p[@class='alert alert-success']")
def __init__(self,driver):
self.driver=driver
def letter_input_field_fun(self):
return self.driver.find_element(*NewsLetter.letter_input_field)
def submit_btn_fun(self):
return self.driver.find_element(*NewsLetter.submit_btn)
def alert_box_existing_msg_fun(self):
return self.driver.find_element(*NewsLetter.alert_box_existing_msg)
def alert_box_success_msg_fun(self):
return self.driver.find_element(*NewsLetter.alert_box_success_msg)
|
{"/ActualTests/test_flow1.py": ["/pageObject/NewsLetter.py", "/pageObject/HomePage.py", "/pageObject/SignInPage.py", "/pageObject/CreateAccount.py"], "/pageObject/test_Run_File.py": ["/pageObject/NewsLetter.py"]}
|
13,348
|
sajetan/contact_book
|
refs/heads/master
|
/project/Authentication.py
|
from project import *
class UserAuth(object):
def __init__(self,username,password):
self.username = username
self.password = password
def do_authentication(self):
if self.username == "tej" and self.password == "123":
#starting user session
session['logged_in'] = True
else:
return False
return True
|
{"/project/Authentication.py": ["/project/__init__.py"], "/project/tables.py": ["/project/__init__.py"], "/project/contacts.py": ["/project/__init__.py", "/project/tables.py"], "/app.py": ["/project/__init__.py", "/project/authentication.py"], "/project/authentication.py": ["/project/__init__.py"]}
|
13,349
|
sajetan/contact_book
|
refs/heads/master
|
/project/validate_form.py
|
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField,validators
from wtforms.validators import DataRequired, Email, Length, ValidationError, NumberRange
class ContactForm(FlaskForm):
name = StringField('Name', validators=[DataRequired(), Length(min=-1, max=80, message='You cannot have more than 80 characters')])
surname = StringField('Surname', validators=[Length(min=-1, max=100, message='You cannot have more than 100 characters')])
email = StringField('E-Mail', validators=[Email(), Length(min=-1, max=200, message='You cannot have more than 200 characters')])
phone = StringField('Phone', validators=[Length(min=6, max=20, message='Phone number should be between 6-20 characters')])
def validate_phone(form, field):
print(field)
if (len(field.data))>6:
try:
int(field.data)
except Exception as e:
raise ValidationError('Invalid phone number - Accepts only numbers')
|
{"/project/Authentication.py": ["/project/__init__.py"], "/project/tables.py": ["/project/__init__.py"], "/project/contacts.py": ["/project/__init__.py", "/project/tables.py"], "/app.py": ["/project/__init__.py", "/project/authentication.py"], "/project/authentication.py": ["/project/__init__.py"]}
|
13,350
|
sajetan/contact_book
|
refs/heads/master
|
/project/__init__.py
|
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
from flask import Flask,make_response,json,g,jsonify,request, redirect, url_for, render_template, flash, session, abort
#from flask_httpauth import HTTPBasicAuth
from flask_restful import reqparse, abort, Api, Resource
from flask_sqlalchemy import SQLAlchemy
import logging
from logging.handlers import RotatingFileHandler
#initialize app before importing anything else
app = Flask(__name__)
#auth = HTTPBasicAuth()
api = Api(app)
app.config['SECRET_KEY'] = 'the quick brown fox jumps over the lazy dog'
#added for saving logs
def configure_logger(logger_level):
app.logger.setLevel(logger_level)
handler = logging.handlers.RotatingFileHandler('cloud.log',maxBytes=10000000,backupCount=10)
formatter = logging.Formatter('%(asctime)s - [%(levelname)s/%(module)s/%(funcName)s/%(lineno)d] - %(message)s')
handler.setFormatter(formatter)
app.logger.addHandler(handler)
configure_logger(logging.DEBUG)
|
{"/project/Authentication.py": ["/project/__init__.py"], "/project/tables.py": ["/project/__init__.py"], "/project/contacts.py": ["/project/__init__.py", "/project/tables.py"], "/app.py": ["/project/__init__.py", "/project/authentication.py"], "/project/authentication.py": ["/project/__init__.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.