step function input issue - python

Hi my step function cdk code is something like this
tasks.LambdaInvoke(self, "my_step_function",
lambda_function=my_lambda,
output_path="$.Payload",
payload=stepfunctions.TaskInput.from_object({
"payload.$": "$",
"job_id.$": "$$.Job.Id"
})
and when doing post request I am sending request like this :
scan_resp = requests.post(BASE_URL + '/start', json={'job_id': job_id},
headers={'x-api-key': api_key})
and getting this error
{
"error": "States.Runtime",
"cause": "An error occurred while executing the state my_lambda' (entered at the event id #2). The JSONPath '$$.Job.Id' specified for the field 'job_id.$' could not be found in the input '{\"Execution\":{\"Id\":\"arn:aws:states:us-west-2:935463345537:execution:on-demand-scan-flow-orchestrator:fd51a151-70d4-4d8a-b203-fe3ea5ce7269\",\"Input\":{\"data\":{\"job_id\":30150908},\"apiInfo\":{\"httpMethod\":\"POST\",\"apiKey\":\"zWLyDJkvnSWaiK4Rf\"}},\"Name\":\"fd51a151-70d4-4d8a-b203-fe3ea5ce7269\",\"RoleArn\":\"arn:aws:iam::935463345537:role/on-demand-scan-stack-myorchestratorR-1LCG5GDN3L44F\",\"StartTime\":\"2022-07-06T14:05:17.175Z\"},\"StateMachine\":{\"Id\":\"arn:aws:states:us-west-2:935463345537:stateMachine:my-orchestrator\",\"Name\":\"my-function\"},\"State\":{\"Name\":\"my-function\",\"EnteredTime\":\"2022-07-06T14:05:17.222Z\",\"RetryCount\":0}}'"
}

The $$. prefix refers to the execution's Context Object. It has no Job key. Perhaps you mean $$.Execution.Id? If Job.Id is part of your own defined input, prefix it with (a single) $..

Related

How to call callback url from python?

I am trying to call a callback URL from a python function.
Here is the code:
rasa_url = "http://localhost:5005/webhooks/callback/webhook"
wa_data = {
"sender":"Rasa",
"message":"hi"
}
r = requests.post(url=rasa_url, data=wa_data)
In the terminal of rasa run, I am getting below error:
sanic.exceptions.InvalidUsage: Failed when parsing body as json.
I also tried,
r = requests.post(url=rasa_url, data=json.loads(json.dumps(wa_data)))
How can I solve this?
I think your request does not coincide with the documentation. The only one with both sender and message i found is to:
http://localhost:5005/conversations/{conversation_id}/messages
where you can send a JSON in this format (you also have an optional parse_data key)
{
"text": "Hello!",
"sender": "user"
}

Axiom and Flask POST and GET requests, passing arguments

I am learning how web apps work and after successfully creating connection between front and back end I managed to perform get request with axiom:
Route in my Flask
#app.route('/api/random')
def random_number():
k = kokos()
print(k)
response = {'randomNumber': k}
return jsonify(response)
my kokos() function
def kokos():
return (890)
Function that I call to get data from backend:
getRandomFromBackend () {
const path = `http://localhost:5000/api/random`
axios.get(path)
.then(response => {this.randomNumber = response.data.randomNumber})
.catch(error => {
console.log(error)
})
}
Now suppose I have an input field in my App with value that I want to use in the function kokos() to affect the result and what is going to be displayed in my app.. Can someone explain me how to do that?
Is this what POST requests are for and I have to post first and then get? Or can I use still GET and somehow pass "arguments"? Is this even GET and POST are for or am I making it too complicated for myself?
Is this the proper way to do these kind of thing? I just have a lot of code in python already written and want to simply exchange data between server and client.
Thank you, Jakub
You can add second argument
axios.get(path, {
params: {
id: 122
}
})
.then ...
You can pass id like this or anything it will be available in get params at python side like we pass in URL.
python side [Flask] (http://flask.pocoo.org/docs/1.0/quickstart/#accessing-request-data)
To access parameters submitted in the URL (?key=value) you can use the args attribute:
def random_number():
id = request.args.get('id', '')
k = kokos(id)
id will be passed kokos function if no id is provided it will be blank ''
you can read axios docu to make complex requests.
https://github.com/axios/axios
if any doubt please comment.

JSON RPC Returns 'Invalid API parameter' upon request in python

I'm trying to create my own jsonrpc client for a project, using python and requests. After an hour of searching online, Most errors are to do with people executing a get rather than a post or people getting a different error. According the the JSONRPC Spec (Found Here http://www.jsonrpc.org/specification) It should work. Any help would be most grateful. Thanks Sam.
Requests & Code Below:
Post Request Body:
{"method": "GudMethod", "params": {"ur": "HELLO"}, "jsonrpc": "2.0", "id": 1}
Request Response:
{
"jsonrpc": "2.0",
"result": {
"method": "GudMethod",
"success": false,
"error": "Invalid API parameter [jsonrpc] must be 2.0 [\"GudMethod\"]",
"extra": [],
"metrics": {
"st": "2018-05-24 22:16:37",
"sspt": 0.0006299018859863281
}
},
"id": null
}
Codes:
import json
import requests
class Client():
def __init__(self,url):
self.url = url
self.id = 0
def request(self,method,prms):
rq = Request(self,method,prms)
return rq
class Request():
def __init__(self,client,method,prms):
self.client = client
self.method = method
self.prms = prms
self.rq = None
def buildRequest(self):
self.client.id = self.client.id + 1
url = self.client.url + "?method={}".format(self.method)
jb = {}
jb["jsonrpc"] = "2.0"
jb["method"] = self.method
jb["params"] = self.prms
jb["id"] = self.client.id
body = json.dumps(jb)
return url,body
def execute(self):
url , body = self.buildRequest()
self.rq = requests.post(url,data=body)
print(body)
print(self.rq.text)
Also, dont ask me to use a ready made one. I was told that already, but due to where the project will be used, I can't install any librarys. Luckily requests will be installed, that would be painful otherwise
Your client's request looks fine.
The server must be parsing your request incorrectly, assigning the value GudMethod to the name jsonrpc.
Not only is the server parsing your request incorrectly, but the response also is not valid according to the JSON-RPC specification:
1) There should be no result field:
result
This member is REQUIRED on success.
This member MUST NOT exist if there was an error invoking the method.
The value of this member is determined by the method invoked on the Server.
2) There should be a top-level error field:
error
This member is REQUIRED on error.
This member MUST NOT exist if there was no error triggered during invocation.
The value for this member MUST be an Object as defined in section 5.1.
3) The error field should be a JSON Object with the following fields:
code
A Number that indicates the error type that occurred.
This MUST be an integer.
message
A String providing a short description of the error.
The message SHOULD be limited to a concise single sentence.
data
A Primitive or Structured value that contains additional information about the error.
This may be omitted.
The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.).
As the server erroneously believes the jsonrpc field is not equal to 2.0, the error code field should be -32600 and the message field Invalid Request indicating
The JSON sent is not a valid Request object.

Blockchain info wallet check payment

i am trying to create bill for payment and send to my customer via telegram bot:
i am using blockchain API V2-https://blockchain.info/api/api receive .my code is:
xpub='***'
keyk='02e57f1***'
url='https://api.blockchain.info/v2/receive?xpub='+str(xpub)+'&callback=https%3A%2F%2Fdoors03.ru&key='+keyk
x=requests.get(url)
r=x.json()
r=r['address']
r -is an adress wich was made.
i am sending it to my costumer(by the way is there any way to send adress with exact sum for pay ) . After i want to check is payment was recieved:
data={ "Content-Type": "text/plain","key":keyk,"addr":r,"callback":"https%3A%2F%2Fdoors03.ru","onNotification":"KEEP", "op":"RECEIVE"}
r = requests.post(url, data=data)
and this is the response - u'{\n "message" : "Internal handlers error"\n}'
what i am doing wrong ? how to check payments ? how to send address with exact sum of btc or ethereum ?
Sorry, i don't have enough reputation to post a comment, so this is
the only option i have. #egorkh have you solved this problem? Maybe
you have received explanation from blockchain.info support? I have
sent them a question about that, but they are answering for too long.
UPDATE: Finally, i have found solution.
In my case, reason of "Internal handlers error" message is in a wrong interpretation of their API.
As they haven't implemented balance_update request in their java-api, i did it on my own and i did it in wrong way.
I have put this parameters:
{"key":keyk,"addr":r,"callback":"https%3A%2F%2Fdoors03.ru","onNotification":"KEEP", "op":"RECEIVE"}
as post parameters, like in other methods they have provided in api. In those methods parameters are URLEncoded like you did with callback link. But...
In this HTML request they must be sent as plain text in json format without any special encoding, like that:
Map<String, String> params = new HashMap<String, String>();
params.put("addr", address);
params.put("callback", callbackUrl);
params.put("key", apiCode);
params.put("onNotification", keepOnNotification? "KEEP" : "DELETE");
params.put("confs", Integer.toString(confirmationCount));
params.put("op", StringUtils.isBlank(operationType) ? "ALL" : operationType);
//parse parameters map to json string(that's optional: you can write it directly as string)
String body = new Gson().toJson(params);
if (requestMethod.equals("POST")) {
byte[] postBytes = body.getBytes("UTF-8");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "text/plain");
conn.setRequestProperty("Content-Length", String.valueOf(postBytes.length));
conn.getOutputStream().write(postBytes);
conn.getOutputStream().close();
}
The main reason of your error may be that you put "Content-Type": "text/plain" in data object (, and maybe encoded callback url) .

Published function on picloud throws an error

I am trying to send a file to a function on picloud via REST with poster python library on google app engine (An HTML JPEG image upload). But the function throws this error :
{"error": {"msg": "Function arguments (POST data) are not valid JSON", "code": 446, "data": "{'parameter': u' filename'}", "retry": false}}
I have set the function's output encoding to raw, also I've followed the docs to detail.
Here are some of the function details.
Function name: detector(name,ifile)
takes two arguments,an image file and its name
Here is a relevant part of the code:
#all needed classes and libraries have been imported,urlfetch, poster,MultipartParam class ect.
#here we go!
params=[]
params.append(MultipartParam("Imagename",filename="anyname.jpg",filetype="application/octet-stream",value=some_file_uploaded_via_html_form))
#http_headers has been defined with appropriate autorization credentials
datagen,headers=multipart.encode(params)
data=str().join(datagen)
result=urlfetch.fetch(url=my_defined_function_url,payload=data,method=urlfetch.POST,headers=http_headers)
print result.content
When I add the following lines,in order to include the real function arguments
params.append(MultipartParam('name',value=filename_variable)
params.append(MultipartParam('ifile',value=some_file_uploaded_via_html_form)
I get the error
{"error": {"msg": " charset is defined multiple times", "code": 445, "retry": false}}
I have also tried wrapping the parameters in a dictionary, rather than separate MultipartParam instances
Please help.
You got a space in your argument:
params.append(MultipartParam('ifile',value=some_file_uploaded_via_html _form)
This should likely be:
params.append(MultipartParam('ifile',value=some_file_uploaded_via_html_form)
Note that some_file_uploaded_via_html_form is one word.

Categories

Resources