SyntaxError: invalid syntax - python 2.7 - Odoo v9 community - python

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'}

Related

How to fix: azure.core.exceptions.ServiceRequestError: EOF occurred in violation of protocol (_ssl.c:1129)

I am trying to interact with the TextAnalyticsClient of Azure to run a pretrained custom Entity Recognition program. However, when I call the attribute .begin_recognize_custom_entities(...) in the code shown below. It appears that the administration of the key credentials passes succesfully (in text_analytics_client = TextAnalyticsClient(...)), but then it fails afterwards.
"""
FILE: sample_recognize_custom_entities.py
DESCRIPTION:
This sample demonstrates how to recognize custom entities in documents.
Recognizing custom entities is available as an action type through the begin_analyze_actions API.
For information on regional support of custom features and how to train a model to
recognize custom entities, see https://aka.ms/azsdk/textanalytics/customentityrecognition
USAGE:
python sample_recognize_custom_entities.py
Set the environment variables with your own values before running the sample:
1) AZURE_LANGUAGE_ENDPOINT - the endpoint to your Language resource.
2) AZURE_LANGUAGE_KEY - your Language subscription key
3) CUSTOM_ENTITIES_PROJECT_NAME - your Language Studio project name
4) CUSTOM_ENTITIES_DEPLOYMENT_NAME - your Language Studio deployment name
"""
import os
print('#############################################################')
def sample_recognize_custom_entities():
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient
deployment_name = #####
endpoint = #####
key = #####
project_name = #####
path_to_sample_document = r'C:\Users\#####\Documents\#####\Source\Document cracking\output_documents\txt_for_ML_566docs_270922\text.txt'
text_analytics_client = TextAnalyticsClient(
endpoint=endpoint,
credential=AzureKeyCredential(key),
)
with open(path_to_sample_document) as fd:
document = [fd.read()]
poller = text_analytics_client.begin_recognize_custom_entities(
document,
project_name=project_name,
deployment_name=deployment_name
)
document_results = poller.result()
for result in document_results:
custom_entities_result = result[0] # first document, first result
if not custom_entities_result.is_error:
for entity in custom_entities_result.entities:
print(
"Entity '{}' has category '{}' with confidence score of '{}'".format(
entity.text, entity.category, entity.confidence_score
)
)
else:
print(
"...Is an error with code '{}' and message '{}'".format(
custom_entities_result.code, custom_entities_result.message
)
)
sample_recognize_custom_entities()
if __name__ == "__main__":
sample_recognize_custom_entities()
it gives the following error:
File "C:\Users\#####\Documents\#####\Source\Document cracking\crack-document\test_ML_connection.py", line 71, in <module>
sample_recognize_custom_entities()
File "C:\Users\#####\Documents\#####\Source\Document cracking\crack-document\test_ML_connection.py", line 48, in sample_recognize_custom_entities
poller = text_analytics_client.begin_recognize_custom_entities(
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\tracing\decorator.py", line 78, in wrapper_use_tracer
return func(*args, **kwargs)
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\ai\textanalytics\_validate.py", line 74, in wrapper
return func(*args, **kwargs)
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\ai\textanalytics\_text_analytics_client.py", line 1388, in begin_recognize_custom_entities
self.begin_analyze_actions(
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\tracing\decorator.py", line 78, in wrapper_use_tracer
return func(*args, **kwargs)
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\ai\textanalytics\_validate.py", line 74, in wrapper
return func(*args, **kwargs)
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\ai\textanalytics\_text_analytics_client.py", line 1213, in begin_analyze_actions
self._client.begin_analyze_text_submit_job(
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\ai\textanalytics\_generated\_operations_mixin.py", line 277, in begin_analyze_text_submit_job
return mixin_instance.begin_analyze_text_submit_job(body, **kwargs)
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\tracing\decorator.py", line 78, in wrapper_use_tracer
return func(*args, **kwargs)
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\ai\textanalytics\_generated\v2022_05_01\operations\_patch.py", line 67, in begin_analyze_text_submit_job
raw_result = self._analyze_text_submit_job_initial( # type: ignore
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\ai\textanalytics\_generated\v2022_05_01\operations\_text_analytics_client_operations.py", line 353, in _analyze_text_submit_job_initial
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\pipeline\_base.py", line 211, in run
return first_node.send(pipeline_request) # type: ignore
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\pipeline\_base.py", line 71, in send
response = self.next.send(request)
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\pipeline\_base.py", line 71, in send
response = self.next.send(request)
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\pipeline\_base.py", line 71, in send
response = self.next.send(request)
[Previous line repeated 2 more times]
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\pipeline\policies\_redirect.py", line 158, in send
response = self.next.send(request)
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\pipeline\policies\_retry.py", line 468, in send
raise err
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\pipeline\policies\_retry.py", line 446, in send
response = self.next.send(request)
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\pipeline\_base.py", line 71, in send
response = self.next.send(request)
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\pipeline\_base.py", line 71, in send
response = self.next.send(request)
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\pipeline\_base.py", line 71, in send
response = self.next.send(request)
[Previous line repeated 3 more times]
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\pipeline\_base.py", line 103, in send
self._sender.send(request.http_request, **request.context.options),
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\pipeline\transport\_requests_basic.py", line 361, in send
raise error
azure.core.exceptions.ServiceRequestError: EOF occurred in violation of protocol (_ssl.c:1129)
Anyone knows what this means, and how to solve it?
Thanks in advance,
Koeiswit

Azure TableService() returns python ValueError in prod, but not dev

I've got dev Python code running GREAT that uses...
1 from azure.cosmosdb.table.tableservice import TableService
2 from azure.cosmosdb.table.models import Entity
...
85 table_service = TableService(connection_string = table_storage_connection_string)
86 perform_lookup = table_service.get_entity(mapping_table, 'test', 'foo')
After copying the code to prod and changing the values of...
table_storage_connection_string
Docs say using connection_string is ok.
Validated this is a connection string to the Table Storage Account
It IS using a Key Vault reference in local.settings.json/Azure Portal App Settings
mapping_table
...I get the error:
Exception while executing function: Functions.my-func-prod <--- Result: Failure Exception: ValueError: You need to provide an account name and either an account_key or sas_token when creating a storage service. Stack: File "/azure-functions-host/workers/python/3.8/LINUX/X64/azure_functions_worker/dispatcher.py", line 343, in _handle__invocation_request call_result = await self._loop.run_in_executor( File "/usr/local/lib/python3.8/concurrent/futures/thread.py", line 57, in run result = self.fn(*self.args, **self.kwargs) File "/azure-functions-host/workers/python/3.8/LINUX/X64/azure_functions_worker/dispatcher.py", line 480, in __run_sync_func return func(**params) File "/home/site/wwwroot/my-func-prod/__init__.py", line 85, in main table_service = TableService(connection_string = table_storage_connection_string) File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/cosmosdb/table/tableservice.py", line 173, in __init__ service_params = _TableServiceParameters.get_service_parameters( File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/cosmosdb/table/common/_connection.py", line 110, in get_service_parameters params = _ServiceParameters._from_connection_string(connection_string, service) File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/cosmosdb/table/common/_connection.py", line 153, in _from_connection_string return _ServiceParameters(service, File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/cosmosdb/table/common/_connection.py", line 85, in __init__ raise ValueError(_ERROR_STORAGE_MISSING_INFO)
prop__StartTime 2020-10-16T04:50:07.099Z
prop__Duration 00:00:01.2898150
ProcessId 18
Microsoft.Azure.WebJobs.Host.FunctionInvocationException: Exception while executing function: Functions.my-func-prod
Why would TableService() work just fine in dev with a connection string, require the Table Storage account name and account key or sas token when in prod?
EDIT 1:
When connection_string is substituted with account_name and account_key of the storage account, I get a new error on the subsequent line (89):
1 from azure.cosmosdb.table.tableservice import TableService
2 from azure.cosmosdb.table.models import Entity
...
85 table_service = TableService(
86 account_name = table_storage_account_name,
87 account_key = table_storage_account_key
88 )
89 perform_lookup = table_service.get_entity(mapping_table, 'test', 'foo')
New Error:
Exception while executing function: Functions.my-func-prod <--- Result: Failure Exception: AzureSigningError: Incorrect padding Stack: File "/azure-functions-host/workers/python/3.8/LINUX/X64/azure_functions_worker/dispatcher.py", line 343, in _handle__invocation_request call_result = await self._loop.run_in_executor( File "/usr/local/lib/python3.8/concurrent/futures/thread.py", line 57, in run result = self.fn(*self.args, **self.kwargs) File "/azure-functions-host/workers/python/3.8/LINUX/X64/azure_functions_worker/dispatcher.py", line 480, in __run_sync_func return func(**params) File "/home/site/wwwroot/my-func-prod/__init__.py", line 89, in main perform_lookup = table_service.get_entity(mapping_table, 'test', 'foo') File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/cosmosdb/table/tableservice.py", line 896, in get_entity return self._perform_request(request, _convert_json_response_to_entity, File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/cosmosdb/table/tableservice.py", line 1106, in _perform_request return super(TableService, self)._perform_request(request, parser, parser_args, operation_context) File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/cosmosdb/table/common/storageclient.py", line 386, in _perform_request raise ex File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/cosmosdb/table/common/storageclient.py", line 358, in _perform_request raise ex File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/cosmosdb/table/common/storageclient.py", line 302, in _perform_request self.authentication.sign_request(request) File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/cosmosdb/table/_auth.py", line 35, in sign_request self._add_authorization_header(request, string_to_sign) File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/cosmosdb/table/common/_auth.py", line 75, in _add_authorization_header raise _wrap_exception(ex, AzureSigningError)
Anyone overcome this issue before with Table Storage?
I tried to reproduce your error, but both using connection_string and using account_name and account_key all worked well.
The connection_string contains both AccountName and AccountKey, looks like this:
DefaultEndpointsProtocol=https;AccountName=<your-account-name>;AccountKey=<e60xxxxxxxxxxx==>;EndpointSuffix=core.windows.net
If the connection_string does not include the AccountName or AccountKey, the error will appear.
The error(Incorrect padding) is related to your account key being incorrect. Please regenerate the key in the portal and try with the new one.

Python client for AWS Redis Cluster

Can anyone suggest a Python client for AWS Redis Cluster enabled?
I'm using redis-py-cluster, but it fails:
Sample code:
from rediscluster import StrictRedisCluster
startup_nodes = [{"host": "xxxx.clustercfg.apn2.cache.amazonaws.com", "port": "6379"}]
r = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True, skip_full_coverage_check=False)
r.set('foo', 'bar')
value = r.get('foo')
======
Exception:
Traceback (most recent call last):
File "testRedisCluster.py", line 11, in
r = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True, skip_full_coverage_check=False)
File "/Library/Python/2.7/site-packages/rediscluster/client.py", line 181, in init
**kwargs
File "/Library/Python/2.7/site-packages/rediscluster/connection.py", line 141, in init
self.nodes.initialize()
File "/Library/Python/2.7/site-packages/rediscluster/nodemanager.py", line 228, in initialize
need_full_slots_coverage = self.cluster_require_full_coverage(nodes_cache)
File "/Library/Python/2.7/site-packages/rediscluster/nodemanager.py", line 270, in cluster_require_full_coverage
return any(node_require_full_coverage(node) for node in nodes.values())
File "/Library/Python/2.7/site-packages/rediscluster/nodemanager.py", line 270, in
return any(node_require_full_coverage(node) for node in nodes.values())
File "/Library/Python/2.7/site-packages/rediscluster/nodemanager.py", line 267, in node_require_full_coverage
return "yes" in r_node.config_get("cluster-require-full-coverage").values()
File "/Library/Python/2.7/site-packages/redis/client.py", line 715, in config_get
return self.execute_command('CONFIG GET', pattern)
File "/Library/Python/2.7/site-packages/redis/client.py", line 668, in execute_command
return self.parse_response(connection, command_name, **options)
File "/Library/Python/2.7/site-packages/redis/client.py", line 680, in parse_response
response = connection.read_response()
File "/Library/Python/2.7/site-packages/redis/connection.py", line 629, in read_response
raise response
redis.exceptions.ResponseError: unknown command 'CONFIG'
I'm using redis-py-cluster 1.3.4.
Any idea?
Change the parameter skip_full_coverage_check=False to skip_full_coverage_check=True

Appengine throwing BadRequestError: The property.name is the empty string

I have an application that has worked successfully in the past. Today however, it's started throwing an error when I try write to datastore. For example, I'm creating a new entity of this model
class EventInstallment(ndb.Model):
somekey = ndb.KeyProperty()
somename = ndb.StringProperty(default = "")
start_date = ndb.DateTimeProperty()
notes = ndb.StringProperty("")
moderator_approved = ndb.BooleanProperty(default = True)
added_by = ndb.KeyProperty()
created = ndb.DateTimeProperty(auto_now_add = True)
using this code
ins = somemodel()
ins.somename = "26-september-2016"
ins.somekey = the_key
ins.start_date = datetime.datetime.now()
ins.put()
and this exception gets thrown.
Traceback (most recent call last):
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/admin/__init__.py", line 363, in post
exec(compiled_code, globals())
File "<string>", line 8, in <module>
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 3451, in _put
return self._put_async(**ctx_options).get_result()
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/tasklets.py", line 383, in get_result
self.check_success()
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/tasklets.py", line 427, in _help_tasklet_along
value = gen.throw(exc.__class__, exc, tb)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/context.py", line 824, in put
key = yield self._put_batcher.add(entity, options)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/tasklets.py", line 427, in _help_tasklet_along
value = gen.throw(exc.__class__, exc, tb)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/context.py", line 358, in _put_tasklet
keys = yield self._conn.async_put(options, datastore_entities)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/tasklets.py", line 513, in _on_rpc_completion
result = rpc.get_result()
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 613, in get_result
return self.__get_result_hook(self)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/datastore/datastore_rpc.py", line 1881, in __put_hook
self.check_rpc_success(rpc)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/datastore/datastore_rpc.py", line 1373, in check_rpc_success
raise _ToDatastoreError(err)
BadRequestError: The property.name is the empty string.
Any idea what this issue might be? It looks like a change in GAE ndb - as it worked as recently as 1 month ago...
Shouldn't notes = ndb.StringProperty("") be: notes = ndb.StringProperty(default = "") ?

How to fix such ClientForm bug?

from mechanize import Browser
br = Browser()
page = br.open('http://wow.interzet.ru/news.php?readmore=23')
br.form = br.forms().next()
print br.form
gives me the following error:
Traceback (most recent call last):
File "C:\Users\roddik\Desktop\mech.py", line 6, in <module>
br.form = br.forms().next()
File "build\bdist.win32\egg\mechanize\_mechanize.py", line 426, in forms
File "D:\py26\lib\site-package\mechanize-0.1.11-py2.6.egg\mechanize\_html.py", line 559, in forms
File "D:\py26\lib\site-packages\mechanize-0.1.11-py2.6.egg\mechanize\_html.py", line 225, in forms
File "D:\py26\lib\site-packages\clientform-0.2.10-py2.6.egg\ClientForm.py", line 967, in ParseResponseEx
File "D:\py26\lib\site-packages\clientform-0.2.10-py2.6.egg\ClientForm.py", line 1100, in _ParseFileEx
File "D:\py26\lib\site-packages\clientform-0.2.10-py2.6.egg\ClientForm.py", line 870, in feed
File "D:\py26\lib\sgmllib.py", line 104, in feed
self.goahead(0)
File "D:\py26\lib\sgmllib.py", line 138, in goahead
k = self.parse_starttag(i)
File "D:\py26\lib\sgmllib.py", line 290, in parse_starttag
self._convert_ref, attrvalue)
File "D:\py26\lib\sgmllib.py", line 302, in _convert_ref
return self.convert_charref(match.group(2)) or \
File "D:\py26\lib\site-packages\clientform-0.2.10-py2.6.egg\ClientForm.py", line 850, in convert_charref
File "D:\py26\lib\site-packages\clientform-0.2.10-py2.6.egg\ClientForm.py", line 244, in unescape_charref
ValueError: invalid literal for int() with base 10: 'e'
How can I fix it?
Edit:
I've fixed it this way. Is it ok? If not, how instead?
import ClientForm
from mechanize import Browser
def myunescape_charref(data, encoding):
if not str(data).isdigit(): return 0
name, base = data, 10
if name.startswith("x"):
name, base= name[1:], 16
uc = unichr(int(name, base))
if encoding is None:
return uc
else:
try:
repl = uc.encode(encoding)
except UnicodeError:
repl = "&#%s;" % data
return repl
ClientForm.unescape_charref = myunescape_charref
The problem is caused by urls like this
http://wow.zet/forum/index.php?showtopic=1197&pid=30419&st=0&#entry30419
ClientForm is looking for an integer after the &#
It is ok to have the # in the url, but it should be escaped in the html
as &# means a character encoding

Categories