I had a script that I used for checking my balances in Bittrex and now I'm trying to upgrade to the WebSocket API but I'm having a hard time since there's a lot of concepts I don't understand. This is function I'm trying to call:
from signalr_aio import Connection
from base64 import b64decode
from zlib import decompress, MAX_WBITS
import hashlib
import hmac
import json
async def create_signature(api_secret, challenge):
api_sign = hmac.new(api_secret.encode(), challenge.encode(),
hashlib.sha512).hexdigest()
return api_sign
From there I need to pass api_sign to to another function. I've tried playing around with it but I can't even get print(create_signature(api_secret, challenge)) to work. The asyncio module isn't even imported either so I can't use the information I found on how async works, and I'm assuming it's not necessary to import it.
When I try calling it the way I would a regular function I get that the coroutine was never awaited
I am the author of the example you are using. If you can't figure out how the authentication is done from the example or if its beyond your current understanding, then I suggest to use either:
Async: https://github.com/slazarov/python-bittrex-websocket-aio
Non-async: https://github.com/slazarov/python-bittrex-websocket
I am the author of both libraries
Related
I am unittesting my new librabry, which is basically database interface. Our apps use it to access our database. that means, I want to test all methods, but I do not want DB commands to be called for real. I only check if they are called with correct arguemnts.
For that purpose, I am mocking the database library. this is the actual code that DOES work:
import pytest
from unittests.conftest import PyTestConfig as Tconf
from my_lib.influx_interface import InfluxInterface
class TestInfluxInterface:
def test_connect(self, mocker):
"""
Create InfluxConnector object and call connect()
check if __init__() arguments are passed / used correctly
"""
influx_client = mocker.patch('my_lib.influx_interface.InfluxDBClient', autospec=True)
test_connector = InfluxInterface(Tconf.test_id)
# Call connect with no input (influx_client - should be called with no arguemnts
test_connector.connect()
influx_client.assert_called_once()
influx_client.reset_mock()
# Call connect with custom correct input (influx_client - should be called with custom values
test_connector.connect(Tconf.custom_conf)
influx_client.assert_called_once_with(url=Tconf.custom_conf["url"], token=Tconf.custom_conf["token"],
org=Tconf.custom_conf["org"], timeout=Tconf.custom_conf["timeout"],
debug=Tconf.custom_conf["debug"])
influx_client.reset_mock()
# Call connect with incorrect input (influx_client - should be called with default values
test_connector.connect(Tconf.default_conf)
influx_client.assert_called_once_with(url=Tconf.default_conf["url"], token=Tconf.default_conf["token"],
org=Tconf.default_conf["org"], timeout=Tconf.default_conf["timeout"],
debug=Tconf.default_conf["debug"])
Now, what I do next, is to add more methods into TestInfluxInterface class, which will be testing rest of the code. One test method for each method in my library. Thats how I usually do it.
The problem is, that there is a part of the code:
influx_client = mocker.patch('my_lib.influx_interface.InfluxDBClient', autospec=True)
test_connector = InfluxInterface(Tconf.test_id)
That will be same for every method. Thus I will be copy-pasting it over and over. As you can already see, thats not good solution.
In unittest, I would do this:
import unittest
import unittest.mock as mock
from unittests.conftest import PyTestConfig as Tconf
from my_lib.influx_interface import InfluxInterface
#mock.patch('my_lib.influx_interface.InfluxDBClient', autospec=True)
class TestInfluxInterface:
def setUp(self):
self.test_connector = InfluxInterface(Tconf.test_id)
def test_connect(self, influx_client):
"""
Create InfluxConnector object and call connect()
check if __init__() arguments are passed / used correctly
"""
# Call connect with no input (influx_client - should be called with no arguemnts
self.test_connector.connect()
influx_client.assert_called_once()
Than in each method, I would use self.test_connector to call whatever method I want to test, and check if it called correct influx_client method, with correct parameters.
However, we are moving from unittest to pytest. And while I am wrapping my head around pytest docs, reading stuff here and there, fixtures, mockers, etc..I cannot find out how to do this correctly.
I want to organize my firebase cloud functions in specific files,
and currently, I have these 3:
index.ts
crypto.ts
webscrape.ts
Inside of these files, I have functions that use specific dependencies that are needed nowhere else.
For example, in crypto.ts I need the crypto-js package to encrypt some user data and store it into the database.
So I am importing it like so:
import * as CryptoJS from "crypto-js";
as advised in https://firebase.google.com/docs/functions/handle-dependencies#typescript
On the other hand, when I try to import puppeteer into webscrape.ts like this:
import * as puppeteer from"puppeteer-extra";
then calling puppeteer.launch(); gives me an error :
Property 'launch' does not exist on type 'typeof import("c:/Users/username/Desktop/project/firebasee/functions/node_modules/puppeteer-extra/dist/index")'
and it only works when I do const puppeteer = require("puppeteer-extra");
What's the difference here?
My goal is to keep the dependencies of each functions and file/module as small as possible because I assume that this will also keep the size of each function container small (Is that even true?)
I didn't want to import everything to index.ts even when I trigger a function, that doesn't use this dependency at all.
So what is the correct way of handling these dependencies?
Thanks!
The following import will get the default export from that package.
import puppeteer from "puppeteer-extra"
I looked for the default export in the Github repository and found that.
const defaultExport: PuppeteerExtra = (() => {
return new PuppeteerExtra(...requireVanillaPuppeteer())
})()
export default defaultExport
They have mentioned both ES6 import and require methods here.
// javascript import
const puppeteer = require('puppeteer-extra')
// typescript/es6 module import
import puppeteer from 'puppeteer-extra'
You can read more about import on MDN.
I'm researching Sanic as we're looking for alternatives to our flask-based rest services. I'm intriguied by the async nature of sanic, but I know that we'll bump into a lot of code that simply won't support async (we use a ton of boto3 and also some ORMs on top of DynamoDB for example, none of which support awaiting).
So: I need to find the cleanest way of being able to run synchronous code inside an async framework like Sanic. In python 3.7 there's the asyncio.create_task call which I'm finding interesting.
Wondering if this would be a possible way to go:
main.py:
#default boilerplate sanic code excluded for brevity
from app_logic import AppLogic
#app.route("/")
async def test(request):
task = await asyncio.create_task(AppLogic.sync_request('https://stuff.com'))
return json({"hello": "world", 'status_code': task.status_code})
app_logic.py:
import requests
class AppLogic(object):
#staticmethod
async def sync_request(url='https://myurl.com'):
#Some non-async library/code thingy
print('requesting the thing')
return requests.get(url)
This seems to work, and the the returned task object is a regular requests response.
However, I have no idea if this is "safe" - eg I'm not sure how I can investigate the event loop and verify that it's not blocking in any way. I'm sure there's also other reasons for this approach being completely dumb, so lay them on me :-)
I am having strange issues with Typescript when I import things from a file which exports them. Sometimes I will export a function, then import it to another file, then I use the function and it is not a function anymore. When I define the function in the same file, all of a sudden the function is a function?!?!?
Why would a function stop being a function when it is exported? I have had similar problems with classes too.
The hard part of this issue is I can't recreate a simple example because it only happens when I am using some kind of higher level package.
For example, I had a similar issue with sequelize-typescript here: my github issue with typescript-sequelize
Below is some codes showing off the basic issue I'm having with one of the decorators from InversifyJS.
container.ts
import {fluentProvide} from "inversify-binding-decorators";
export const provideSingleton = (identifier: any) => {
return fluentProvide(identifier)
.inSingletonScope()
.done(true);
};
test.service.ts
import {provideSingleton} from './container'
#provideSingleton(TYPES.TEST)
export default class TestService {}
The strangest thing is when I put the provideSingleton in the same file as the TestService, everything works!?!?!
Basically to recreate the issue, simply follow the example from here: inversify-binding-decorators - Using #provideFluent multiple times. However there is an issue with the example, so please see this issue: fluentProvide example needed. The above provideSingleton reflects the changes from that issue. Then you simply import the provideSingleton function from another file instead of defining it in the same like in the example.
Can anyone explain to me what I'm missing? Why oh why would certain exported items not bee seen as the type they are? Is there a step I'm not seeing that NodeJS takes to make the item actually exported and therefore different? Can I force the function to resolve as a function so it can be used as such?
ENV:
NodeJS: 10.9.0
Typescript: 3.0.1
Mac: 10.13.16
So it looks like you can get issues like this when NodeJS can't handle a recursive import. I'm not exactly sure how to check you are getting this error other than your symptoms are like what I stated above. Basically the recursion caused my function to not load and therefore undefined is not a function.
It would be easy to notice if you had code like so:
a.ts
import B from './b';
export default class A extends B {}
b.ts
import A from './a';
export default class B extends A {}
In my case, I think my function provideSingleton did not like the file I put it in because of some conflicting code in the file, which all I had was:
import {Container} from 'inversify';
import "reflect-metadata";
import {fluentProvide} from "inversify-binding-decorators";
const container = new Container();
function ProvideSingleton(identifier: any) {
return fluentProvide(identifier)
.inSingletonScope()
.done(true);
}
export {container, ProvideSingleton}
In the end, if this issue comes up, try another file for your function and pay good attention to how the order of the loading happens. Although NodeJS handles recursive imports most of the time, you can still trip it out.
When trying to connect a factory I want it to periodically try to reconnect if it fails to do so. I tried it with a code looking like that:
def reconnect():
print("this sucks")
reactor.connectTCP("localhost", 6667, factory2)
factory2 = pb.PBClientFactory()
factory2.clientConnectionFailed(reconnect(), "reasons")
reactor.connectTCP("localhost", 6667, factory2)
If I run this code it prints "this sucks" just once, although calling the connectTCP method with factory2 as parameter again. How should I go about implementing the desired behavior?
clientConnectionFailed is a method that is called by Twisted on a factory when a connection attempt fails. The usage in your example is nonsensical.
See ReconnectingClientFactory for one solution:
from twisted.internet.protocol import ReconnectingClientFactory
from twisted.internet import reactor
from yourlib import YourProtocol
factory = ReconnectingClientFactory()
factory.protocol = YourProtocol
reactor.connectTCP(host, port, factory)
reactor.run()
However, this does not combine well with PB due to the use of a custom factory class to support PB. This is just one of many reasons to avoid using PB at all.
A more recently introduced solution is ClientService:
from twisted.application.internet import ClientService
from twisted.internet.endpoints import HostnameEndpoint
from yourlib import YourFactory
factory = YourFactory()
service = ClientService(
HostnameEndpoint(reactor, host, port),
YourFactory(),
)
service.startService()
reactor.run()
Note I've skipped over correct "service" usage here for brevity; see the Twisted
service documentation for details on correct usage.