Problem starting Telegram bot with pyrogram - python-3.x

Hi i am receiving an error starting a bot with nothing on it yet
I am using Pyrogram (2.0.97) and Python (3.9.6)
I didn't developed more code for this bot yet, but i want to use this library (pyrogram) and not other library, because of this decorators that has on this library
Here is the simple code
from pyrogram import Client, filters
from pyrogram.types import Message
from pyrogram.types import (
InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup
)
TELEGRAM_API_ID = "22284blablabla"
TELEGRAM_API_HASH = "186a3759fc29f394bad2700cc29ecblablabla"
TELEGRAM_BOT_TOKEN = "blablablablabla"
app = Client(
'SegBot',
api_id=TELEGRAM_API_ID,
api_hash=TELEGRAM_API_HASH,
bot_token=TELEGRAM_BOT_TOKEN
)
#app.on_message(filters.private)
async def hello(client, message):
await message.reply("Hello from Pyrogram!")
print('running!!!')
app.run()
And the error is:
running!!!
Traceback (most recent call last):
File "G:\Drives compartilhados\SEG FIS\API\TELEGRAM BOT TEST\bot_test.py", line 151, in <module>
app.run()
File "C:\Users\roberto.lins\AppData\Roaming\Python\Python39\site-packages\pyrogram\methods\utilities\run.py", line 84, in run
self.start()
return loop.run_until_complete(coroutine)
File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "C:\Users\roberto.lins\AppData\Roaming\Python\Python39\site-packages\pyrogram\methods\utilities\start.py", line 58, in start
is_authorized = await self.connect()
File "C:\Users\roberto.lins\AppData\Roaming\Python\Python39\site-packages\pyrogram\methods\auth\connect.py", line 40, in connect
await self.load_session()
File "C:\Users\roberto.lins\AppData\Roaming\Python\Python39\site-packages\pyrogram\client.py", line 586, in load_session
await Auth(
File "C:\Users\roberto.lins\AppData\Roaming\Python\Python39\site-packages\pyrogram\session\auth.py", line 254, in create
raise e
File "C:\Users\roberto.lins\AppData\Roaming\Python\Python39\site-packages\pyrogram\session\auth.py", line 89, in create
res_pq = await self.invoke(raw.functions.ReqPqMulti(nonce=nonce))
File "C:\Users\roberto.lins\AppData\Roaming\Python\Python39\site-packages\pyrogram\session\auth.py", line 67, in invoke
return self.unpack(response)
File "C:\Users\roberto.lins\AppData\Roaming\Python\Python39\site-packages\pyrogram\session\auth.py", line 60, in unpack
return TLObject.read(b)
File "C:\Users\roberto.lins\AppData\Roaming\Python\Python39\site-packages\pyrogram\raw\core\tl_object.py", line 33, in read
return cast(TLObject, objects[int.from_bytes(b.read(4), "little")]).read(b, *args)
KeyError: 0
Any help, please?

Related

Alembic loves giving me `RuntimeWarning: coroutine 'connect' was never awaited`

Switched to using SQLAlchemy from TortoiseORM and thought I'd look into Alembic to handle its migrations. After editing the env.py and alembic.ini files I still can't get alembic to generate any migrations. The error sqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called; can't call await_only() here. Was IO attempted in an unexpected place? (Background on this error at: https://sqlalche.me/e/14/xd2s) sys:1: RuntimeWarning: coroutine 'connect' was never awaited is self-explanatory but I have no idea what exactly to change.
I'm following directions in the FastAPI-Users docs but am completely lost. Any help would be appreciated.
What I've tried:
Setting run_migrations_offline() and run_migrations_online() as async
Using asyncio.run() to so I can run them
Offered a delectable sacrifice to Cthulu
models.py
import os
from typing import AsyncGenerator
from fastapi import Depends
from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.ext.declarative import DeclarativeMeta, declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import Column, String, Integer, DateTime
DATABASE_URL = os.getenv('DATABASE_URL')
Base: DeclarativeMeta = declarative_base()
class Account(Base):
__tablename__ = 'app_account'
id = Column(Integer, primary_key=True, nullable=False)
timezone = Column(String(5), default='+0800')
engine = create_async_engine(DATABASE_URL)
async_session_maker = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
async def create_db_and_tables():
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all) # noqa
async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
async with async_session_maker() as session:
yield session
alembic.ini
sqlalchemy.url = postgresql+asyncpg://foo:pass123#127.0.0.1:5432/foo
env.py
# add your model's MetaData object here
# for 'autogenerate' support
from models import Base
target_metadata = Base.metadata
Running alembic revision --autogenerate:
Traceback (most recent call last):
File "/home/dever/venv/systemapp-ne8n42/bin/alembic", line 8, in <module>
sys.exit(main())
File "/home/dever/venv/systemapp-ne8n42/lib/python3.9/site-packages/alembic/config.py", line 590, in main
CommandLine(prog=prog).main(argv=argv)
File "/home/dever/venv/systemapp-ne8n42/lib/python3.9/site-packages/alembic/config.py", line 584, in main
self.run_cmd(cfg, options)
File "/home/dever/venv/systemapp-ne8n42/lib/python3.9/site-packages/alembic/config.py", line 561, in run_cmd
fn(
File "/home/dever/venv/systemapp-ne8n42/lib/python3.9/site-packages/alembic/command.py", line 229, in revision
script_directory.run_env()
File "/home/dever/venv/systemapp-ne8n42/lib/python3.9/site-packages/alembic/script/base.py", line 569, in run_env
util.load_python_file(self.dir, "env.py")
File "/home/dever/venv/systemapp-ne8n42/lib/python3.9/site-packages/alembic/util/pyfiles.py", line 94, in load_python_file
module = load_module_py(module_id, path)
File "/home/dever/venv/systemapp-ne8n42/lib/python3.9/site-packages/alembic/util/pyfiles.py", line 110, in load_module_py
spec.loader.exec_module(module) # type: ignore
File "<frozen importlib._bootstrap_external>", line 850, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "migrations/env.py", line 77, in <module>
run_migrations_online()
File "migrations/env.py", line 65, in run_migrations_online
with connectable.connect() as connection:
File "/home/dever/venv/systemapp-ne8n42/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 3234, in connect
return self._connection_cls(self, close_with_result=close_with_result)
File "/home/dever/venv/systemapp-ne8n42/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 96, in __init__
else engine.raw_connection()
File "/home/dever/venv/systemapp-ne8n42/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 3313, in raw_connection
return self._wrap_pool_connect(self.pool.connect, _connection)
File "/home/dever/venv/systemapp-ne8n42/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 3280, in _wrap_pool_connect
return fn()
File "/home/dever/venv/systemapp-ne8n42/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 310, in connect
return _ConnectionFairy._checkout(self)
File "/home/dever/venv/systemapp-ne8n42/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 868, in _checkout
fairy = _ConnectionRecord.checkout(pool)
File "/home/dever/venv/systemapp-ne8n42/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 476, in checkout
rec = pool._do_get()
File "/home/dever/venv/systemapp-ne8n42/lib/python3.9/site-packages/sqlalchemy/pool/impl.py", line 256, in _do_get
return self._create_connection()
File "/home/dever/venv/systemapp-ne8n42/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 256, in _create_connection
return _ConnectionRecord(self)
File "/home/dever/venv/systemapp-ne8n42/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 371, in __init__
self.__connect()
File "/home/dever/venv/systemapp-ne8n42/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 666, in __connect
pool.logger.debug("Error on connect(): %s", e)
File "/home/dever/venv/systemapp-ne8n42/lib/python3.9/site-packages/sqlalchemy/util/langhelpers.py", line 70, in __exit__
compat.raise_(
File "/home/dever/venv/systemapp-ne8n42/lib/python3.9/site-packages/sqlalchemy/util/compat.py", line 208, in raise_
raise exception
File "/home/dever/venv/systemapp-ne8n42/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 661, in __connect
self.dbapi_connection = connection = pool._invoke_creator(self)
File "/home/dever/venv/systemapp-ne8n42/lib/python3.9/site-packages/sqlalchemy/engine/create.py", line 590, in connect
return dialect.connect(*cargs, **cparams)
File "/home/dever/venv/systemapp-ne8n42/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 597, in connect
return self.dbapi.connect(*cargs, **cparams)
File "/home/dever/venv/systemapp-ne8n42/lib/python3.9/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py", line 777, in connect
await_only(self.asyncpg.connect(*arg, **kw)),
File "/home/dever/venv/systemapp-ne8n42/lib/python3.9/site-packages/sqlalchemy/util/_concurrency_py3k.py", line 59, in await_only
raise exc.MissingGreenlet(
sqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called; can't call await_only() here. Was IO attempted in an unexpected place? (Background on this error at: https://sqlalche.me/e/14/xd2s)
sys:1: RuntimeWarning: coroutine 'connect' was never awaited
Any help would be greatly appreciated.
It turns out if you're using Alembic with async then you just need to initialize it using the async template.
alembic init -t async migrations
Sauce: Using Asyncio with Alembic

how to prevent ThreadedWebsocketManager (binance python api) from asyncio.exceptions.TimeoutError?

this error happens every 10 min in my code , I just do not know how to keep the ThreadedWebsocketManager alive all the time .the document did not express it clearly 。
will you good guys tell me how to fix it .
I have the same issue here. It would be of great help if someone could provide a solution to this problem.
Traceback (most recent call last):
File "test.py", line 351, in <module>
loop.run_until_complete(main())
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2800.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 616, in run_until_complete
return future.result()
File "test.py", line 257, in main
await asyncio.gather(
File "test.py", line 208, in calculate
second_pair_usdt = await client.get_symbol_ticker(symbol=second_token+FIAT_USD)
File "C:\Users\Thoma\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\binance\client.py", line 6836, in get_symbol_ticker
return await self._get('ticker/price', data=params, version=self.PRIVATE_API_VERSION)
File "C:\Users\Thoma\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\binance\client.py", line 6551, in _get
return await self._request_api('get', path, signed, version, **kwargs)
File "C:\Users\Thoma\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\binance\client.py", line 6514, in _request_api
return await self._request(method, uri, signed, **kwargs)
File "C:\Users\Thoma\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\binance\client.py", line 6495, in _request
async with getattr(self.session, method)(uri, **kwargs) as response:
File "C:\Users\Thoma\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\aiohttp\client.py", line 1117, in __aenter__
self._resp = await self._coro
File "C:\Users\Thoma\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\aiohttp\client.py", line 619, in _request
break
File "C:\Users\Thoma\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\aiohttp\helpers.py", line 656, in __exit__
raise asyncio.TimeoutError from None
asyncio.exceptions.TimeoutError

Error while creating a service using nameko for Pysnmp get_request--Attempted "nameko_entrypoints" operation on ASN.1 schema object

I am new to pysnmp and nameko. I have been assignment a work to create a service in nameko framework to perform snmp get_request using pysnmp library.
Below is the code i have tried
from pysnmp.hlapi import *
from nameko.rpc import rpc
class GreetingService(object):
name = "greeting_service"
#rpc
def getFunc(oid):
errorIndication, errorStatus, errorIndex, varBinds = next(
getCmd(SnmpEngine(),
CommunityData('public', mpModel=0),
UdpTransportTarget(('snmp.live.gambitcommunications.com', 161)),
ContextData(),
ObjectType(ObjectIdentity('SNMPv2-MIB', oid, 0)))
)
if errorIndication:
print(errorIndication)
elif errorStatus:
print('%s at %s' % (errorStatus.prettyPrint(),
errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
else:
for varBind in varBinds:
print(' = '.join([x.prettyPrint() for x in varBind]))
if __name__ == "__main__":
getFunc('sysName')
when i try to start the service using terminal with the following command
$ nameko run helloworld
I get the following error message.
syed#syed-ThinkPad-E480:~/Pysnmp$ nameko run helloworld
Traceback (most recent call last):
File "/home/syed/.local/bin/nameko", line 11, in <module>
sys.exit(main())
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/main.py", line 112, in main
args.main(args)
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/commands.py", line 110, in main
main(args)
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/run.py", line 181, in main
import_service(path)
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/run.py", line 71, in import_service
if inspect.getmembers(potential_service, is_entrypoint):
File "/usr/lib/python3.7/inspect.py", line 354, in getmembers
if not predicate or predicate(value):
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/run.py", line 35, in is_entrypoint
return hasattr(method, ENTRYPOINT_EXTENSIONS_ATTR)
File "/home/syed/.local/lib/python3.7/site-packages/pyasn1/type/base.py", line 221, in __getattr__
raise error.PyAsn1Error('Attempted "%s" operation on ASN.1 schema object' % attr)
pyasn1.error.PyAsn1Error: Attempted "nameko_entrypoints" operation on ASN.1 schema object
Error in sys.excepthook:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook
from apport.fileutils import likely_packaged, get_recent_crashes
File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
from apport.report import Report
File "/usr/lib/python3/dist-packages/apport/report.py", line 30, in <module>
import apport.fileutils
File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 23, in <module>
from apport.packaging_impl import impl as packaging
File "/usr/lib/python3/dist-packages/apport/packaging_impl.py", line 24, in <module>
import apt
File "/usr/lib/python3/dist-packages/apt/__init__.py", line 23, in <module>
import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'
Original exception was:
Traceback (most recent call last):
File "/home/syed/.local/bin/nameko", line 11, in <module>
sys.exit(main())
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/main.py", line 112, in main
args.main(args)
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/commands.py", line 110, in main
main(args)
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/run.py", line 181, in main
import_service(path)
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/run.py", line 71, in import_service
if inspect.getmembers(potential_service, is_entrypoint):
File "/usr/lib/python3.7/inspect.py", line 354, in getmembers
if not predicate or predicate(value):
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/run.py", line 35, in is_entrypoint
return hasattr(method, ENTRYPOINT_EXTENSIONS_ATTR)
File "/home/syed/.local/lib/python3.7/site-packages/pyasn1/type/base.py", line 221, in __getattr__
raise error.PyAsn1Error('Attempted "%s" operation on ASN.1 schema object' % attr)
pyasn1.error.PyAsn1Error: Attempted "nameko_entrypoints" operation on ASN.1 schema object
Please help me out to understand weather what i have tried is correct way or else it is wrong.. If so how to rectify the mistake.
Any help will be appreciable.
Thanks in advance
It has something to do with the way how nameko hooks up your code...
It seems to try looking up nameko_entrypoints attribute at all objects it can find in your module eventually running into ASN.1 schema objects (which are sacred and should not be used for anything other than blueprinting purposes).
My suggestion would be to replace from pysnmp.hlapi import * with specific imports of pysnmp classes/functions you are using in your code. That should hopefully hide fragile pieces out of nameko's sight.

Celery configuration in Django, connecting tasks to the view

I've recently configured celery to run some dummy tasks, and ran the workers through Terminal on my Mac. It all seems to run accordingly, took a while, since some of the literature out there seems to advise different configuration scenarios, but I got there anyway. Now the next step is to trigger the tasks via my view in Django. I'm using celery 1.2.26.post2
My project structure:
/MyApp
celery_tasks.py
celeryconfig.py
__init__.py
I've been following several tutorials and found this video and this video and this video very helpful to obtain an overall view of celery.
My scripts are:
celery_tasks.py
from celery import Celery
from celery.task import task
app = Celery() # Initialise the app
app.config_from_object('celeryconfig') # Tell Celery instance to use celeryconfig module
suf = lambda n: "%d%s" % (n, {1: "st", 2: "nd", 3: "rd"}.get(n if n < 20 else n % 10, "th"))
#task
def fav_doctor():
"""Reads doctor.txt file and prints out fav doctor, then adds a new
number to the file"""
with open('doctor.txt', 'r+') as f:
for line in f:
nums = line.rstrip().split()
print ('The {} doctor is my favorite'.format(suf(int(nums[0]))))
for num in nums[1:]:
print ('Wait! The {} doctor is my favorite'.format(suf(int(num))))
last_num = int(nums[-1])
new_last_num = last_num + 1
f.write(str(new_last_num) + ' ')
#task
def reverse(string):
return string[::-1]
#task
def add(x, y):
return x+y
celeryconfig.py
from datetime import timedelta
## List of modules to import when celery starts.
CELERY_IMPORTS = ('celery_tasks',)
## Message Broker (RabbitMQ) settings.
BROKER_URL = 'amqp://'
BROKER_PORT = 5672
#BROKER_TRANSPORT = 'sqlalchemy'
#BROKER_HOST = 'sqlite:///tasks.db'
#BROKER_VHOST = '/'
#BROKER_USER = 'guest'
#BROKER_PASSWORD = 'guest'
## Result store settings.
CELERY_RESULT_BACKEND = 'rpc://'
#CELERY_RESULT_DBURI = 'sqlite:///mydatabase.db'
## Worker settings
#CELERYD_CONCURRENCY = 1
#CELERYD_TASK_TIME_LIMIT = 20
#CELERYD_LOG_FILE = 'celeryd.log'
#CELERYD_LOG_LEVEL = 'INFO'
## Misc
CELERY_IGNORE_RESULT = False
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_ACCEPT_CONTENT=['json']
CELERY_TIMEZONE = 'Europe/Berlin'
CELERY_ENABLE_UTC = True
CELERYBEAT_SCHEDULE = {
'doctor-every-10-seconds': {
'task': 'celery_tasks.fav_doctor',
'schedule': timedelta(seconds=3),
},
}
__init__.py
from .celery_tasks import app as celery_app # Ensures app is always imported when Django starts so that shared_task will use this app.
__all__ = ['celery_app']
In settings.py
INSTALLED_APPS = [
...
'djcelery',
]
In my views folder, I have a specific view module, admin_scripts.py
from MyApp.celery_tasks import fav_doctor, reverse, send_email, add
#login_required
def admin_script_dashboard(request):
if request.method == 'POST':
form = Admin_Script(request.POST)
if form.is_valid():
backup_script_select = form.cleaned_data['backup_script_select']
dummy_script_select = form.cleaned_data['dummy_script_select']
print ("backup_script_select: {0}".format(backup_script_select))
print ("dummy_script_select: {0}".format(dummy_script_select))
if backup_script_select:
print ("Backup script exectuting. Please wait...")
dbackup_script_dir = str(Path.home()) + '/Software/MyOtherApp/cli-tools/dbbackup_DRAFT.py'
subprocess.call(" python {} ".format(dbackup_script_dir), shell=True)
async_result = reverse.delay('Using Celery')
print ("async_result: {0}".format(async_result))
result = reverse.AsyncResult(async_result.id)
print ("result: {0}".format(result))
print ("Something occured...")
if dummy_script_select:
print ("Dummy script exectuting. Please wait...")
dummy_script_dir = str(Path.home()) + '/Software/MyOtherApp/cli-tools/dummy.py'
subprocess.call(" python {} ".format(dummy_script_dir), shell=True)
async_result = add.delay(2, 5)
print ("async_result: {0}".format(async_result))
result = add.AsyncResult(async_result.id)
print ("result: {0}".format(result))
print ("Something occured...")
return render(request, 'MyApp/admin_scripts_db.html')
The problem occurs at the line in my admin_scripts.py file, where async_result = add.delay(2, 5) is called. Below the traceback:
[12/Jul/2018 09:23:19] ERROR [django.request:135] Internal Server Error: /MyProject/adminscripts/
Traceback (most recent call last):
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/local.py", line 309, in _get_current_object
return object.__getattribute__(self, '__thing')
AttributeError: 'PromiseProxy' object has no attribute '__thing'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/kombu/utils/__init__.py", line 323, in __get__
return obj.__dict__[self.__name__]
KeyError: 'conf'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/loaders/base.py", line 158, in _smart_import
return imp(path)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/loaders/base.py", line 112, in import_from_cwd
package=package,
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/utils/imports.py", line 101, in import_from_cwd
return imp(module, package=package)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/loaders/base.py", line 106, in import_module
return importlib.import_module(module, package=package)
File "/Users/MyMBP/anaconda3/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'celeryconfig'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/Users/MyMBP/Software/MyProject/MyProjectsite/MyProject/views/admin_scripts.py", line 44, in admin_script_dashboard
async_result = add.delay(2, 5)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/local.py", line 143, in __getattr__
return getattr(self._get_current_object(), name)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/local.py", line 311, in _get_current_object
return self.__evaluate__()
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/local.py", line 341, in __evaluate__
thing = Proxy._get_current_object(self)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/local.py", line 101, in _get_current_object
return loc(*self.__args, **self.__kwargs)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/app/base.py", line 270, in _task_from_fun
'__wrapped__': fun}, **options))()
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/app/task.py", line 201, in __new__
instance.bind(app)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/app/task.py", line 365, in bind
conf = app.conf
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/kombu/utils/__init__.py", line 325, in __get__
value = obj.__dict__[self.__name__] = self.__get(obj)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/app/base.py", line 638, in conf
return self._get_config()
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/app/base.py", line 454, in _get_config
self.loader.config_from_object(self._config_source)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/loaders/base.py", line 140, in config_from_object
obj = self._smart_import(obj, imp=self.import_from_cwd)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/loaders/base.py", line 161, in _smart_import
return symbol_by_name(path, imp=imp)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/kombu/utils/__init__.py", line 96, in symbol_by_name
module = imp(module_name, package=package, **kwargs)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/loaders/base.py", line 112, in import_from_cwd
package=package,
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/utils/imports.py", line 101, in import_from_cwd
return imp(module, package=package)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/loaders/base.py", line 106, in import_module
return importlib.import_module(module, package=package)
File "/Users/MyMBP/anaconda3/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'celeryconfig'
Numerous errors get thrown, and the traceback is very large, about 9000 lines long in total. This is just a snippet. I'm new to celery and task queueing in general, so perhaps for some of the experts out there you can pick out some very obvious mistakes from my code.
As I said, the configuration of celery is successful, and when triggering the tasks in Terminal, the tasks do what they are supposed to do. I'm building this up piece by piece, so this next step is to trigger the tasks using my view in Django (instead of being called using Terminal). Once I have figured that out, then the ultimate aim is to track the progress of a task, and report the output to the user in a separate window (.js, AJAX etc.) that shows for example the line output that you see in Console.
I read that the tasks.py (in my case celery_tasks.py) file needs to be in a django app that's registered in settings.py. Is this true?
This is not a full answer, but may help partly others who encounter a similar issue:
Basically in the celery_tasks.py there is the following:
app.config_from_object('celeryconfig')
When I trigger the workers through Terminal, this works. When I do it via my view, then the error message above can be seen. Changing this line works via the view:
app.config_from_object('MyApp.celeryconfig')
I still need to figure out why there is this discrepancy and how to resolve this so that it is indifferent whether the Tasks are called via my view or Terminal.

Tornado OAuth2 Error in get_argument() (Facebook change)

I have a problem that I can't work out. My code worked for localhost however how I have a proper domain setup i'm getting some strange problems trying to login with facebook. I have since moved to python 3.6
I have the following tornado setup code:
handlers = [
(r"/facebookAuth",FBAuth),
# other handlers...
]
# Settings dict for Application
settings = {
# static handler
# Set specific HTTP404 errors to Error404 Class
"default_handler_class": Error404,
"cookie_secret":"xxx",
"facebook_redirect_uri":"https://www.example.com/facebookAuth",
"facebook_secret":"xxx",
"facebook_app_id":"xxx",
}
class FBAuth(BaseHandler,tornado.auth.FacebookGraphMixin):
async def get(self):
if self.get_argument("code", False):
print("not code")
user = await self.get_authenticated_user(redirect_uri=self.settings["facebook_redirect_uri"],
client_id=self.settings["facebook_app_id"],
client_secret=self.settings["facebook_secret"],
code=self.get_argument("code"))
print("******")
print(user)
firstName=user["first_name"]
lastName=user["last_name"]
# set cookie and start up code
else:
print("code")
await self.authorize_redirect(redirect_uri=self.settings["facebook_redirect_uri"],
client_id=self.settings["facebook_app_id"],
scope=["email","public_profile"])
I can't work out the result of the code. It shows:
code
not code
and crashes with the following:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/tornado-4.5.dev1-py3.6-linux-x86_64.egg/tornado/web.py", line 1474, in _execute
result = yield result
File "/usr/local/lib/python3.6/site-packages/tornado-4.5.dev1-py3.6-linux-x86_64.egg/tornado/gen.py", line 1045, in run
value = future.result()
File "/usr/local/lib/python3.6/site-packages/tornado-4.5.dev1-py3.6-linux-x86_64.egg/tornado/concurrent.py", line 237, in result
raise_exc_info(self._exc_info)
File "<string>", line 3, in raise_exc_info
File "/usr/local/lib/python3.6/site-packages/tornado-4.5.dev1-py3.6-linux-x86_64.egg/tornado/gen.py", line 1051, in run
yielded = self.gen.throw(*exc_info)
File "<string>", line 6, in _wrap_awaitable
File "/home/cs/charliesays/authHandlers.py", line 13, in get
code=self.get_argument("code"))
File "<string>", line 3, in __await__
File "/usr/local/lib/python3.6/site-packages/tornado-4.5.dev1-py3.6-linux-x86_64.egg/tornado/gen.py", line 1045, in run
value = future.result()
File "/usr/local/lib/python3.6/site-packages/tornado-4.5.dev1-py3.6-linux-x86_64.egg/tornado/concurrent.py", line 237, in result
raise_exc_info(self._exc_info)
File "<string>", line 3, in raise_exc_info
File "/usr/local/lib/python3.6/site-packages/tornado-4.5.dev1-py3.6-linux-x86_64.egg/tornado/stack_context.py", line 314, in wrapped
ret = fn(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/tornado-4.5.dev1-py3.6-linux-x86_64.egg/tornado/auth.py", line 983, in _on_access_token
"access_token": args["access_token"][-1],
KeyError: 'access_token'
It seems there is a problem with the:
code=self.get_argument("code") in the call to get_authenticated_user()

Resources