I have a new model in a custom module .
in this module i want to do a backorder on a order (1 product with 2 of quantity)
I want to do this backorder when a field is changed on a form
When i do that i have this error :
Traceback (most recent call last): File
"/usr/lib/python2.7/dist-packages/odoo/http.py", line 642, in
_handle_exception
return super(JsonRequest, self)._handle_exception(exception) File "/usr/lib/python2.7/dist-packages/odoo/http.py", line 684, in
dispatch
result = self._call_function(**self.params) File "/usr/lib/python2.7/dist-packages/odoo/http.py", line 334, in
_call_function
return checked_call(self.db, *args, **kwargs) File "/usr/lib/python2.7/dist-packages/odoo/service/model.py", line 101, in
wrapper
return f(dbname, *args, **kwargs) File "/usr/lib/python2.7/dist-packages/odoo/http.py", line 327, in
checked_call
result = self.endpoint(*a, **kw) File "/usr/lib/python2.7/dist-packages/odoo/http.py", line 942, in call
return self.method(*args, **kw) File "/usr/lib/python2.7/dist-packages/odoo/http.py", line 507, in
response_wrap
response = f(*args, **kw) File "/usr/lib/python2.7/dist-packages/odoo/addons/web/controllers/main.py",
line 895, in call_kw
return self._call_kw(model, method, args, kwargs) File "/usr/lib/python2.7/dist-packages/odoo/addons/web/controllers/main.py",
line 887, in _call_kw
return call_kw(request.env[model], method, args, kwargs) File "/usr/lib/python2.7/dist-packages/odoo/api.py", line 689, in call_kw
return call_kw_multi(method, model, args, kwargs) File "/usr/lib/python2.7/dist-packages/odoo/api.py", line 680, in
call_kw_multi
result = method(recs, *args, **kwargs) File "/usr/lib/python2.7/dist-packages/odoo/models.py", line 5535, in
onchange
value = record[name] File "/usr/lib/python2.7/dist-packages/odoo/models.py", line 5269, in
getitem
return self._fields[key].get(self, type(self)) File "/usr/lib/python2.7/dist-packages/odoo/fields.py", line 930, in
get
value = record._cache[self] File "/usr/lib/python2.7/dist-packages/odoo/models.py", line 5620, in
getitem
value = self._recs.env.cache[field][self._recs.id] KeyError: <odoo.models.NewId object at 0x7f312b74d150>
Here is my model :
class PickingProcess(models.Model):
_inherit = "mail.thread"
_name = 'picking.process'
_description = "picking process ecoparc"
input_action = fields.Char("Action" ,store=True)
#api.one
#api.depends('input_action')
def _compute_imput_action2(self):
ctx = dict(self._context or {})
_logger.error(ctx)
pic = self.env['stock.picking'].browse(4910)
for pack in pic.pack_operation_ids:
pack.qty_done = 1
backOrderModel = self.env['stock.backorder.confirmation']
backorderObj = backOrderModel.create(
{'pick_id': 4910})
backorderObj._process(cancel_backorder=False)
return
Do you have an idea why i have this error and how to fix it please?
Thanks a lot
Thomas
Related
I can't figure out what's wrong in my code:
import threading
from telegram.ext import ApplicationBuilder
import asyncio
import time
botApp = ApplicationBuilder().token(token="******:******").build()
def main():
* computation stuff *
while True
asyncio.run(send_msg()) * send result of computention 2 times*
time.sleep(5)
async def send_msg():
print("sending")
await botApp.bot.sendMessage(
chat_id="********",
text='example',
parse_mode= 'markdown'
)
if __name__ == '__main__':
x = threading.Thread(target=main()).start
botApp.run_polling()
that raise this error:
Traceback (most recent call last):
File "/Library/Python/3.8/site-packages/anyio/streams/tls.py", line 130, in _call_sslobject_method
result = func(*args)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/ssl.py", line 888, in read
** v = self._sslobj.read(len)
ssl.SSLWantReadError: The operation did not complete (read) (_ssl.c:2607)
During handling of the above exception, another exception occurred:
**
Traceback (most recent call last):
File "/Library/Python/3.8/site-packages/telegram/request/_baserequest.py", line 274, in _request_wrapper
code, payload = await self.do_request(
File "/Library/Python/3.8/site-packages/telegram/request/_httpxrequest.py", line 199, in do_request
res = await self._client.request(
File "/Library/Python/3.8/site-packages/httpx/_client.py", line 1533, in request
return await self.send(request, auth=auth, follow_redirects=follow_redirects)
File "/Library/Python/3.8/site-packages/httpx/_client.py", line 1620, in send
response = await self._send_handling_auth(
File "/Library/Python/3.8/site-packages/httpx/_client.py", line 1648, in _send_handling_auth
response = await self._send_handling_redirects(
File "/Library/Python/3.8/site-packages/httpx/_client.py", line 1685, in _send_handling_redirects
response = await self._send_single_request(request)
File "/Library/Python/3.8/site-packages/httpx/_client.py", line 1722, in _send_single_request
response = await transport.handle_async_request(request)
File "/Library/Python/3.8/site-packages/httpx/_transports/default.py", line 353, in handle_async_request
resp = await self._pool.handle_async_request(req)
File "/Library/Python/3.8/site-packages/httpcore/_async/connection_pool.py", line 253, in handle_async_request
raise exc
File "/Library/Python/3.8/site-packages/httpcore/_async/connection_pool.py", line 237, in handle_async_request
response = await connection.handle_async_request(request)
File "/Library/Python/3.8/site-packages/httpcore/_async/connection.py", line 90, in handle_async_request
return await self._connection.handle_async_request(request)
File "/Library/Python/3.8/site-packages/httpcore/_async/http2.py", line 144, in handle_async_request
raise exc
File "/Library/Python/3.8/site-packages/httpcore/_async/http2.py", line 112, in handle_async_request
status, headers = await self._receive_response(
File "/Library/Python/3.8/site-packages/httpcore/_async/http2.py", line 229, in _receive_response
event = await self._receive_stream_event(request, stream_id)
File "/Library/Python/3.8/site-packages/httpcore/_async/http2.py", line 260, in _receive_stream_event
await self._receive_events(request, stream_id)
File "/Library/Python/3.8/site-packages/httpcore/_async/http2.py", line 281, in _receive_events
events = await self._read_incoming_data(request)
File "/Library/Python/3.8/site-packages/httpcore/_async/http2.py", line 341, in _read_incoming_data
raise exc
File "/Library/Python/3.8/site-packages/httpcore/_async/http2.py", line 327, in _read_incoming_data
data = await self._network_stream.read(self.READ_NUM_BYTES, timeout)
File "/Library/Python/3.8/site-packages/httpcore/backends/asyncio.py", line 34, in read
return await self._stream.receive(max_bytes=max_bytes)
File "/Library/Python/3.8/site-packages/anyio/streams/tls.py", line 195, in receive
data = await self._call_sslobject_method(self._ssl_object.read, max_bytes)
File "/Library/Python/3.8/site-packages/anyio/streams/tls.py", line 137, in _call_sslobject_method
data = await self.transport_stream.receive()
File "/Library/Python/3.8/site-packages/anyio/_backends/_asyncio.py", line 1264, in receive
self._transport.resume_reading()
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/asyncio/selector_events.py", line 798, in resume_reading
self._add_reader(self._sock_fd, self._read_ready)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/asyncio/selector_events.py", line 744, in _add_reader
self._loop._add_reader(fd, callback, *args)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/asyncio/selector_events.py", line 256, in _add_reader
self._check_closed()
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/asyncio/base_events.py", line 508, in _check_closed
** raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
The above exception was the direct cause of the following exception:**
Traceback (most recent call last):
File "./test.py", line 26, in <module>
threading.Thread(target=main())
File "./test.py", line 12, in main
asyncio.run(send_msg())
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/asyncio/runners.py", line 43, in run
return loop.run_until_complete(main)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "./test.py", line 18, in send_msg
await botApp.bot.sendMessage(
File "/Library/Python/3.8/site-packages/telegram/ext/_extbot.py", line 2598, in send_message
return await super().send_message(
File "/Library/Python/3.8/site-packages/telegram/_bot.py", line 331, in decorator
result = await func(*args, **kwargs) # skipcq: PYL-E1102
File "/Library/Python/3.8/site-packages/telegram/_bot.py", line 760, in send_message
return await self._send_message(
File "/Library/Python/3.8/site-packages/telegram/ext/_extbot.py", line 488, in _send_message
result = await super()._send_message(
File "/Library/Python/3.8/site-packages/telegram/_bot.py", line 512, in _send_message
result = await self._post(
File "/Library/Python/3.8/site-packages/telegram/_bot.py", line 419, in _post
return await self._do_post(
File "/Library/Python/3.8/site-packages/telegram/ext/_extbot.py", line 306, in _do_post
return await super()._do_post(
File "/Library/Python/3.8/site-packages/telegram/_bot.py", line 450, in _do_post
return await request.post(
File "/Library/Python/3.8/site-packages/telegram/request/_baserequest.py", line 165, in post
result = await self._request_wrapper(
File "/Library/Python/3.8/site-packages/telegram/request/_baserequest.py", line 290, in _request_wrapper
**raise NetworkError(f"Unknown error in HTTP implementation: {repr(exc)}") from exc
telegram.error.NetworkError: Unknown error in HTTP implementation: RuntimeError('Event loop is closed')**
Is there anyone who can help me?
I wanted to create a main function to do some computational stuff every 5 seconds and advise me sending a message using a telegram bot... For this reason I created a thread to run the main function while the main thread run the telegram API
I am trying to write simple code in shared memory in multiprocessing. I am getting errors. Please help me to solve this.
import multiprocessing
import time
def calc_square(numbers, q):
for n in numbers:
q.put(n*n)
def calc_cube(numbers, q):
for n in numbers:
q.put(n*n*n)
if __name__ == "__main__":`enter code here`
numbers = [2,3,5,7,9,10]
numbers2 = [2,3,5,7,9,10]
q = multiprocessing.Queue()
q2 = multiprocessing.Queue()
p = multiprocessing.Process(target=calc_square, args=(numbers,q))
p1 = multiprocessing.Process(target=calc_square, args=(numbers2,q2))
time.sleep(0.05)
p.start()
p1.start()
p.join()
p1.join()
while q.empty() is False:
print(q.get())
while q2.empty() is False:
print(q2.get())
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\Hello\AppData\Local\Programs\Python\Python310\lib\multiprocessing\spawn.py", line 116, in spawn_main
exitcode = _main(fd, parent_sentinel)
File "C:\Users\Hello\AppData\Local\Programs\Python\Python310\lib\multiprocessing\spawn.py", line 126, in _main
self = reduction.pickle.load(from_parent)
AttributeError: Can't get attribute 'calc_square' on <module '__main__' (built-in)>
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\Hello\AppData\Local\Programs\Python\Python310\lib\multiprocessing\spawn.py", line 116, in spawn_main
exitcode = _main(fd, parent_sentinel)
File "C:\Users\Hello\AppData\Local\Programs\Python\Python310\lib\multiprocessing\spawn.py", line 126, in _main
self = reduction.pickle.load(from_parent)
AttributeError: Can't get attribute 'calc_square' on <module '__main__' (built-in)>
I am trying this simple code and below error comes while getting uid
url = 'http://localhost:8071'
db = "db8aaa_19sep22"
username = "admin"
password = "Admin#347"
common = xmlrpc.client.ServerProxy('{}/xmlrpc/2/common'.format(url))
common.version()
uid = common.authenticate(db, username, password, {})
Getting below error
File "/home/oem/odoo/odoo-14/odoo/addons/base/models/ir_http.py", line 237, in _dispatch
result = request.dispatch()
File "/home/oem/odoo/odoo-14/odoo/http.py", line 684, in dispatch
result = self._call_function(**self.params)
File "/home/oem/odoo/odoo-14/odoo/http.py", line 360, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/home/oem/odoo/odoo-14/odoo/service/model.py", line 94, in wrapper
return f(dbname, *args, **kwargs)
File "/home/oem/odoo/odoo-14/odoo/http.py", line 348, in checked_call
result = self.endpoint(*a, **kw)
File "/home/oem/odoo/odoo-14/odoo/http.py", line 913, in __call__
return self.method(*args, **kw)
File "/home/oem/odoo/odoo-14/odoo/http.py", line 532, in response_wrap
response = f(*args, **kw)
File "/home/oem/odoo/odoo-14/odoo/addons/web/controllers/main.py", line 1393, in call_button
action = self._call_kw(model, method, args, kwargs)
File "/home/oem/odoo/odoo-14/odoo/addons/web/controllers/main.py", line 1381, in _call_kw
return call_kw(request.env[model], method, args, kwargs)
File "/home/oem/odoo/odoo-14/odoo/api.py", line 396, in call_kw
result = _call_kw_multi(method, model, args, kwargs)
File "/home/oem/odoo/odoo-14/odoo/api.py", line 383, in _call_kw_multi
result = method(recs, *args, **kwargs)
File "/home/oem/odoo/14foraaa/migration_scripts/model/leads.py", line 55, in get_leads_rpc
uid = common.authenticate(db, username, password, {})
File "/usr/lib/python3.7/xmlrpc/client.py", line 1112, in __call__
return self.__send(self.__name, args)
File "/usr/lib/python3.7/xmlrpc/client.py", line 1452, in __request
verbose=self.__verbose
File "/usr/lib/python3.7/xmlrpc/client.py", line 1154, in request
return self.single_request(host, handler, request_body, verbose)
File "/usr/lib/python3.7/xmlrpc/client.py", line 1170, in single_request
return self.parse_response(resp)
File "/usr/lib/python3.7/xmlrpc/client.py", line 1342, in parse_response
return u.close()
File "/usr/lib/python3.7/xmlrpc/client.py", line 656, in close
raise Fault(**self._stack[0])
Exception
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/oem/odoo/odoo-14/odoo/http.py", line 640, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/home/oem/odoo/odoo-14/odoo/http.py", line 316, in _handle_exception
raise exception.with_traceback(None) from new_cause
xmlrpc.client.Fault: <Fault 1: 'Traceback (most recent call last):\n File "/opt/odoo/openerp/service/wsgi_server.py", line 75, in xmlrpc_return\n result = openerp.http.dispatch_rpc(service, method, params)\n File "/opt/odoo/openerp/http.py", line 115, in dispatch_rpc\n result = dispatch(method, params)\n File "/opt/odoo/openerp/service/common.py", line 26, in dispatch\n return fn(*params)\n File "/opt/odoo/openerp/service/common.py", line 38, in exp_authenticate\n return res_users.authenticate(db, login, password, user_agent_env)\n File "/opt/odoo/openerp/addons/user_logs/users.py", line 26, in authenticate\n uid = super(res_users, self).authenticate(db, login, password, user_agent_env)\n File "/opt/odoo/openerp/addons/base/res/res_users.py", line 464, in authenticate\n uid = self._login(db, login, password)\n File "/opt/odoo/openerp/addons/base/res/res_users.py", line 427, in _login\n self.check_credentials(cr, user_id, password)\n File "/opt/odoo/openerp/api.py", line 268, in wrapper\n return old_api(self, *args, **kwargs)\n File "/opt/odoo/openerp/api.py", line 372, in old_api\n result = method(recs, *args, **kwargs)\n File "/opt/odoo/openerp/addons/otp_auth/models/res_users.py", line 24, in check_credentials\n totp = request.session.get(\'otploginobj\')\n File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 338, in __getattr__\n return getattr(self._get_current_object(), name)\n File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 297, in _get_current_object\n return self.__local()\n File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 132, in _lookup\n raise RuntimeError(\'object unbound\')\nRuntimeError: object unbound\n'>```
Hi I have following code
#commands.command(name="playing", aliases=["np"])
async def playing_command(self, ctx, name: t.Optional[str]):
player = self.get_player(ctx)
name = name or player.queue.current_track.title
async with ctx.typing():
async with aiohttp.request("GET", LYRICS_URL + name, headers={}) as r:
#if not 200 <= r.status <= 299:
#raise NoLyricsFound
data = await r.json()
if not player.is_playing:
raise PlayerIsAlreadyPaused
embed = discord.Embed(
title="Wird gespielt",
colour=ctx.author.colour,
timestamp=dt.datetime.utcnow(),
)
embed.set_thumbnail(url=data["thumbnail"]["genius"])
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.avatar_url)
embed.add_field(name="Track title", value=player.queue.current_track.title, inline=False)
embed.add_field(name="Artist", value=player.queue.current_track.author, inline=False)
position = divmod(player.position, 60000)
length = divmod(player.queue.current_track.length, 60000)
embed.add_field(
name="Position",
value=f"{int(position[0])}:{round(position[1]/1000):02}/{int(length[0])}:{round(length[1]/1000):02}",
inline=False
)
await ctx.send(embed=embed)
But when I run this and the bot cant find a Thumbnail I get the key Error 'thumbnail'
So I tried this
#playing_command.error
async def playing_command(self, ctx, name: t.Optional[str]):
player = self.get_player(ctx)
name = name or player.queue.current_track.title
async with ctx.typing():
async with aiohttp.request("GET", LYRICS_URL + name, headers={}) as r:
#if not 200 <= r.status <= 299:
#raise NoLyricsFound
data = await r.json()
if not player.is_playing:
raise PlayerIsAlreadyPaused
embed = discord.Embed(
title="Wird gespielt",
colour=ctx.author.colour,
timestamp=dt.datetime.utcnow(),
)
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.avatar_url)
embed.add_field(name="Track title", value=player.queue.current_track.title, inline=False)
embed.add_field(name="Artist", value=player.queue.current_track.author, inline=False)
position = divmod(player.position, 60000)
length = divmod(player.queue.current_track.length, 60000)
embed.add_field(
name="Position",
value=f"{int(position[0])}:{round(position[1]/1000):02}/{int(length[0])}:{round(length[1]/1000):02}",
inline=False
)
await ctx.send(embed=embed)
But with this I get errors like
_ClientEventTask exception was never retrieved
future: <ClientEventTask state=finished event=on_message coro=<bound method MusicBot.on_message of <bot.bot.MusicBot object at 0x0000022FEF05E6A0>> exception=CommandInvokeError('Command raised an exception: TypeError: can only concatenate str (not "CommandInvokeError") to str')>
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\user\Desktop\Neuer Ordner\MusicBot\bot\cogs\music.py", line 637, in playing_command
embed.set_thumbnail(url=data["thumbnail"]["genius"])
KeyError: 'thumbnail'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'thumbnail'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 71, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\user\Desktop\Neuer Ordner\MusicBot\bot\cogs\music.py", line 658, in error_command
async with aiohttp.request("GET", LYRICS_URL + name, headers={}) as r:
TypeError: can only concatenate str (not "CommandInvokeError") to str
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 348, in _run_event
await self.on_error(event_name, *args, **kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\user\Desktop\Neuer Ordner\MusicBot\bot\bot.py", line 68, in on_message
await self.process_commands(msg)
File "C:\Users\user\Desktop\Neuer Ordner\MusicBot\bot\bot.py", line 64, in process_commands
await self.invoke(ctx)
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 943, in invoke
await ctx.command.dispatch_error(ctx, exc)
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 422, in dispatch_error
await injected(cog, ctx, error)
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 77, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: can only concatenate str (not "CommandInvokeError") to str
How to fix this
I just want when the thumbnail function fails that the bot send a embed without thumbnail
To check if a key exists in a dict you can use the in operator.
>>> "key" in {"key": "value"}
True
So just put an if around the set_thumbnail line.
if "thumbnail" in data and "genius" in data["thumbnail"]:
embed.set_thumbnail(url=data["thumbnail"]["genius"])
If the if's condition is False it won't run set_thumbnail so it won't add one, like you wanted.
I got this error where I have no clue where it come from and where to start to debug. I do not understand this error at all. I'll just post my code here. I utilized multithreading in my code to periodically save the tweets on separate files. My program will work fine for maybe over 10 days, and then throw me this error message. Maybe twitter reset my connection?
import twitter
import json
import time
from tqdm import tqdm
import string
from datetime import timedelta, datetime
import threading
import os
consumer_key = '*'
consumer_secret = '*'
access_token_key = '*'
access_token_secret = '*'
api = twitter.Api(consumer_key = consumer_key,\
consumer_secret = consumer_secret,\
access_token_key = access_token_key,\
access_token_secret = access_token_secret)
os.chdir('*/social_media/streamed_tweets')
#multiThreading class and functions starts here
class timerThread(threading.Thread):
def __init__(self, threadID, name, stoptime, stopevent): #remember to change args accordingly
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.stoptime = stoptime
self.stopevent = stopevent
def run(self):
print("Starting " + self.name)
twiTimer(self.stoptime, self.stopevent)
print("Exiting " + self.name)
class streamerThread(threading.Thread):
def __init__(self, threadID, name, keywords, stop): #remember to change args accordingly
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.keywords = keywords
self.stop = stop
def run(self):
print("Starting " + self.name)
twiStream(self.keywords, self.stop)
print("Exiting " + self.name)
def twiTimer(stop_time, stop_event):
while True:
now1 = datetime.now()
t = str(now1.timetz())
if t[:8] == stop_time: #make it t[:8] for daily loop
stop_event.set()
print('stop triggered')
time.sleep(1) #wait to pass the '00' time
time.sleep(0.1)
def twiStream(keywords, stop_event):
while True:
stream = api.GetStreamFilter(track = keywords, languages=['en'], filter_level = None)
now2 = datetime.now()
filename = str(now2.date())+'.txt' #change this to date() for daily loop
f = open(filename, 'w+')
stop_event.clear() #reset the event
print(now2)
with tqdm() as pbar:
while not stop_event.is_set():
counter = 2
for tweet in stream:
if counter <= 0:
break
f.write(json.dumps(tweet))
f.write('\n')
pbar.update()
counter -= 1
f.close()
time.sleep(0.5)
#multiThreading class and functions ends here
def main():
keywords = ['*']
stop = threading.Event()
stop_at = '00:00:00' #make it '00:00:00' for daily loop
#count = 10
thread1 = timerThread(1, 'timerThread', stop_at, stop)
thread2 = streamerThread(2, 'streamerThread', keywords, stop)
thread1.start()
thread2.start()
print("Exiting Main Thread")
if __name__ == "__main__":
main()
Here is the full error message:
Exception in thread streamerThread:
Traceback (most recent call last):
File "/home/abe/anaconda3/lib/python3.6/site-packages/urllib3/contrib/pyopenssl.py", line 285, in recv_into
return self.connection.recv_into(*args, **kwargs)
File "/home/abe/anaconda3/lib/python3.6/site-packages/OpenSSL/SSL.py", line 1814, in recv_into
self._raise_ssl_error(self._ssl, result)
File "/home/abe/anaconda3/lib/python3.6/site-packages/OpenSSL/SSL.py", line 1631, in _raise_ssl_error
raise SysCallError(errno, errorcode.get(errno))
OpenSSL.SSL.SysCallError: (104, 'ECONNRESET')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/abe/anaconda3/lib/python3.6/site-packages/urllib3/response.py", line 331, in _error_catcher
yield
File "/home/abe/anaconda3/lib/python3.6/site-packages/urllib3/response.py", line 637, in read_chunked
self._update_chunk_length()
File "/home/abe/anaconda3/lib/python3.6/site-packages/urllib3/response.py", line 569, in _update_chunk_length
line = self._fp.fp.readline()
File "/home/abe/anaconda3/lib/python3.6/socket.py", line 586, in readinto
return self._sock.recv_into(b)
File "/home/abe/anaconda3/lib/python3.6/site-packages/urllib3/contrib/pyopenssl.py", line 290, in recv_into
raise SocketError(str(e))
OSError: (104, 'ECONNRESET')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/abe/anaconda3/lib/python3.6/site-packages/requests/models.py", line 749, in generate
for chunk in self.raw.stream(chunk_size, decode_content=True):
File "/home/abe/anaconda3/lib/python3.6/site-packages/urllib3/response.py", line 461, in stream
for line in self.read_chunked(amt, decode_content=decode_content):
File "/home/abe/anaconda3/lib/python3.6/site-packages/urllib3/response.py", line 665, in read_chunked
self._original_response.close()
File "/home/abe/anaconda3/lib/python3.6/contextlib.py", line 99, in __exit__
self.gen.throw(type, value, traceback)
File "/home/abe/anaconda3/lib/python3.6/site-packages/urllib3/response.py", line 349, in _error_catcher
raise ProtocolError('Connection broken: %r' % e, e)
urllib3.exceptions.ProtocolError: ('Connection broken: OSError("(104, \'ECONNRESET\')",)', OSError("(104, 'ECONNRESET')",))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/abe/anaconda3/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "streamer.py", line 48, in run
twiStream(self.keywords, self.stop)
File "streamer.py", line 72, in twiStream
for tweet in stream:
File "/home/abe/anaconda3/lib/python3.6/site-packages/twitter/api.py", line 4575, in GetStreamFilter
for line in resp.iter_lines():
File "/home/abe/anaconda3/lib/python3.6/site-packages/requests/models.py", line 793, in iter_lines
for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode):
File "/home/abe/anaconda3/lib/python3.6/site-packages/requests/models.py", line 752, in generate
raise ChunkedEncodingError(e)
requests.exceptions.ChunkedEncodingError: ('Connection broken: OSError("(104, \'ECONNRESET\')",)', OSError("(104, 'ECONNRESET')",))