I am trying to run the first example:Get Campaigns,through the python sdk(ads api,not adwords).
I got an error that did not describe how to solve the problem: google.api_core.exceptions.DeadlineExceeded: 504 Deadline Exceeded
"""This example illustrates how to get all campaigns.
To add campaigns, run add_campaigns.py.
"""
from __future__ import absolute_import
import argparse
import six
import sys
import google.ads.google_ads.client
_DEFAULT_PAGE_SIZE = 10
def main(client, customer_id, page_size):
ga_service = client.get_service('GoogleAdsService', version='v1')
query = ('SELECT campaign.id, campaign.name FROM campaign '
'ORDER BY campaign.id')
results = ga_service.search(customer_id, query=query, page_size=page_size)
try:
for row in results:
print('Campaign with ID %d and name "%s" was found.'
% (row.campaign.id.value, row.campaign.name.value))
except google.ads.google_ads.errors.GoogleAdsException as ex:
print('Request with ID "%s" failed with status "%s" and includes the '
'following errors:' % (ex.request_id, ex.error.code().name))
for error in ex.failure.errors:
print('\tError with message "%s".' % error.message)
if error.location:
for field_path_element in error.location.field_path_elements:
print('\t\tOn field: %s' % field_path_element.field_name)
sys.exit(1)
if __name__ == '__main__':
google_ads_client = (google.ads.google_ads.client.GoogleAdsClient
.load_from_storage("google-ads.yaml"))
main(google_ads_client, "customer_id", _DEFAULT_PAGE_SIZE)
and got the error:
Traceback (most recent call last):
File "c:/PythonProjects/google_ads_api_test/google-ads-python-master/google-ads-python-master/examples/basic_operations/get_campaigns.py", line 68, in <module>
main(google_ads_client, "customer_id", _DEFAULT_PAGE_SIZE)
File "c:/PythonProjects/google_ads_api_test/google-ads-python-master/google-ads-python-master/examples/basic_operations/get_campaigns.py", line 40, in main
for row in results:
File "C:\Anaconda3\lib\site-packages\google\api_core\page_iterator.py", line 204, in _items_iter
for page in self._page_iter(increment=False):
File "C:\Anaconda3\lib\site-packages\google\api_core\page_iterator.py", line 235, in _page_iter
page = self._next_page()
File "C:\Anaconda3\lib\site-packages\google\api_core\page_iterator.py", line 526, in _next_page
response = self._method(self._request)
File "C:\Anaconda3\lib\site-packages\google\api_core\gapic_v1\method.py", line 143, in __call__
return wrapped_func(*args, **kwargs)
File "C:\Anaconda3\lib\site-packages\google\api_core\retry.py", line 270, in retry_wrapped_func
on_error=on_error,
File "C:\Anaconda3\lib\site-packages\google\api_core\retry.py", line 179, in retry_target
return target()
File "C:\Anaconda3\lib\site-packages\google\api_core\timeout.py", line 214, in func_with_timeout
return func(*args, **kwargs)
File "C:\Anaconda3\lib\site-packages\google\api_core\grpc_helpers.py", line 59, in error_remapped_callable
six.raise_from(exceptions.from_grpc_error(exc), exc)
File "<string>", line 3, in raise_from
google.api_core.exceptions.DeadlineExceeded: 504 Deadline Exceeded
Is something wrong with the call?
I believe you simply need to increase your timeout value in your configuration.
Related
My task (check payment status in Sberbank. If no capture - retry check):
from ....celeryconf import app
from . import client as sberbank
from ...models import Payment, Transaction
#app.task(bind=True, default_retry_delay=60, time_limit=1200)
def check_status_sberbank_task(self, order_id, connection_params):
sberbank_client = sberbank.Client(auth=(connection_params['login'], connection_params['password']),
sandbox=connection_params['sandbox_mode'])
response = sberbank_client.payment.get_status(order_id=order_id)
txn = Transaction.objects.get(token=order_id)
if response['actionCode'] == 0:
txn.is_success = True
txn.save()
payment = Payment.objects.get(pk=txn.payment_id)
payment.charge_status = 'fully-charged'
payment.captured_amount = payment.total
payment.save()
return 'Success pay on Sberbank for ' + str(order_id)
else:
self.retry(countdown=60)
in log file I have:
ERROR celery.app.trace Task
saleor.payment.gateways.sberbank.tasks.check_status_sberbank_task[bb384815-4a5b-49d7-bc29-114707f072b1]
raised unexpected: RuntimeError('Never call result.get() within a
task!\nSee
http://docs.celeryq.org/en/latest/userguide/tasks.html#task-synchronous-subtasks\n',)
[PID:26869:Thread-825]
Traceback (most recent call last): File
"/home/korolev/saleor/lib/python3.6/site-packages/celery/app/trace.py",
line 385, in trace_task
R = retval = fun(*args, **kwargs) File "/home/korolev/saleor/saleor/payment/gateways/sberbank/tasks.py", line
26, in check_status_sberbank_task
self.retry(countdown=60) File "/home/korolev/saleor/lib/python3.6/site-packages/celery/app/task.py",
line 715, in retry
S.apply().get() File "/home/korolev/saleor/lib/python3.6/site-packages/celery/result.py",
line 1015, in get
assert_will_not_block() File "/home/korolev/saleor/lib/python3.6/site-packages/celery/result.py",
line 41, in assert_will_not_block
raise RuntimeError(E_WOULDBLOCK)
RuntimeError: Never call result.get() within a task! See
http://docs.celeryq.org/en/latest/userguide/tasks.html#task-synchronous-subtasks
How do I fix this error?
I'm trying to write a small python 3 utility script that checks to see if a file exists on my server.
So I have the code below that has a big array of string values that I pass to a simple function that returns the url and the response code.
However, when I run it I get all these errors I don't even know where to start:
$ python ReturnPath.py
Traceback (most recent call last):
File "ReturnPath.py", line 86, in <module>
checkResponse(u)
File "ReturnPath.py", line 5, in checkResponse
code = urllib.request.urlopen(url).getcode()
File "C:\Program Files\Python37\lib\urllib\request.py", line 222, in urlopen
return opener.open(url, data, timeout)
File "C:\Program Files\Python37\lib\urllib\request.py", line 510, in open
req = Request(fullurl, data)
File "C:\Program Files\Python37\lib\urllib\request.py", line 328, in __init__
self.full_url = url
File "C:\Program Files\Python37\lib\urllib\request.py", line 354, in full_url
self._parse()
File "C:\Program Files\Python37\lib\urllib\request.py", line 383, in _parse
raise ValueError("unknown url type: %r" % self.full_url)
ValueError: unknown url type: '"https://myserver.org/Media/CharacterAvatarImages/ae275ecb-183e-4e8d-8465-9d6d36c1323f.jpg"'
Here is my code:
import urllib.request
def checkResponse(url):
code = urllib.request.urlopen(url).getcode()
print(url + " = " + code)
return
arrCases = []
arrCases.extend([
"https://myserver.org/Media/CharacterAvatarImages/ae275ecb-183e-4e8d-8465-9d6d36c1323f.jpg",
"https://myserver.org/Media/CharacterAvatarImages/3ea92fa3-1ef0-4358-b38d-bb04e653aa53.jpg",
"https://myserver.org/Media/CharacterAvatarImages/7958a0e3-171b-46b5-875e-970368389bdf.jpg",
"https://myserver.org/Media/CharacterAvatarImages/e9a6cb00-6811-4b47-9aac-88480578dd44.jpg",
"https://myserver.org/Media/CharacterAvatarImages/73df88c3-b829-4519-9523-2bbe1f2c8549.jpg",
"https://myserver.org/Media/CharacterAvatarImages/61aa614b-5c95-487c-b4e3-783231b43677.jpg",
"https://myserver.org/Media/CharacterAvatarImages/8be7811f-18dc-4a81-a557-8b81605e3452.jpg",
"https://myserver.org/Media/CharacterAvatarImages/56539acb-2b1b-4410-a4bc-ac2eb0dc00fa.jpg",
"https://myserver.org/Media/CharacterAvatarImages/8bcf93fc-b435-4fd4-9c82-4aba78c58529.jpg",
])
for u in arrCases:
checkResponse(u)
What am I doing wrong?
You have to catch errors from broken URLs. I also increased speed through multiprocessing.Pool.
import urllib.request
from urllib.error import HTTPError, URLError
import multiprocessing
def checkResponse(url):
try:
code = urllib.request.urlopen(url, timeout=1).getcode()
except (HTTPError, URLError) as error:
print(url, " = ", error)
else:
print(url, " = ", code)
return
arrCases = []
arrCases.extend([
"https://i.stack.imgur.com/DsNOB.jpg",
"https://myserver.org/Media/CharacterAvatarImages/ae275ecb-183e-4e8d-8465-9d6d36c1323f.jpg",
"https://myserver.org/Media/CharacterAvatarImages/3ea92fa3-1ef0-4358-b38d-bb04e653aa53.jpg",
"https://myserver.org/Media/CharacterAvatarImages/7958a0e3-171b-46b5-875e-970368389bdf.jpg",
"https://myserver.org/Media/CharacterAvatarImages/e9a6cb00-6811-4b47-9aac-88480578dd44.jpg",
"https://myserver.org/Media/CharacterAvatarImages/73df88c3-b829-4519-9523-2bbe1f2c8549.jpg",
"https://myserver.org/Media/CharacterAvatarImages/61aa614b-5c95-487c-b4e3-783231b43677.jpg",
"https://myserver.org/Media/CharacterAvatarImages/8be7811f-18dc-4a81-a557-8b81605e3452.jpg",
"https://myserver.org/Media/CharacterAvatarImages/56539acb-2b1b-4410-a4bc-ac2eb0dc00fa.jpg",
"https://myserver.org/Media/CharacterAvatarImages/8bcf93fc-b435-4fd4-9c82-4aba78c58529.jpg",
])
with multiprocessing.Pool(processes=4) as pool:
pool.map(checkResponse, arrCases)
I have a problem with my endpoint in Falcon framework, I have two models Class with access to DB but when execute the seconds class, this raise an exception:
sqlalchemy.exc.NoSuchColumnError: "Could not locate column in row for column 'translate'
I don't have a 'translate' column in my database or in my object mapping.
Version:
Python 3.6.2
PyMySQL==0.7.11
SQLAlchemy==1.1.11
My Code:
endpoint:
def on_post(self, req, resp, courseid, examid):
with self.db.connect() as cnn:
mdl_party = Party(cnn)
mdl_exam = Exam(cnn)
rolecourseid = mdl_party.find_rolecourseid(roleid,courseid,examid)
if rolecourseid is None :
raise AppValidationEx("ExamDoesntExist")
take_exam_id = mdl_exam.new_user_exam(username, rolecourseid, examid)
Class Party
class Party(object):
def __init__(self, dbconnection):
self.cnn = dbconnection
def find_rolecourseid(self, roleid, courseid, examid):
s = text(''' SELECT ... ''')
cursor = self.cnn.execute(s,
p_roleid=roleid,
p_courseid=courseid,
p_examid=examid)
return cursor.first()
Class Exam
class Exam(object):
""" a user class """
def __init__(self, dbconnection):
self.cnn = dbconnection
def new_user_exam(self, username, rolecourseid, examid):
now = datetime.utcnow()
data = {
'partyRoleCourseId': rolecourseid,
'examTakeDate': now,
'examTakeStart': now,
'examId': examid,
'createdBy': username,
'createdDate': now,
'deleted': 0,
'version': 0
}
ins = partyrolecourseexam.insert().values(data)
cursor = self.cnn.execute(ins) #this raise exception
take_exam_id = cursor.inserted_primary_key[0]
Database
engine = create_engine("mysql+pymysql://%s:%s#%s/%s?charset=utf8" % DBPARAMS,
pool_size=50,
max_overflow=100,
echo=False)
metadata = MetaData()
partyrolecourseexam = Table('partyrolecourseexam', metadata,
Column("id", Integer, primary_key=True),
Column("partyRoleCourseId", Integer),
...
)
The error raise when execute the "new_user_exam" method.
if the function 'find_rolecourseid' does not execute, the method "new_user_exam" works.
All trace:
Traceback (most recent call last):
File "C:\Users\USER\dev\clexam\env\lib\site-packages\sqlalchemy\engine\result.py", line 73, in __getitem__
processor, obj, index = self._keymap[key]
KeyError: 'translate'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\USER\dev\clexam\env\lib\site-packages\sqlalchemy\engine\result.py", line 99, in __getattr__
return self[name]
File "C:\Users\USER\dev\clexam\env\lib\site-packages\sqlalchemy\engine\result.py", line 75, in __getitem__
processor, obj, index = self._parent._key_fallback(key)
File "C:\Users\USER\dev\clexam\env\lib\site-packages\sqlalchemy\engine\result.py", line 563, in _key_fallback
expression._string_or_unprintable(key))
sqlalchemy.exc.NoSuchColumnError: "Could not locate column in row for column 'translate'"
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\USER\dev\clexam\env\lib\site-packages\tornado\web.py", line 1488, in _execute
result = self.prepare()
File "C:\Users\USER\dev\clexam\env\lib\site-packages\tornado\web.py", line 2774, in prepare
self.fallback(self.request)
File "C:\Users\USER\dev\clexam\env\lib\site-packages\tornado\wsgi.py", line 277, in __call__
WSGIContainer.environ(request), start_response)
File "C:\Users\USER\dev\clexam\env\lib\site-packages\falcon\api.py", line 230, in __call__
if not self._handle_exception(ex, req, resp, params):
File "C:\Users\USER\dev\clexam\env\lib\site-packages\falcon\api.py", line 657, in _handle_exception
err_handler(ex, req, resp, params)
File "app_rest.py", line 17, in handle_errors
raise ex
File "C:\Users\USER\dev\clexam\env\lib\site-packages\falcon\api.py", line 227, in __call__
responder(req, resp, **params)
File "C:\Users\USER\dev\clexam\controllers\exam_take.py", line 32, in on_post
take_exam_id = mdl_exam.new_user_exam(username, rolecourseid, examid)
File "C:\Users\USER\dev\clexam\models\exam.py", line 43, in new_user_exam
cursor = self.cnn.execute(ins)
File "C:\Users\USER\dev\clexam\env\lib\site-packages\sqlalchemy\engine\base.py", line 945, in execute
return meth(self, multiparams, params)
File "C:\Users\USER\dev\clexam\env\lib\site-packages\sqlalchemy\sql\elements.py", line 263, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "C:\Users\USER\dev\clexam\env\lib\site-packages\sqlalchemy\engine\base.py", line 1053, in _execute_clauseelement
compiled_sql, distilled_params
File "C:\Users\USER\dev\clexam\env\lib\site-packages\sqlalchemy\engine\base.py", line 1189, in _execute_context
context)
File "C:\Users\USER\dev\clexam\env\lib\site-packages\sqlalchemy\engine\base.py", line 1405, in _handle_dbapi_exception
util.reraise(*exc_info)
File "C:\Users\USER\dev\clexam\env\lib\site-packages\sqlalchemy\util\compat.py", line 187, in reraise
raise value
File "C:\Users\USER\dev\clexam\env\lib\site-packages\sqlalchemy\engine\base.py", line 1182, in _execute_context
context)
File "C:\Users\USER\dev\clexam\env\lib\site-packages\sqlalchemy\engine\default.py", line 470, in do_execute
cursor.execute(statement, parameters)
File "C:\Users\USER\dev\clexam\env\lib\site-packages\pymysql\cursors.py", line 164, in execute
query = self.mogrify(query, args)
File "C:\Users\USER\dev\clexam\env\lib\site-packages\pymysql\cursors.py", line 143, in mogrify
query = query % self._escape_args(args, conn)
File "C:\Users\USER\dev\clexam\env\lib\site-packages\pymysql\cursors.py", line 123, in _escape_args
return dict((key, conn.literal(val)) for (key, val) in args.items())
File "C:\Users\USER\dev\clexam\env\lib\site-packages\pymysql\cursors.py", line 123, in <genexpr>
return dict((key, conn.literal(val)) for (key, val) in args.items())
File "C:\Users\USER\dev\clexam\env\lib\site-packages\pymysql\connections.py", line 821, in literal
return self.escape(obj, self.encoders)
File "C:\Users\USER\dev\clexam\env\lib\site-packages\pymysql\connections.py", line 814, in escape
return escape_item(obj, self.charset, mapping=mapping)
File "C:\Users\USER\dev\clexam\env\lib\site-packages\pymysql\converters.py", line 27, in escape_item
val = encoder(val, mapping)
File "C:\Users\USER\dev\clexam\env\lib\site-packages\pymysql\converters.py", line 110, in escape_unicode
return u"'%s'" % _escape_unicode(value)
File "C:\Users\USER\dev\clexam\env\lib\site-packages\pymysql\converters.py", line 73, in _escape_unicode
return value.translate(_escape_table)
File "C:\Users\USER\dev\clexam\env\lib\site-packages\sqlalchemy\engine\result.py", line 101, in __getattr__
raise AttributeError(e.args[0])
AttributeError: Could not locate column in row for column 'translate'
Help and thks
I have this code which checks if there's a provider specified, and a pem key, in order to send over an xml to a server:
#api.multi
def send_xml_file(self, envio_dte=None, file_name="envio",company_id=False):
if not company_id.dte_service_provider:
raise UserError(_("Not Service provider selected!"))
try:
signature_d = self.get_digital_signature_pem(
company_id)
seed = self.get_seed(company_id)
template_string = self.create_template_seed(seed)
seed_firmado = self.sign_seed(
template_string, signature_d['priv_key'],
signature_d['cert'])
token = self.get_token(seed_firmado,company_id)
_logger.info(_("Token is: {}").format(token))
except:
raise Warning(connection_status[response.e])
return {'sii_result': 'NoEnviado'}
On this line: _logger.info(_("Token is: {}").format(token)) is throwing me SyntaxError: invalid syntax this is my traceback:
Traceback (most recent call last):
File "/home/kristian/.virtualenvs/odoov9/lib/python2.7/site-packages/werkzeug/serving.py", line 177, in run_wsgi
execute(self.server.app)
File "/home/kristian/.virtualenvs/odoov9/lib/python2.7/site-packages/werkzeug/serving.py", line 165, in execute
application_iter = app(environ, start_response)
File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/service/server.py", line 246, in app
return self.app(e, s)
File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/service/wsgi_server.py", line 184, in application
return application_unproxied(environ, start_response)
File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/service/wsgi_server.py", line 170, in application_unproxied
result = handler(environ, start_response)
File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/http.py", line 1492, in __call__
self.load_addons()
File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/http.py", line 1513, in load_addons
m = __import__('openerp.addons.' + module)
File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/modules/module.py", line 61, in load_module
mod = imp.load_module('openerp.addons.' + module_part, f, path, descr)
File "/home/kristian/odoov9/solti/l10n_cl_dte/__init__.py", line 2, in <module>
from . import models, controllers, wizard
File "/home/kristian/odoov9/solti/l10n_cl_dte/models/__init__.py", line 2, in <module>
from . import invoice, partner, company, payment_term, sii_regional_offices
File "/home/kristian/odoov9/solti/l10n_cl_dte/models/invoice.py", line 500
_logger.info(_("Token is: {}").format(token))
^
SyntaxError: invalid syntax
I've checked for missing parenthesis, and stuff like that, but I still cannot figure it out.
Any ideas on this?
Thanks in advance!
Logger needs to be tabbed over, to be in the try block.
#api.multi
def send_xml_file(self, envio_dte=None, file_name="envio",company_id=False):
if not company_id.dte_service_provider:
raise UserError(_("Not Service provider selected!"))
try:
signature_d = self.get_digital_signature_pem(
company_id)
seed = self.get_seed(company_id)
template_string = self.create_template_seed(seed)
seed_firmado = self.sign_seed(
template_string, signature_d['priv_key'],
signature_d['cert'])
token = self.get_token(seed_firmado,company_id)
_logger.info(_("Token is: {}").format(token))
except:
# This is probably not doing what you expect
# raise will stop program execution, so the
# return will not actually return.
raise Warning(connection_status[response.e])
return {'sii_result': 'NoEnviado'}
I'm doing a POST request to an API, the code looks like this:
#gen.coroutine
def call():
...
response = yield AsyncHTTPClient().fetch(
HTTPRequest(
url='https://api.mywebsite.com/v1/users',
headers=headers,
method='POST',
body=json.dumps(body),
validate_cert=False
)
)
print response, response.body
if __name__ == "__main__":
tornado.ioloop.IOLoop.current().run_sync(call)
The server responds first time with 201 Created and the second time with 200 OK.
But for that code I get this error for the first time. The second time works
Traceback (most recent call last):
File "t.py", line 49, in <module>
tornado.ioloop.IOLoop.current().run_sync(call)
File "/usr/lib/python2.7/dist-packages/tornado/ioloop.py", line 389, in run_sync
return future_cell[0].result()
File "/usr/lib/python2.7/dist-packages/tornado/concurrent.py", line 129, in result
raise_exc_info(self.__exc_info)
File "/usr/lib/python2.7/dist-packages/tornado/stack_context.py", line 302, in wrapped
ret = fn(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/tornado/gen.py", line 574, in inner
self.set_result(key, result)
File "/usr/lib/python2.7/dist-packages/tornado/gen.py", line 500, in set_result
self.run()
File "/usr/lib/python2.7/dist-packages/tornado/gen.py", line 529, in run
yielded = self.gen.throw(*exc_info)
File "t.py", line 43, in call
validate_cert=False
File "/usr/lib/python2.7/dist-packages/tornado/gen.py", line 520, in run
next = self.yield_point.get_result()
File "/usr/lib/python2.7/dist-packages/tornado/gen.py", line 409, in get_result
return self.runner.pop_result(self.key).result()
File "/usr/lib/python2.7/dist-packages/tornado/concurrent.py", line 131, in result
return super(TracebackFuture, self).result(timeout=timeout)
File "/usr/lib/python2.7/dist-packages/concurrent/futures/_base.py", line 401, in result
return self.__get_result()
File "/usr/lib/python2.7/dist-packages/concurrent/futures/_base.py", line 360, in __get_result
raise self._exception
AssertionError
Looks like you are using sync function HTTPRequest in future
from tornado.httpclient import AsyncHTTPClient
from tornado.httpclient import HTTPResponse
def call():
response = None
http_client = AsyncHTTPClient()
try:
body = json.dumps(body)
response: HTTPResponse = yield http_client.fetch('https://api.mywebsite.com/v1/users', method='POST', body=str(body), headers=headers, request_timeout=5)
except Exception as e:
print('get_request error:{0}'.format(e))