APScheduler Look up object error - apscheduler

APScheduler (3.3.1) py2.7
I use this code to do my job When I use Memory as job store it can work well but I have too many job and my Memory in server is limit so I change SQLAlchemyJobStore as job store but I got the Lookup error. How to solve it.
Code:
def script(indicator, strategy_name, real_time=False):
# Solve No handlers could be found for logger “apscheduler.scheduler
import logging
logging.basicConfig(level=logging.ERROR,
format='%(name)-12s %(asctime)s %(levelname)-8s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S')
try:
job_defaults = {
'coalesce': False,
'max_instances': 1,
"misfire_grace_time": config.real_time_script_interval + 5,
}
executors = {
'default': ThreadPoolExecutor(60),
}
jobstores = {
"default": SQLAlchemyJobStore(url='sqlite:///jobs.sqlite')
}
scheduler = BlockingScheduler(daemonic=True, jobstores=jobstores, job_defaults=job_defaults,
executors=executors)
module = __import__("%s.%s" % (indicator, strategy_name), fromlist=[strategy_name])
if real_time:
for st in module.strategy:
scheduler.add_job(st.run, "interval", seconds=config.real_time_script_interval)
else:
for st in module.strategy:
# 计算最近的下一个准点时间
start_time = _recent_time(st.run_period)
scheduler.add_job(st.run, "interval", **start_time)
scheduler.start()
except Exception as e:
logger.get("run-log").error(error_msg())
Error:
apscheduler.jobstores.default Thu, 06 Apr 2017 10:50:32 ERROR Unable to restore job "d100a4b24e2d49c3ad51305fd846e5f5" -- removing it
Traceback (most recent call last):
File "/Users/wyx/bitcoin_workspace/fibo-strategy/.env/lib/python2.7/site-packages/apscheduler/jobstores/sqlalchemy.py", line 135, in _get_jobs
jobs.append(self._reconstitute_job(row.job_state))
File "/Users/wyx/bitcoin_workspace/fibo-strategy/.env/lib/python2.7/site-packages/apscheduler/jobstores/sqlalchemy.py", line 122, in _reconstitute_job
job.__setstate__(job_state)
File "/Users/wyx/bitcoin_workspace/fibo-strategy/.env/lib/python2.7/site-packages/apscheduler/job.py", line 260, in __setstate__
self.func = ref_to_obj(self.func_ref)
File "/Users/wyx/bitcoin_workspace/fibo-strategy/.env/lib/python2.7/site-packages/apscheduler/util.py", line 277, in ref_to_obj
raise LookupError('Error resolving reference %s: error looking up object' % ref)
LookupError: Error resolving reference base.strategy:Strategy.run: error looking up object
apscheduler.jobstores.default Thu, 06 Apr 2017 10:50:32 ERROR Unable to restore job "2602167cd3c745c2b0764a2b63da1a3a" -- removing it
Traceback (most recent call last):
File "/Users/wyx/bitcoin_workspace/fibo-strategy/.env/lib/python2.7/site-packages/apscheduler/jobstores/sqlalchemy.py", line 135, in _get_jobs
jobs.append(self._reconstitute_job(row.job_state))
File "/Users/wyx/bitcoin_workspace/fibo-strategy/.env/lib/python2.7/site-packages/apscheduler/jobstores/sqlalchemy.py", line 122, in _reconstitute_job
job.__setstate__(job_state)
File "/Users/wyx/bitcoin_workspace/fibo-strategy/.env/lib/python2.7/site-packages/apscheduler/job.py", line 260, in __setstate__
self.func = ref_to_obj(self.func_ref)
File "/Users/wyx/bitcoin_workspace/fibo-strategy/.env/lib/python2.7/site-packages/apscheduler/util.py", line 277, in ref_to_obj
raise LookupError('Error resolving reference %s: error looking up object' % ref)
LookupError: Error resolving reference base.strategy:Strategy.run: error looking up object
apscheduler.jobstores.default Thu, 06 Apr 2017 10:50:32 ERROR Unable to restore job "3eb917670e7642b8848a165268df8913" -- removing it
Traceback (most recent call last):
File "/Users/wyx/bitcoin_workspace/fibo-strategy/.env/lib/python2.7/site-packages/apscheduler/jobstores/sqlalchemy.py", line 135, in _get_jobs
jobs.append(self._reconstitute_job(row.job_state))
File "/Users/wyx/bitcoin_workspace/fibo-strategy/.env/lib/python2.7/site-packages/apscheduler/jobstores/sqlalchemy.py", line 122, in _reconstitute_job
job.__setstate__(job_state)
File "/Users/wyx/bitcoin_workspace/fibo-strategy/.env/lib/python2.7/site-packages/apscheduler/job.py", line 260, in __setstate__
self.func = ref_to_obj(self.func_ref)
File "/Users/wyx/bitcoin_workspace/fibo-strategy/.env/lib/python2.7/site-packages/apscheduler/util.py", line 277, in ref_to_obj
raise LookupError('Error resolving reference %s: error looking up object' % ref)
LookupError: Error resolving reference base.strategy:Strategy.run: error looking up object
Supplementary instruction for Alex Grönholm's question here because it is hard to say in comment
In base/strategy_util.py:
base_strategy is some classes which inherit the BaseStrategy class in base/strategy.py . The BaseStrategy has its run method
def _strategy(base_strategy, minute, ticker_table_format):
class Strategy(base_strategy):
run_period = minute
def _init_params(self):
self.ticker_table_format = ticker_table_format
return Strategy()
def _create_strategy(base_strategy, minute_list=ALL_MINUTE):
strategy_list = []
for minute in minute_list:
for ticker_table_format in const.TICKER_TABLE_FORMAT.ALL:
st = _strategy(base_strategy, minute, ticker_table_format)
strategy_list.append(st)
return strategy_list
def ma_strategy(base_strategy):
return _create_strategy(base_strategy)
In MA/touch_avg.py:
MA_TOUCH_AVG inherit the BaseStrategy class
from base.strategy import MA_TOUCH_AVG
from base.strategy_util import ma_strategy
strategy = ma_strategy(MA_TOUCH_AVG)
And then I use click to call the strategy like python run_strategy.py run MA touch_avg
In run_strategy.py:
#cli.command()
#click.argument('indicator')
#click.argument('strategy_name')
def run(indicator, strategy_name):
""" run indicator strategy_name """
real_time_strategy_name = ["touch_avg", "limit"]
util.script(indicator, strategy_name,
real_time=strategy_name in real_time_strategy_name)

The reason you're having this problem is because you create a class dynamically, in a function. APScheduler stores the reference to the scheduled function as module:varname. How is the scheduler expected to find a class that you're making on the fly in a function?

Related

send file to serial port in python

i am trying to send the file below '105.8k' to my energy meter.
i am using the xmodem example from pypi but i get the following error:
Traceback (most recent call last):
File "C:\Py\mainpy.py", line 68, in <module>
status = modem.send(f, retry=3)
File "C:\Users\admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\xmodem\__init__.py", line 270, in send
char = self.getc(1)
File "C:\py\mainpy.py", line 62, in getc
return ser.read(size) or None
AttributeError: 'str' object has no attribute 'read'
the code i use:
### send file to port###
ser = serialPortCombobox.get().split(" ")[0]
def getc(size, timeout=1):
return ser.read(size) or None
def putc(data, timeout=1):
return ser.write(data)
modem = XMODEM(getc, putc)
f = open('105.8k', 'rb')
status = modem.send(f, retry=3)
ser.close()
stream.close()
thank you for your help.

Error downloading PDF files

I have the following (simplified) code:
import os
import scrapy
class TestSpider(scrapy.Spider):
name = 'test_spider'
start_urls = ['http://www.pdf995.com/samples/pdf.pdf', ]
def parse(self, response):
save_path = 'test'
file_name = 'test.pdf'
self.save_page(response, save_path, file_name)
def save_page(self, response, save_dir, file_name):
os.makedirs(save_dir, exist_ok=True)
with open(os.path.join(save_dir, file_name), 'wb') as afile:
afile.write(response.body)
When i run it, I get this error:
[scrapy.core.scraper] ERROR: Error downloading <GET http://www.pdf995.com/samples/pdf.pdf>
Traceback (most recent call last):
File "C:\Python36\lib\site-packages\twisted\internet\defer.py", line 1301, in _inlineCallbacks
result = g.send(result)
File "C:\Python36\lib\site-packages\scrapy\core\downloader\middleware.py", line 43, in process_request
defer.returnValue((yield download_func(request=request,spider=spider)))
File "C:\Python36\lib\site-packages\twisted\internet\defer.py", line 1278, in returnValue
raise _DefGen_Return(val)
twisted.internet.defer._DefGen_Return: <200 http://www.pdf995.com/samples/pdf.pdf>
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python36\lib\site-packages\twisted\internet\defer.py", line 1301, in _inlineCallbacks
result = g.send(result)
File "C:\Python36\lib\site-packages\scrapy\core\downloader\middleware.py", line 53, in process_response
spider=spider)
File "C:\Python36\lib\site-packages\scrapy_beautifulsoup\middleware.py", line 16, in process_response
return response.replace(body=str(BeautifulSoup(response.body, self.parser)))
File "C:\Python36\lib\site-packages\scrapy\http\response\__init__.py", line 79, in replace
return cls(*args, **kwargs)
File "C:\Python36\lib\site-packages\scrapy\http\response\__init__.py", line 20, in __init__
self._set_body(body)
File "C:\Python36\lib\site-packages\scrapy\http\response\__init__.py", line 55, in _set_body
"Response body must be bytes. "
TypeError: Response body must be bytes. If you want to pass unicode body use TextResponse or HtmlResponse.
Do I need to introduce a middleware or something to handle this? This looks like it should be valid, at least by other examples.
Note: at the moment I'm not using a pipeline because there in my real spider I have a lot of checks on whether the related item has been scraped, validating if this pdf belongs to the item, and checking a custom name of a pdf to see if it was downloaded. And as mentioned, many samples did what I'm doing here so I thought it would be easier and work.
The issue because of your own scrapy_beautifulsoup\middleware.py which is trying to replace the return response.replace(body=str(BeautifulSoup(response.body, self.parser))).
You need to correct that and that should fix the issue

Apache Beam Dataflow: 'NoneType' object has no attribute 'parts'

I'm trying to write a pipeline to read a stream from pubsub and write it to bigquery using google cloud dataflow with apache beam.
I have this code:
import apache_beam as beam
from apache_beam.transforms.window import FixedWindows
topic = 'projects/???/topics/???'
table = '???.???'
gcs_path = "gs://???"
with beam.Pipeline(runner="DataflowRunner", argv=[
"--project", "???",
"--staging_location", ("%s/staging_location" % gcs_path),
"--temp_location", ("%s/temp" % gcs_path),
"--output", ("%s/output" % gcs_path)
]) as p:
(p
| 'winderow' >> beam.WindowInto(FixedWindows(60))
| 'hello' >> beam.io.gcp.pubsub.ReadStringsFromPubSub(topic)
| 'hello2' >> beam.io.Write(beam.io.gcp.bigquery.BigQuerySink(table))
)
p.run().wait_until_finish()
But I'm getting this error when running it:
No handlers could be found for logger "oauth2client.contrib.multistore_file"
ERROR:root:Error while visiting winderow
Traceback (most recent call last):
File ".\main.py", line 20, in <module>
p.run().wait_until_finish()
File "C:\ProgramData\Anaconda2\lib\site-packages\apache_beam\pipeline.py", line 339, in run
return self.runner.run(self)
File "C:\ProgramData\Anaconda2\lib\site-packages\apache_beam\runners\dataflow\dataflow_runner.py", line 296, in run
super(DataflowRunner, self).run(pipeline)
File "C:\ProgramData\Anaconda2\lib\site-packages\apache_beam\runners\runner.py", line 138, in run
pipeline.visit(RunVisitor(self))
File "C:\ProgramData\Anaconda2\lib\site-packages\apache_beam\pipeline.py", line 367, in visit
self._root_transform().visit(visitor, self, visited)
File "C:\ProgramData\Anaconda2\lib\site-packages\apache_beam\pipeline.py", line 710, in visit
part.visit(visitor, pipeline, visited)
File "C:\ProgramData\Anaconda2\lib\site-packages\apache_beam\pipeline.py", line 713, in visit
visitor.visit_transform(self)
File "C:\ProgramData\Anaconda2\lib\site-packages\apache_beam\runners\runner.py", line 133, in visit_transform
self.runner.run_transform(transform_node)
File "C:\ProgramData\Anaconda2\lib\site-packages\apache_beam\runners\runner.py", line 176, in run_transform
return m(transform_node)
File "C:\ProgramData\Anaconda2\lib\site-packages\apache_beam\runners\dataflow\dataflow_runner.py", line 526, in run_ParDo
input_step = self._cache.get_pvalue(transform_node.inputs[0])
File "C:\ProgramData\Anaconda2\lib\site-packages\apache_beam\runners\runner.py", line 252, in get_pvalue
self._ensure_pvalue_has_real_producer(pvalue)
File "C:\ProgramData\Anaconda2\lib\site-packages\apache_beam\runners\runner.py", line 226, in _ensure_pvalue_has_real_producer
while real_producer.parts:
AttributeError: 'NoneType' object has no attribute 'parts'
Is this a problem with the code or configuration?
How can I get it working?
I don't have experience with windowed pipelines yet but for what I understand from the concept, the windows are supposed to be applied to your input data and not as a pipeline setup.
This being the case, your code probably should be:
with beam.Pipeline(runner="DataflowRunner", argv=[
"--project", "???",
"--staging_location", ("%s/staging_location" % gcs_path),
"--temp_location", ("%s/temp" % gcs_path),
"--output", ("%s/output" % gcs_path)
]) as p:
(p
| 'hello' >> beam.io.gcp.pubsub.ReadStringsFromPubSub(topic)
| 'winderow' >> beam.WindowInto(FixedWindows(60))
| 'hello2' >> beam.io.Write(beam.io.gcp.bigquery.BigQuerySink(table))
)
p.run().wait_until_finish()
The official repo have some samples on windowed operations as well.

mnist_with_summaries.py error: 'Graph' object has no attribute 'SerializeToString'

When I try to run mnist_with_summaries.py I get the following error:
Traceback (most recent call last):
File "/home/rob/tf_from_source/tensorflow/examples/tutorials/mnist/mnist_with_summaries.py", line 110, in
tf.app.run()
File "/home/rob/.virtualenvs/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/platform/default/_app.py", line 30, in run
sys.exit(main(sys.argv))
File "/home/rob/tf_from_source/tensorflow/examples/tutorials/mnist/mnist_with_summaries.py", line 85, in main
writer = tf.train.SummaryWriter(FLAGS.summaries_dir, sess.graph)
File "/home/rob/.virtualenvs/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/training/summary_io.py", line 104, in init
self.add_graph(graph_def)
File "/home/rob/.virtualenvs/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/training/summary_io.py", line 168, in add_graph
graph_bytes = graph_def.SerializeToString()
AttributeError: 'Graph' object has no attribute 'SerializeToString'
I'm also seeing this error on some of my own code when I try to generate a tensorboard graph. Any ideas about the problem and solution would be appreciated.
Looks like the answer was provided here. I rolled back to the r0.7 branch and the problem was resolved.

Unknown report type: webkit Error when printing report?

I been with the following error for the past few days and I can't get a clue how to proceed.
The full error is:
2015-01-26 17:29:25,162 21218 ERROR myodoo openerp.service.report: Exception: Unknown report type: webkit
Traceback (most recent call last):
File "/opt/odoo/openerp/service/report.py", line 93, in go
result, format = openerp.report.render_report(cr, uid, ids, object, datas, context)
File "/opt/odoo/openerp/report/__init__.py", line 40, in render_report
return registry['ir.actions.report.xml'].render_report(cr, uid, ids, name, data, context)
File "/opt/odoo/openerp/api.py", line 237, in wrapper
return old_api(self, *args, **kwargs)
File "/opt/odoo/openerp/addons/base/ir/ir_actions.py", line 155, in render_report
return new_report.create(cr, uid, res_ids, data, context)
File "/opt/odoo/openerp/report/report_sxw.py", line 391, in create
raise NotImplementedError(_('Unknown report type: %s') % report_type)
NotImplementedError: Unknown report type: webkit
2015-01-26 17:29:25,397 21218 ERROR myodoo openerp.addons.web.controllers.main: An exception occured during an http request
Traceback (most recent call last):
File "/opt/odoo/addons/web/controllers/main.py", line 69, in wrap
return f(*args, **kwargs)
File "/opt/odoo/addons/web/controllers/main.py", line 1576, in index
request.session.db, request.session.uid, request.session.password, report_id)
File "/opt/odoo/openerp/http.py", line 807, in proxy_method
result = dispatch_rpc(self.service_name, method, args)
File "/opt/odoo/openerp/http.py", line 100, in dispatch_rpc
result = dispatch(method, params)
File "/opt/odoo/openerp/service/report.py", line 34, in dispatch
res = fn(db, uid, *params)
File "/opt/odoo/openerp/service/report.py", line 141, in exp_report_get
return _check_report(report_id)
File "/opt/odoo/openerp/service/report.py", line 119, in _check_report
raise openerp.osv.orm.except_orm(exc.message, exc.traceback)
except_orm: (u'Unknown report type: webkit', (<type 'exceptions.NotImplementedError'>, NotImplementedError(u'Unknown report type: webkit',), <traceback object at 0x7fa2f9af8dd0>))
I been developing on my module so I thought it was something I touched, but even when I install previous working versions of the module I still get the same error.
That makes me feel that there might be a change in the system but I checked if wkhtmltopdf is working and everything seems normal.
Any clue on where to look will be really appreciated.
Thanks!
It can be that you don't have the Webkit report engine installed.
Check if the report_webkit module is installed.