When I call Create API from the python console, It gives following exception.
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
File "C:\Python27\lib\v1pysdk\base_asset.py", line 44, in create
return Class._v1_v1meta.create_asset(Class._v1_asset_type_name, newdata)
File "C:\Python27\lib\v1pysdk\v1meta.py", line 128, in create_asset
new_asset_xml = self.server.create_asset(asset_type_name, update_doc)
File "C:\Python27\lib\v1pysdk\client.py", line 202, in create_asset
return self.get_xml(path, query=query, postdata=body)
File "C:\Python27\lib\v1pysdk\client.py", line 159, in get_xml
document = ElementTree.fromstring(body)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1281, in XML
parser.feed(text)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1623, in feed
self._raiseerror(v)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1487, in _raiseerror
raise err
xml.etree.ElementTree.ParseError: reference to invalid character number: line 7575, column 75
I am running it with Python2.7 on windows.
This is the API I am calling
from v1pysdk import V1Meta
v1 = V1Meta(
address = 'www11.v1host.com',
instance = '<InstName>',
username = 'sbaid',
password = 'XXXXXX'
)
new_story = v1.Story.create(
Name = "Temp",
Scope = v1.Scope(321450)
)
v1.Scope(321450) returns the correct project name, that implies that session with version1 is established correctly.
These are the only two mandatory parameters and I am able to create the story with these two parameters using Web interface.
I am also able to create the story using following REST request
URL - https://www11.v1host.com/InstName/rest-1.v1/Data/Story
<Asset href="/<InstName>/rest-1.v1/New/Story">
<Attribute name="Name" act="set">Temp</Attribute>
<Relation name="Scope" act="set">
<Asset href="/<InstName>/rest-1.v1/Data/Scope/321450" idref="Scope:321450" />
</Relation>
</Asset>
There is an alternate way to specify the host address which is more reliable. Here's an example that you can try against the public VersionOne SDK testing instance:
from v1pysdk import V1Meta
with V1Meta (
instance_url = 'https://www14.v1host.com/v1sdktesting',
username = 'admin',
password = 'admin'
) as v1:
new_story = v1.Story.create(
Name = "Temp Test for StackOverflow question",
Scope = v1.Scope(0)
)
fetched_story = v1.Story.where(Number=new_story.Number).first()
print fetched_story.Name
Related
I am looking for some advice on how I can upsert or replace existing user entity.
I tried couple of API's documented here and also here.
The entities are read from database and the plan is to keep them in sync with database values as a scheduled job.
Update: Code Snippet
client_options = {"quota_project_id": gcp_default_project_id,
"api_endpoint": "us-central1-dialogflow.googleapis.com:443"}
client = EntityTypesClient(credentials=credentials_det, client_options=client_options)
entity_type = v3beta.EntityType()
entity_type.display_name = entity_display_name
entity_type.kind = "KIND_REGEXP"
print(client_options)
entity_type.entities = entity_json
# Initialize request argument(s)
request = v3beta.UpdateEntityTypeRequest(
entity_type=entity_type,
)
print(request)
response = client.update_entity_type(request=request)
print(response)
entity_json is fetched from DB and created as JSON object as below.
df = get_data.get_df_details(config_dir, entity_data_source, sql)
username = df['username'].tolist()
entity_json = []
for each in username:
each_entity_value = {}
each_entity_value['value'] = each
each_entity_value['synonyms'] = [each]
entity_json.append(each_entity_value)
Here's the Trace
Traceback (most recent call last):
File "/Users/<some_dir>/df_ins_entities/df_ins_entities/ins_entity_val.py", line 116, in
ins_now(config_dir, input_entity_name, entity_data_source)
File "/Users/<some_dir>/df_ins_entities/df_ins_entities/ins_entity_val.py", line 96, in ins_now
response = client.update_entity_type(request=request)
File "/Users/<some_dir>/df_ins_entities/lib/python3.9/site-packages/google/cloud/dialogflowcx_v3beta1/services/entity_types/client.py", line 902, in update_entity_type
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
File "/Users/<some_dir>/df_ins_entities/lib/python3.9/site-packages/google/api_core/gapic_v1/method.py", line 154, in call
return wrapped_func(args, **kwargs)
File "/Users/<some_dir>/df_ins_entities/lib/python3.9/site-packages/google/api_core/grpc_helpers.py", line 59, in error_remapped_callable
raise exceptions.from_grpc_error(exc) from exc
google.api_core.exceptions.InvalidArgument: 400 Resource name '' does not match 'projects//locations//agents//entityTypes/*'.
Process finished with exit code 1
I am having an issue with a simple body parsing using pyswagger (library to test OpenAPI compliant APIs).
Here is my script:
import os
from dotenv import load_dotenv, find_dotenv
from pyswagger import App, Security
from pyswagger.contrib.client.requests import Client
# load my security token
load_dotenv(find_dotenv())
api_key = os.environ.get('HELLO_SWAGGER_API_KEY', 'xxx')
hello_swagger_json = 'https://europewest.services.azureml.net/subscriptions/300c8e706bdd414aa1c215ceb2b5a465/services/363818fa1c4a4d0b9d5c03a3dc6f1dfe/swagger.json'
# adapted from pyswagger quick start
app = App._create_(hello_swagger_json)
auth = Security(app)
auth.update_with('api_key', api_key)
client = Client(auth)
# this produces a dictionary exactly as in the schema example for 'execute' operation
hello_body = dict(Inputs=dict(input1=[dict(name="mission-liao")]), GlobalParameters=dict())
# submit execute post request
req, resp = app.op['execute'](body=hello_body)
which give me this error when executing last line:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "P:\Development\Anaconda3\envs\tgml36\lib\site-packages\pyswagger\spec\v2_0\objects.py", line 283, in __call__
_convert_parameter(final(p))
File "P:\Development\Anaconda3\envs\tgml36\lib\site-packages\pyswagger\spec\v2_0\objects.py", line 264, in _convert_parameter
c = p._prim_(v, self._prim_factory, ctx=dict(read=False))
File "P:\Development\Anaconda3\envs\tgml36\lib\site-packages\pyswagger\spec\v2_0\objects.py", line 184, in _prim_
return prim_factory.produce(self.schema, v, ctx) if i == 'body' else prim_factory.produce(self, v, ctx)
File "P:\Development\Anaconda3\envs\tgml36\lib\site-packages\pyswagger\primitives\__init__.py", line 200, in produce
val = ret.apply_with(obj, val, ctx)
File "P:\Development\Anaconda3\envs\tgml36\lib\site-packages\pyswagger\primitives\_model.py", line 29, in apply_with
self[k] = ctx['factory'].produce(pobj, v)
File "P:\Development\Anaconda3\envs\tgml36\lib\site-packages\pyswagger\primitives\__init__.py", line 196, in produce
val = _2nd(obj, ret, val, ctx)
File "P:\Development\Anaconda3\envs\tgml36\lib\site-packages\pyswagger\primitives\comm.py", line 40, in _2nd_pass_obj
return ret.apply_with(obj, val, ctx)
File "P:\Development\Anaconda3\envs\tgml36\lib\site-packages\pyswagger\primitives\_model.py", line 29, in apply_with
self[k] = ctx['factory'].produce(pobj, v)
File "P:\Development\Anaconda3\envs\tgml36\lib\site-packages\pyswagger\primitives\__init__.py", line 196, in produce
val = _2nd(obj, ret, val, ctx)
File "P:\Development\Anaconda3\envs\tgml36\lib\site-packages\pyswagger\primitives\comm.py", line 40, in _2nd_pass_obj
return ret.apply_with(obj, val, ctx)
File "P:\Development\Anaconda3\envs\tgml36\lib\site-packages\pyswagger\primitives\_array.py", line 48, in apply_with
self.extend(map(functools.partial(ctx['factory'].produce, obj.items), val))
File "P:\Development\Anaconda3\envs\tgml36\lib\site-packages\pyswagger\primitives\__init__.py", line 200, in produce
val = ret.apply_with(obj, val, ctx)
File "P:\Development\Anaconda3\envs\tgml36\lib\site-packages\pyswagger\primitives\_model.py", line 29, in apply_with
self[k] = ctx['factory'].produce(pobj, v)
File "P:\Development\Anaconda3\envs\tgml36\lib\site-packages\pyswagger\primitives\__init__.py", line 192, in produce
raise ValueError('Can\'t resolve type from:(' + str(obj.type) + ', ' + str(obj.format) + ')')
ValueError: Can't resolve type from:(String, )
I cannot really understand if there is something I am doing wrong or if this is a bug.
This is actually a very simple example I was trying to build because I am having an issue with authentication in a more complex example, but while in the more complex example the body parsing does not raise errors, here I am having problems even before sending a request!
The script should be reproducible (swagger.json should be accessible from the url in the script, if not I can attach it) and I have logging info only when running the command app = App._create_(hello_swagger_json) (so this too should be reproducible too using the above script).
The webservice that I am trying to test is a simple Web service built with Azure ML Studio (which provides a Swagger API, the reason why I found out about Swagger in the first place).
I am running with pyswagger version 0.8.39.
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 want to retrieve assignments from an old HIT on mturk using boto. This is what I did.
from boto.mturk.connection import MTurkConnection
import csv
mtc = MTurkConnection(aws_access_key_id=ACCESS_ID,
aws_secret_access_key=SECRET_KEY,
host=HOST)
assignments = mtc.get_assignments(HIT_ID, status=None, sort_by='SubmitTime', sort_direction='Ascending', page_size=10, page_number=1, response_groups=None)
with open('assignments.csv','w') as tar:
csvwriter = csv.writer(tar, delimiter=';', quoting = csv.QUOTE_NONE, quotechar='')
for asgn in assignments:
row = []
for i in range(len(asgn.answers[0])):
row.append(asgn.answers[0][i].fields[0])
csvwriter.writerow(row)
But it is throwing this error.
Traceback (most recent call last):
File "launch_task.py", line 13, in <module>
assignments = mtc.get_assignments(HIT_ID, status=None, sort_by='SubmitTime', sort_direction='Ascending', page_size=10, page_number=1, response_groups=None)
File "/home/projects/django_version/env/local/lib/python2.7/site-packages/boto/mturk/connection.py", line 417, in get_assignments
[('Assignment', Assignment)])
File "/home/projects/django_version/env/local/lib/python2.7/site-packages/boto/mturk/connection.py", line 838, in _process_request
return self._process_response(response, marker_elems)
File "/home/projects/django_version/env/local/lib/python2.7/site-packages/boto/mturk/connection.py", line 853, in _process_response
raise MTurkRequestError(response.status, response.reason, body)
boto.mturk.connection.MTurkRequestError: MTurkRequestError: 200 OK
<?xml version="1.0"?>
<GetAssignmentsForHITResponse><OperationRequest>
<RequestId>b006785d-4001-4835-adf6-2df34joW9588e</RequestId></OperationRequest>
<GetAssignmentsForHITResult><Request><IsValid>False</IsValid>
<Errors><Error><Code>AWS.MechanicalTurk.HITDoesNotExist</Code>
<Message>Hit 3MRHU529465LUERYI53175P072A8 does not exist. (1463449047025 s)</Message>
<Data><Key>HITId</Key><Value>3MRHU529465LUERYI53175P072A8</Value></Data>
<Data><Key>HITId</Key><Value>3MRHU529465LUERYI53175P072A8</Value></Data>
</Error></Errors>
</Request></GetAssignmentsForHITResult></GetAssignmentsForHITResponse>
I assure you the HIT does exist. I am using boto 2.40.0 .
I came upon the following error trace while just playing with this interface I plan to use in a Django app:
import sunburnt
si = sunburnt.SolrInterface("http://localhost:8984/solr/sprod/")
si.query(global_attr_article_type='casual shoes').execute()
Traceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python2.7/dist-packages/sunburnt/search.py", line 599, in execute
result = self.interface.search(**self.options())
File "/usr/local/lib/python2.7/dist-packages/sunburnt/sunburnt.py", line 212, in search
return self.schema.parse_response(self.conn.select(params))
File "/usr/local/lib/python2.7/dist-packages/sunburnt/schema.py", line 510, in parse_response
return SolrResponse(self, msg)
File "/usr/local/lib/python2.7/dist-packages/sunburnt/schema.py", line 652, in init
self.result = SolrResult(schema, result_node)
File "/usr/local/lib/python2.7/dist-packages/sunburnt/schema.py", line 691, in init
self.docs = [schema.parse_result_doc(n) for n in node.xpath("doc")]
File "/usr/local/lib/python2.7/dist-packages/sunburnt/schema.py", line 519, in parse_result_doc
return dict([self.parse_result_doc(n) for n in doc.getchildren()])
File "/usr/local/lib/python2.7/dist-packages/sunburnt/schema.py", line 516, in parse_result_doc
values = [self.parse_result_doc(n, name) for n in doc.getchildren()]
File "/usr/local/lib/python2.7/dist-packages/sunburnt/schema.py", line 525, in parse_result_doc
return name, SolrFieldInstance.from_solr(field_class, doc.text or '').to_user_data()
File "/usr/local/lib/python2.7/dist-packages/sunburnt/schema.py", line 326, in from_solr
self.value = self.field.from_solr(data)
File "/usr/local/lib/python2.7/dist-packages/sunburnt/schema.py", line 161, in from_solr
return self.normalize(value)
File "/usr/local/lib/python2.7/dist-packages/sunburnt/schema.py", line 219, in normalize
(value, self.class, self.name))
SolrError: is invalid value for class 'sunburnt.schema.SolrFieldType_SolrIntField_indexed_True_omitNorms_True_stored_True' (field designer) `
The designer field in the indexed document is indeed empty
<arr name="designer">
<int/>
</arr>
<arr name="discount">
<float>0.0</float>
</arr>
<arr name="discount_label">
<str/>
</arr>
and here's what the schema's got
<fieldType name="integer" class="solr.IntField" omitNorms="true"/>
..
...
....
<field name="designer" type="integer" indexed="true" stored="true"/>
I understand this has to do with the field being empty but since the schema doesn't mention 'required' = true anywhere for this field, I wonder what's really up.
I guess
<arr name="designer"> <int/> </arr>
implies you are trying to store a multi-valued integer field in Solr? But your field definition for designer requires a single-valued integer. If you don't have a designer field for the document, then the document you index should have nothing for this field.