I would like to pass two parameters to my url(status code & parent id). The json response of the url request is such :
{
"page": 1,
"per_page": 10,
"total": 35,
"total_pages": 4,
"data": [
{
"id": 11,
"timestamp": 1565193225660,
"status": "RUNNING",
"operatingParams": {
"rotorSpeed": 2363,
"slack": 63.07,
"rootThreshold": 0
},
"asset": {
"id": 4,
"alias": "Secondary Rotor"
},
"parent": {
"id": 2,
"alias": "Main Rotor Shaft"
}
}]
I would like to know how to pass the two parameters in the url. Passing ?status=RUNNING gives the response of all the devices which have running as status (thats pretty straightforward).
For now I have tried this:
import requests
resp = requests.get('https://jsonmock.hackerrank.com/api/iot_devices/search?status=RUNNING')
q = resp.json()
print(q)
How should I pass in parentid=2, so it returns a response with devices which have their parent id=2.Thank you.
It's plainly documented under "Passing Parameters in URLs" in the Requests docs.
resp = requests.get(
'https://jsonmock.hackerrank.com/api/iot_devices/search',
params={
'status': 'RUNNING',
'parentid': 2,
},
)
To add a second get parameter, use the & separator :
import requests
resp = requests.get('https://jsonmock.hackerrank.com/api/iot_devices/search?status=RUNNING&parentid=2')
q = resp.json()
print(q)
If you want to send data via get request the process is straight forward note how different values are seperated with '&'.
url?name1=value1&name2=value2
If you are using Flask for backend then you can access these parameters like.
para1=request.args.get("name1")
para2=request.args.get("name2")
On the front end you can use ajax to send the request
var xhttp=new XMLHttpRequest();
var url="url?name1=value1&name2=value2"
xhttp.open("GET",url,true)
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200)
{
console.log(this.responseText);
}
};
xhttp.send();
Related
I have made this code to make a user interact with a button of my bot’s message, but i am unable to make it work. Please help.I get the following error:
{"code": 50035, "errors": {"session_id": {"_errors": [{"code": "BASE_TYPE_REQUIRED", "message": "This field is required"}]}}, "message": "Invalid Form Body”}
header = {
'authorization': auth
}
r = requests.get("https://discord.com/api/v9/channels/<channel_id>/messages", headers = header)
message = json.loads(r.text)[0]
data = {
"type": 3,
"guild_id": '<guild_id>',
"channel_id": '<channel_id>',
"message_id": message['id'],
"application_id": '<bot_id>', #the id of the bot to which i want to interact
"data": {
"component_type": 2,
"custom_id": message['components'][0]['components'][2]['custom_id'] #gets the custom_id of the button to interact
}
}
r = requests.post('https://discord.com/api/v9/interactions', json = data, headers = header)
Turns out, I need to add a session_id under the data dict, the problem got solved! Thanks furas for your help!
The code now:
data = {
"type": 3,
"guild_id": '<guild_id>',
"channel_id": '<channel_id>',
"message_id": message['id'],
"session_id": '<session_id>', #if you don't know the string, a random string worked for me
"application_id": '<bot_id>', #the id of the bot to which i want to interact
"data": {
"component_type": 2,
"custom_id": message['components'][0]['components'][2]['custom_id'] #gets the custom_id of the button to interact
}
}
I was coding a webapp based on GPT-2 but it was not good so I decided to switch to official OpenAI GPT-3.
So I make that request:
response = openai.Completion.create(
engine="davinci",
prompt="Hello",
temperature=0.7,
max_tokens=64,
top_p=1,
frequency_penalty=0,
presence_penalty=0
)
And when I print the response I get this:
{
"choices": [
{
"finish_reason": "length",
"index": 0,
"logprobs": null,
"text": ", everyone, and welcome to the first installment of the new opening"
}
],
"created": 1624033807,
"id": "cmpl-3CBfb8yZAFEUIVXfZO90m77dgd9V4",
"model": "davinci:2020-05-03",
"object": "text_completion"
}
But I only want to print the text, so how can I do to print the "text" value in the response list.
Thank you in advance and have a good day.
Using the dict indexing by key, and the list indexing by index
x = {"choices": [{"finish_reason": "length",
"text": ", everyone, and welcome to the first installment of the new opening"}], }
text = x['choices'][0]['text']
print(text) # , everyone, and welcome to the first installment of the new opening
You can try print(response["choices"][0]["text"])
Hope this helps.
I think GPT-3 response structure has been changed, for reference, the response object looks this:
const response = await openai.createCompletion({
model: "text-davinci-002",
prompt: "Say this is a test",
temperature: 0,
max_tokens: 6,
});
// the response looks like the following
{
status: 200,
statusText: 'OK',
headers: {
},
config: {
},
request: <ref *1> ClientRequest {
},
data: {
id: 'cmpl-5zzyzqvh4Hmi5yyNL2LMI9ADkLBU0',
object: 'text_completion',
created: 1665457953,
model: 'text-davinci-002',
choices: [ [Object] ],
usage: { prompt_tokens: 5, completion_tokens: 6, total_tokens: 11 }
}
}
// choices can be accessed like this
var { choices } = { ...response.data }
I've created a Flask application which:
Reads events from different event sources;
Persists those events to database; and
Allows users to search through those events using DataTables 1.10.20.
I'm trying to:
Read the parameters that DataTables is passing to the Flask backend via an AJAX request whenever a user attempts to search through the table; and
Translate those parameters into a dictionary so they can be used when performing server-side filtering.
Here is the code for the table I created in DataTables:
$(document).ready(function() {
events_table_template = {
"scrollX": true,
"pageLength": 10,
"processing": true,
"serverSide": true,
"ajax": {
"url": "/ajax/events",
"type": "POST",
"dataType": "json",
"dataSrc": "data",
"contentType": "application/json"
},
"columns": [
{"data": "event_id"},
{"data": "event_type"},
{"data": "event_timestamp"},
{"data": "event_name"},
]
};
var table = $('#events-table').DataTable(events_table_template);
});
I've tried explicitly returning JSON within the DataTables configuration:
$(document).ready(function() {
events_table_template = {
...
"ajax": {
...
"data": function(args){
return {"args": JSON.stringify(args)};
}
};
var table = $('#events-table').DataTable(events_table_template);
});
Here is the AJAX endpoint on the Flask server:
from mycode import EventService
from flask import Blueprint
import flask
blueprint = Blueprint('events-ajax', __name__, url_prefix='/ajax/')
#blueprint.route('/events/', methods=["POST"])
def get_events():
print("Request data", flask.request.data)
print("Request form", flask.request.form)
api = EventService()
events = api.get_events_via_database()
rows = []
for event in api.get_events_via_database():
rows.append({
'event_id': event.event_id,
'event_type': event.type,
'event_timestamp': event.timestamp,
'event_name': event.name,
})
response = {
'data': rows,
'recordsTotal': len(events),
'recordsFiltered': len(events),
'draw': 1,
}
return flask.jsonify(response)
I've noticed that:
flask.request.data returns a bunch of URL encoded text: Request data b'draw=1&columns%5B0%5D%5Bdata%5D=event_id&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=true&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B1%5D%5Bdata%5D=host_id&columns%5B1%5D%5B...
flask.request.form returns an ImmutableMultiDict object: ImmutableMultiDict([])
I've tried to:
Read the content of the AJAX request using these functions:
flask.request.data
flask.request.form
flask.request.json
flask.request.get_json(force=True)
Change the content-type from the DataTables side of things from application/json to application/json; charset=utf-8
How do you read the AJAX request as JSON?
Remove "contentType": "application/json" from the "ajax" configuration block; and
Use flask.request.form to read the map of parameters present within the AJAX request.
DataTables:
$(document).ready(function() {
events_table_template = {
"scrollX": true,
"pageLength": 10,
"processing": true,
"serverSide": true,
"ajax": {
"url": "/ajax/events",
"type": "POST",
"dataType": "json",
"dataSrc": "data",
},
"columns": [
{"data": "event_id"},
{"data": "event_type"},
{"data": "event_timestamp"},
{"data": "event_name"},
]
};
var table = $('#events-table').DataTable(events_table_template);
});
Flask:
#blueprint.route('/events/', methods=["POST"])
def get_events():
parameters = dict(flask.request.form)
I am trying to retrieve the authentication token from the API using requests library from python. Here is the attempt I have made so far:
def get_token():
data = {
"auth" : {
"identity" : {
"methods" : [ "password" ],
"password": {
"user" : {
"name" : OS_USERNAME,
"domain": { "name": "Default" },
"password": OS_PASSWORD
}
}
}
}
}
r = requests.post(
OS_AUTH_URL+'/auth/tokens',
headers = HEADERS,
json = data, # https://stackoverflow.com/questions/9733638
verify = False
)
print(r.content)
j = json.loads(r.content)
return j['token']['user']['id']
I get token in the response :
{
"token": {
"issued_at": "2018-07-03T11:03:59.000000Z",
"audit_ids": [
"Fg1ywtZBQ1CkigCw70If9g"
],
"methods": [
"password"
],
"expires_at": "2018-07-03T12:03:59.000000Z",
"user": {
"password_expires_at": null,
"domain": {
"id": "default",
"name": "Default"
},
"id": "e0dc5beb383a46b98dad824c5d76e719",
"name": "admin"
}
}
}
However, when I am reusing this token to get, for instance, the list of projects :
def get_tenantID():
r = requests.get(
OS_AUTH_URL+'/auth/projects',
headers = HEADERS,
verify = False
)
return r
r = get_token()
HEADERS['X-Auth-Project-Id'] = 'admin'
HEADERS['X-Auth-Token'] = r
r = get_tenantID()
I get this error as if I would not be authenticated:
<Response [401]>
{"error": {"message": "The request you have made requires authentication.", "code": 401, "title": "Unauthorized"}}
Googling around and using openstack token issue command showed me that usually, token are more like:
gAAAAABaCo1F1CIMVlsTBeuqYH8tm2qR29tbkmUL4vZuhCNPXJI39TQ2YzL6Twoj8fNcAyLe3WhCYW2O1YpbBF0G8mo4bt7Kf0IRsoDOoJ6uWa3RYyJ5SQNoB_5n8EnVXbKPxFYOZ_iFBnaVtL1_XDrGbwsrlDeyy8lZTDdLsqY52pUhFR-7Uow
which is not what I get with get_token.
What am I doing wrong?
Many thanks!
When you use the auth API directly, the token issued comes in the X-Subject-Token header.
Thus, to retrieve in your python example, you could access the response.headers dict like this:
token = r.headers['X-Subject-Token']
More info about authentication in the Keystone v3 docs
1. fetch authentication token as mentioned below:
r = requests.post(
OS_AUTH_URL+'/auth/tokens',
headers = HEADERS,
json = data,
verify = False
)
token = r.headers[X-Subject-Token]
2. Pass this token in header for further request:
{
'X-Auth-Token': token
}
I have created a Facebook Messenger bot which works fine. I have used the Button Template and Image template, and both work perfectly. But when I try the Generic Template, I get no response. I have simply copy pasted the code from here, by performing the appropriate modifications.
I don't know how to debug. Facebook Messenger gives no output on the messaging box. I am currently running the app via Heroku.
Here is my code:
def send_message(token, recipient):
r = requests.post("https://graph.facebook.com/v2.6/me/messages",
params={"access_token": token},
data=json.dumps({
"recipient":{
"id":recipient
},
"message":{
"attachment":{
"type":"template",
"payload":{
"template_type":"generic",
"elements":[
{
"title":"Welcome to Peter\'s Hats",
"image_url":"http://www.godominion.com/content/images/feature-img-small-appliance-electronics.png",
"subtitle":"We\'ve got the right hat for everyone.",
"default_action": {
"type": "web_url",
"url": "https://peterssendreceiveapp.ngrok.io/view?item=103",
"messenger_extensions": true,
"webview_height_ratio": "tall",
"fallback_url": "https://peterssendreceiveapp.ngrok.io/"
},
"buttons":[
{
"type":"web_url",
"url":"https://petersfancybrownhats.com",
"title":"View Website"
}
]
}
]
}
}
}
}),
headers={'Content-type': 'application/json'})
if r.status_code != requests.codes.ok:
print r.text
I would appreciate any help.
Thank you.
EDIT 1: SOLUTION
I got rid of the issue by commenting out:
"messenger_extensions": true,
and
"fallback_url": "https://peterssendreceiveapp.ngrok.io/"},
I'm sure this is not the correct method. But as I am creating a bot, without actual links, this works.
On the second button, "url":"https://petersfancybrownhats.com" is broken.
Try like this
firstly make a function
def function():
extra_data = {
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
"elements": [
{
"title": "Any Title",
"image_url": "https://mbtskoudsalg.com/images/road-clipart-journey-3.png",
"subtitle": "Subtitle.",
"buttons": [
{
"type": "web_url",
"title": "View",
"url": "**MAKE SURE TO WHITELIST THIS URL**", # URL
"messenger_extensions": "true",
"webview_height_ratio": "full"
}
]
}
]
}
}
}
# w_message = "Hi there! How may I help you?"
fb_message_template(extra_data["attachment"], "****RECIEVER ID****")
Make another function
import requests
# // Importing User Defined Modules // #
from get_environ_var import get_environ_var
# // Global vars // #
ACCESS_TOKEN = "FB_ACCESS_TOKEN"
def fb_message_template(extra_data, sender_id):
"""This function sends template message to facebook"""
data = {
'recipient': {'id': sender_id},
'message': {
"attachment": extra_data
}
}
qs = 'access_token=' + ACCESS_TOKEN
resp = requests.post('https://graph.facebook.com/v2.6/me/messages?' + qs, json=data)
print(resp.content)