I'm trying to connect to a ble device with bleak that uses a passkey.
async def connect(self, address):
print("Connecting to device...")
async with BleakClient(address) as client:
response = await client.connect()
print(response)
i'm using above code. The device displays the passkey to enter and windows displays the add a device message to input the code, but i get a timeout error from asyncio and never recieve the response to python.
Traceback (most recent call last):
File "C:\Users\halmelam\PycharmProjects\read_passcode\main.py", line 137, in <module>
asyncio.run(pair.connect(device.address))
File "C:\Users\halmelam\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\halmelam\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "C:\Users\halmelam\PycharmProjects\read_passcode\main.py", line 95, in connect
response = await client.connect()
File "C:\Users\halmelam\.virtualenvs\read_passcode\lib\site-packages\bleak\backends\winrt\client.py", line 249, in connect
await asyncio.wait_for(event.wait(), timeout=timeout)
File "C:\Users\halmelam\AppData\Local\Programs\Python\Python39\lib\asyncio\tasks.py", line 494, in wait_for
raise exceptions.TimeoutError() from exc
asyncio.exceptions.TimeoutError
How do I get the response and how can i send the passkey via python?
Related
I'm trying to connect as a client to my websocket, but yet every time I try this error comes up, I've tried literally everything but the result is always the same
(with other languages, for example NodeJS, I can connect without problems)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/root/api/.venv/lib/python3.9/site-packages/websockets/legacy/client.py", line 138, in read_http_response
status_code, reason, headers = await read_response(self.reader)
File "/root/api/.venv/lib/python3.9/site-packages/websockets/legacy/http.py", line 122, in read_response
raise EOFError("connection closed while reading HTTP status line") from exc
EOFError: connection closed while reading HTTP status line
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/root/api/.venv/lib/python3.9/site-packages/websockets/legacy/client.py", line 666, in __await_impl__
await protocol.handshake(
File "/root/api/.venv/lib/python3.9/site-packages/websockets/legacy/client.py", line 326, in handshake
status_code, response_headers = await self.read_http_response()
File "/root/api/.venv/lib/python3.9/site-packages/websockets/legacy/client.py", line 144, in read_http_response
raise InvalidMessage("did not receive a valid HTTP response") from exc
websockets.exceptions.InvalidMessage: did not receive a valid HTTP response
code:
import websockets
from websockets import client
async def receiver(ws):
for message in ws:
print(f"{message}")
async for websocket in client.connect('wss://localhost:8777/password/AAAAAA/1/175/'):
try:
print('connecting')
except websockets.ConnectionClosed:
print('error')
I've been banging my head against my keyboard for a day now, so I'm giving up and asking for help.
I've got a working consumer using confluence kafka, but I need to make it run as a coroutine so I can get things working with FastAPI. I really wanted to try out AIOKafka for this, but for the life of me, I can't get it to work with a self-signed certificate (this is in our dev env).
Here is the working config for my confluence kafka consumer:
conf = {
"bootstrap.servers": "10.142.252.214:9093",
"group.id": "myConsumerID",
"security.protocol": "SASL_SSL",
"sasl.username": kafkaUser,
"sasl.password": kafkaPass,
"sasl.mechanisms": "PLAIN",
"enable.ssl.certificate.verification": "False",
"on_commit": commit_completed,
"heartbeat.interval.ms": "1000",
"socket.connection.setup.timeout.ms": "10000",
"auto.offset.reset": "earliest"
}
Here is the code I'm trying to use for AIOKafka
async def consume():
cert = "../foo/cert/certificate.pem"
key = "../foo/cert/key.pem"
context2 = ssl.create_default_context()
context2.load_cert_chain(certfile=cert, keyfile=key)
context2.check_hostname = False
context2.verify_mode = CERT_NONE
#context2.ssl_cafile="../foo/cert/CARoot.pem"
context2.ssl_certfile = "cert.pem"
context2.ssl_keyfile = "key.pem"
context2.ssl_password = kafkaKey
context2.ssl_keystore_type = "PEM"
consumer = AIOKafkaConsumer(
'TopicA', 'TopicB',
bootstrap_servers="10.142.252.214:9093",
group_id="myConsumerGroup",
sasl_plain_username="kafkaUser",
sasl_plain_password="kafkaPass",
sasl_mechanism="PLAIN",
security_protocol="SASL_SSL",
ssl_context=context2)
await consumer.start()
try:
# Consume messages
async for msg in consumer:
print("consumed: ", msg.topic, msg.partition, msg.offset,
msg.key, msg.value, msg.timestamp)
finally:
# Will leave consumer group; perform autocommit if enabled.
await consumer.stop()
When I try to run this, I just get the most cryptic errors ever and I can't make any sense on where to start trying to figure out what's wrong.
$ python test-main.py
Traceback (most recent call last):
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/conn.py", line 375, in _on_read_task_error
read_task.result()
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/conn.py", line 518, in _read
resp = await reader.readexactly(4)
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/asyncio/streams.py", line 706, in readexactly
raise exceptions.IncompleteReadError(incomplete, n)
asyncio.exceptions.IncompleteReadError: 0 bytes read on a total of 4 expected bytes
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/myUser/scripts/ansible-hello-world/test-main.py", line 165, in <module>
asyncio.run(consume())
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/asyncio/base_events.py", line 646, in run_until_complete
return future.result()
File "/Users/myUser/scripts/ansible-hello-world/test-main.py", line 155, in consume
await consumer.start()
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/consumer/consumer.py", line 346, in start
await self._client.bootstrap()
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/client.py", line 210, in bootstrap
bootstrap_conn = await create_conn(
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/conn.py", line 96, in create_conn
await conn.connect()
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/conn.py", line 234, in connect
await self._do_sasl_handshake()
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/conn.py", line 314, in _do_sasl_handshake
auth_bytes = await self._send_sasl_token(
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/asyncio/tasks.py", line 445, in wait_for
return fut.result()
kafka.errors.KafkaConnectionError: KafkaConnectionError: Connection at 10.142.252.214:9093 closed
Unclosed AIOKafkaConsumer
consumer: <aiokafka.consumer.consumer.AIOKafkaConsumer object at 0x107338670>
I'm making a discord.py bot and I want to create a async function to send a message. However, a I want to call this function from a non-async function.
This is the discord client initialization
import requests
import json
from datetime import datetime
import discord
import asyncio
from discord.ext import commands
import firebase_admin
from firebase_admin import credentials, firestore
intents = discord.Intents.all()
client = commands.Bot(command_prefix='&', intents=intents)
This is my send_message function
async def msg(msg,channel):
await channel.send(msg)
This is the non-async function that's calling msg()
def checkStart(doc_snapshot,changes,read_time):
for change in changes:
if change.type.name == 'ADDED' or change.type.name == 'MODIFIED':
anaDoc = change.document.to_dict()
if anaDoc['start'] == True:
asyncio.run(msg('Game started!',main_channel[change.document.reference.parent.parent.id]))
print(change.document.reference.parent.parent.id)
Traceback
Thread-ConsumeBidirectionalStream caught unexpected exception Timeout context manager should be used inside a task and will exit.
Traceback (most recent call last):
File "C:\Users\Chico\AppData\Local\Programs\Python\Python39\lib\site-packages\google\api_core\bidi.py", line 657, in _thread_main
self._on_response(response)
File "C:\Users\Chico\AppData\Local\Programs\Python\Python39\lib\site-packages\google\cloud\firestore_v1\watch.py", line 462, in on_snapshot
meth(proto)
File "C:\Users\Chico\AppData\Local\Programs\Python\Python39\lib\site-packages\google\cloud\firestore_v1\watch.py", line 392, in _on_snapshot_target_change_no_change
self.push(change.read_time, change.resume_token)
File "C:\Users\Chico\AppData\Local\Programs\Python\Python39\lib\site-packages\google\cloud\firestore_v1\watch.py", line 568, in push
self._snapshot_callback(keys, appliedChanges, read_time)
File "c:\Users\Chico\Documents\newCartola\main.py", line 221, in checkStart
asyncio.run(msg('Jogo iniciado!',main_channel[change.document.reference.parent.parent.id]))
File "C:\Users\Chico\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\Chico\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "c:\Users\Chico\Documents\newCartola\main.py", line 213, in msg
await channel.send(msg)
File "C:\Users\Chico\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\abc.py", line 904, in send
data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
File "C:\Users\Chico\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 185, in request
async with self.__session.request(method, url, **kwargs) as r:
File "C:\Users\Chico\AppData\Local\Programs\Python\Python39\lib\site-packages\aiohttp\client.py", line 1012, in __aenter__
self._resp = await self._coro
File "C:\Users\Chico\AppData\Local\Programs\Python\Python39\lib\site-packages\aiohttp\client.py", line 426, in _request
with timer:
File "C:\Users\Chico\AppData\Local\Programs\Python\Python39\lib\site-packages\aiohttp\helpers.py", line 579, in __enter__
raise RuntimeError('Timeout context manager should be used '
RuntimeError: Timeout context manager should be used inside a task
I am writing my API using aiohttp, asycpg and asyncpgsa.
I create my application:
async def create_app():
app = web.Application(client_max_size=1024 ** 2 * 70)
Then I execute these lines:
async def on_start(app):
app['db'] = asyncpgsa.create_pool(dsn="postgresql://127.0.0.1:5432/backend")
async def on_shutdown(app):
app['db'].close()
app.on_startup.append(on_start)
app.on_cleanup.append(on_shutdown)
In general, in the example where I got it from, it is written like this:
app['db'] = await asyncpgsa.create_pool(dsn="postgresql://127.0.0.1:5432/backend")
But if I write like this, then an error is thrown "ConnectionRefusedError: [Errno 10061] Connect call failed ('127.0.0.1', 5432)"
But that's okay. Now, when the user visits the URL I need, this function should be triggered:
async def post(request):
async with request.app["db"].acquire() as conn:
query = select([datab.post])
result = await conn.fetch(query)
The datab file says this:
from sqlalchemy import Table, Text, VARCHAR, Integer, MetaData, Column
meta = MetaData()
post = Table(
"post", meta,
Column("id", Integer, primary_key=True),
Column("title", VARCHAR, nullable=True),
Column("body", Text))
But when I go to the URL I want, the site gives me "500 Internal Server Error Server got itself in trouble "
And Pycharm: Error handling request asyncpg.exceptions._base.InterfaceError: pool is not initialized
Very little has been written on the Internet about asyncpg (sa), so I will be immensely grateful if you can help me fix the problem.
I'll add my own code.
main.py
from aiohttp import web
from demo import create_app
import argparse
import sqlalchemy
import asyncpgsa
async def post_handler(request):
body1 = await request.json()
print(body1)
return web.json_response(data=body1, status=201)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--host", help="IPv4/IPv6 address API server would listen on", default="0.0.0.0")
parser.add_argument('--port', help='TCP port API server would listen on', default=8080, type=int)
args = parser.parse_args()
app = create_app()
web.run_app(app, host=args.host, port=args.port)
if __name__ == '__main__':
main()
app.py
from aiohttp import web
import asyncpgsa
from .routes import setup_routes
async def on_start(app):
app['db'] = asyncpgsa.create_pool(dsn="postgresql://127.0.0.1:5432/backendyandex")
async def on_shutdown(app):
app['db'].close()
async def create_app():
app = web.Application(client_max_size=1024 ** 2 * 70)
setup_routes(app)
app.on_startup.append(on_start)
app.on_cleanup.append(on_shutdown)
return app
If you write
app['db'] = await asyncpgsa.create_pool(dsn="postgresql://127.0.0.1:5432/backend")
Then an error occurs
unhandled exception during asyncio.run() shutdown
task: <Task finished coro=<_run_app() done, defined at C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\web.py:287> exception=ConnectionRefusedError(10061, "Connect call failed ('127.0.0.1', 5432)")>
Traceback (most recent call last):
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\web.py", line 508, in run_app
loop.run_until_complete(main_task)
File "C:\Users\lisgl\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 587, in run_until_complete
return future.result()
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\web.py", line 319, in _run_app
await runner.setup()
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\web_runner.py", line 275, in setup
self._server = await self._make_server()
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\web_runner.py", line 375, in _make_server
await self._app.startup()
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\web_app.py", line 416, in startup
await self.on_startup.send(self)
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\signals.py", line 34, in send
await receiver(*args, **kwargs) # type: ignore
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\demo\app.py", line 11, in on_start
app['db'] = await asyncpgsa.create_pool(dsn="postgresql://127.0.0.1:5432/backendyandex")
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\pool.py", line 407, in _async__init__
await self._initialize()
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\pool.py", line 435, in _initialize
await first_ch.connect()
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\pool.py", line 127, in connect
self._con = await self._pool._get_new_connection()
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\pool.py", line 482, in _get_new_connection
**self._connect_kwargs)
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\connection.py", line 1997, in connect
max_cacheable_statement_size=max_cacheable_statement_size,
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\connect_utils.py", line 677, in _connect
raise last_error
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\connect_utils.py", line 668, in _connect
record_class=record_class,
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\connect_utils.py", line 634, in _connect_addr
tr, pr = await compat.wait_for(connector, timeout=timeout)
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\compat.py", line 103, in wait_for
return await asyncio.wait_for(fut, timeout)
File "C:\Users\lisgl\AppData\Local\Programs\Python\Python37\lib\asyncio\tasks.py", line 442, in wait_for
return fut.result()
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\connect_utils.py", line 547, in _create_ssl_connection
host, port)
File "C:\Users\lisgl\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 962, in create_connection
raise exceptions[0]
File "C:\Users\lisgl\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 949, in create_connection
await self.sock_connect(sock, address)
File "C:\Users\lisgl\AppData\Local\Programs\Python\Python37\lib\asyncio\selector_events.py", line 473, in sock_connect
return await fut
File "C:\Users\lisgl\AppData\Local\Programs\Python\Python37\lib\asyncio\selector_events.py", line 503, in _sock_connect_cb
raise OSError(err, f'Connect call failed {address}')
ConnectionRefusedError: [Errno 10061] Connect call failed ('127.0.0.1', 5432)
site.py
from aiohttp import web
from sqlalchemy import select
from . import datab
async def post(request):
async with request.app["db"].acquire() as conn:
query = select([datab.post])
result = await conn.fetch(query)
return web.Response(body=str(result))
And here is the error that crashes if you go to the URL I need:
Error handling request
Traceback (most recent call last):
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\web_protocol.py", line 422, in _handle_request
resp = await self._request_handler(request)
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\web_app.py", line 499, in _handle
resp = await handler(request)
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\demo\site.py", line 13, in post
async with request.app["db"].acquire() as conn:
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\pool.py", line 785, in __aenter__
self.connection = await self.pool._acquire(self.timeout)
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\pool.py", line 622, in _acquire
self._check_init()
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\pool.py", line 745, in _check_init
raise exceptions.InterfaceError('pool is not initialized')
asyncpg.exceptions._base.InterfaceError: pool is not initialized
Your dsn is incorrect, so you can't connect to your database.
postgres://user:pass#host:port/database?option=value is the correct format. You forgot the user and the password.
Also asyncpgsa.create_pool() should be awaited, if not. You don't get the error, because you only assign a coroutine to the variable app['db']. So the connection pool is also not created.
Your second error (from site.py) is caused by not initizalising the connection pool.
More about that you can find in the documentation of asyncpg here (because asyncpgsa's connection pool is based on asyncpg's connection pool).
try to run a basic scripts that adds members to a telegram group over pythoneverywhere server. I installed the main package which is telethon in the server. but i am getting the error in the image below. what am i not doing right?
error message is given below
21:02 ~/Villians TV/Villians5/TeleGram-Scraper-master $ python3 villians5.py
Traceback (most recent call last):
File "villians5.py", line 17, in <module>
client.connect()
File "/home/somti13/.local/lib/python3.8/site-packages/telethon/sync.py", line 39, in syncified
return loop.run_until_complete(coro)
File "/usr/lib/python3.8/asyncio/base_events.py", line 608, in run_until_complete
return future.result()
File "/home/somti13/.local/lib/python3.8/site-packages/telethon/client/telegrambaseclient.py", line 472, in connect
if not await self._sender.connect(self._connection(
File "/home/somti13/.local/lib/python3.8/site-packages/telethon/network/mtprotosender.py", line 125, in connect
await self._connect()
File "/home/somti13/.local/lib/python3.8/site-packages/telethon/network/mtprotosender.py", line 250, in _connect
raise ConnectionError('Connection to Telegram failed {} time(s)'.format(self._retries))
ConnectionError: Connection to Telegram failed 5 time(s)
The mtproto connection type for telegram does not work for free accounts on PythonAnywhere. Only http(s) connections out of PythonAnywhere will work for free accounts.