I have created a post route using werkzeug.
http://localhost:8000/v1/api/<serial_id>/data
def url_map():
tenants = [
Submount(
"/<serial_id>",
[
Rule(
"/data",
methods=["POST"],
endpoint=getData,
)
],
)
]
api = [Submount("/api", api)]
rules = [Submount("/v1", api)]
return Map(rules, strict_slashes=False)
def getData(self, request, serial_id):
logger.error('88888888888888888888888888888888888888888888888888888888888')
logger.error(serial_id)
return {'status': 'ok'}
I am sending request to the path:
requests.post('http://localhost:8000/v1/api/<serial_id>/data',
data= json.dumps({'data':'data'}),
params={'serial_id':1}
)
The problem is instead of printing 1 it print serial_id as <serial_id>.
Expected is:
88888888888888888888888888888888888888888888888888888888888
1
Actual is:
88888888888888888888888888888888888888888888888888888888888
<serial_id>
As #Md Jewele Islam states in the comments the url variable must be like:
url = 'http://localhost:8000/v1/api/{}/data'.format(str(serial_id))
and the request must be sent like:
import json
res = requests.post(url , data= json.dumps({'data':'data'}), params={'serial_id':1})
So you can print the response by:
print(res.text)
Related
I am using Boto3 in python to get the data. I have created an API with the help of Flask in Python. I am firing a query and trying to retrieve the data, but it is too large hence trying to use Paginator but it returns NULL everytime.
paginator = DataClient.get_paginator('get_statement_result')
PaginatorResponse = paginator.paginate(
Id=request.args.get('Id'),
PaginationConfig={
'MaxItems': request.args.get('max-items'),
'StartingToken': request.args.get('start-token')
}
)
RESPONSE['redshift'] = PaginatorResponse
response = app.response_class(
response = json.dumps(RESPONSE ,sort_keys=True,indent=1,default=default),
status = STATUSCODE,
mimetype = 'application/json'
)
This is the paginator code which returns NULL on same query ID which I use in the get_statement_result directly. Here is the code for the same:
RecordsResponse = DataClient.get_statement_result(Id=request.args.get('Id'))
RESPONSE['redshift'] = RecordsResponse
RESPONSE['records'] = convertRecords(RecordsResponse)
response = app.response_class(
response = json.dumps(RESPONSE ,sort_keys=True,indent=1,default=default),
status = STATUSCODE,
mimetype = 'application/json'
)
Result ScreenShot from Get Statement Result
Result ScreenShot from Get Paginator
Not able to understand where I am going wrong, and how to get it done.
1) I require a function which should publish a post with the given message and photo.
One can use the page ID and access tokens provided in self.page_id and self.page_access_token
def __init__(self):
self.page_id = Facebook.get_access_token('FACEBOOK_PAGE_ID')
self.page_access_token = Facebook.get_access_token('FACEBOOK_PAGE_ACCESS_TOKEN')
2) To find which API to hit, check out developer section of the Facebook API: https://developers.facebook.com/docs/graph-api/reference/page/photos/#example-2
3) The function should not return anything.
def publish_photo_msg(self, message, image_url):
#your code here
return
Please help.
python
params = (
('access_token', self.page_access_token),
)
Next, let us fix the data dictionary:
python
data = {
'url': image_url,
'caption': 'this is the caption'
}
Now, let’s proceed to the URL. There are many ways to set this. Here is one way:
python
url = 'https://graph.facebook.com/v5.0/' + self.page_id + '/photos?access_token=' + self.page_access_token
Since we have stored the access_token in the params tuple, let’s make use of it in the requests.post() call.
python
url = 'https://graph.facebook.com/v5.0/' + self.page_id + '/photos'
response = requests.post(url=url, params=params, data=data)
Lastly, you can also verify if your requests.post() call was successful by checking the value of the response variable:
python
print response.status_code, response.json()
For easy reference, here is the full implementation of the publish_photo_msg function with all the suggestions incorporated:
python
params = (
('access_token', self.page_access_token),
)
data = {
'url': image_url,
'caption': message
}
url = 'https://graph.facebook.com/v5.0/' + self.page_id + '/photos'
response = requests.post(url=url, params=params, data=data)
print(response.status_code, response.json())
I have this P2P python code, and I am trying to send a POST request from it to flask:
On my P2P side I have:
...
for reply in con:
jsonData = json.loads(reply)
print(jsonData)
print(type(jsonData) is dict, tuple)
data = urlencode(jsonData)
print(data + " : urlencode")
data = data.encode()
print(data.__class__)
req = urllib.request.Request("http://0.0.0.0:5000/validate", data)
response = urllib.request.urlopen(req)
#res = response.read()
print(response.read().decode('utf8') + " : response in alice")
For my flask code I have:
#app.route('/validate', methods=['POST'])
def validate():
print(request.args)
request args is always output as:
ImmutableMultiDict([])
The output for the P2P side is:
{'index': 2043, 'message': 'New Block Forged', 'previous_hash': 'fa4a49cd092869db788490e79a933e7a45107ce513523500e5cd9c85e25426de', 'proof': 168158, 'transactions': [{'amount': 1, 'recipient': '6760d061731c493e94897164c2362476', 'sender': '0'}]}
True <class 'tuple'>
index=2043&message=New+Block+Forged&previous_hash=fa4a49cd092869db788490e79a933e7a45107ce513523500e5cd9c85e25426de&proof=168158&transactions=%5B%7B%27amount%27%3A+1%2C+%27recipient%27%3A+%276760d061731c493e94897164c2362476%27%2C+%27sender%27%3A+%270%27%7D%5D : urlencode
<class 'bytes'>
{
"add": true
}
: response in alice
As you can see, the data for urllib.request.urlopen looks correct. Why isn't it getting through to the flask side?
You are making the POST request to validate endpoint. And request.args is only return the url querystring. So the real data will be available in request.form.
Answer
Please make the GET request... so data will be available in request.args
data = urllib.parse.urlencode(json_data)
url = 'http://localhost:5000?{}'.format(data)
with urllib.request.urlopen(url) as response:
pass
I am using requests 2.12.1 library in Python 2.7 and Django 1.10 for consume web services. When I use a session for save cookies and use persistence, and pass 10 seconds ~ without use any web service, my view regenerates the object requests.Session()...
This makes web service doesn't serve me, because my view has changed the cookies.
This is my Views.py:
client_session = requests.Session()
#watch_login
def loginUI(request):
response = client_session.post(URL_API+'login/', data={'username': username, 'password': password,})
json_login = response.json()
#login_required(login_url="/login/")
def home(request):
response_statistics = client_session.get(URL_API+'statistics/')
log('ClientSession: '+str(client_session))
try:
json_statistics = response_statistics.json()
except ValueError:
log('ExcepcionClientSession: '+str(client_session))
return logoutUI(request)
return render(request, "UI/home.html", {
'phone_calls' : json_statistics['phone_calls'],
'mobile_calls' : json_statistics['mobile_calls'],
'other_calls' : json_statistics['other_calls'],
'top_called_phones' : json_statistics['top_called_phones'],
'call_ranges_week' : json_statistics['call_ranges_week'],
'call_ranges_weekend' : json_statistics['call_ranges_weekend'],
'access_data' : accessData(request.user.username),
})
def userFeaturesFormInit(clientRequest):
log('FeaturesClientSession: '+str(client_session))
response = client_session.get(URL_API+'features/')
try:
json_features = response.json()
except ValueError as e:
log('ExcepcionFeaturesClientSession: '+str(client_session))
raise e
Thank you.
I fixed it specifying cookies manually, and saving it in the request.
client_session = requests.Session()
response = client_session.post(URL_API+'login/', {'username': username, 'password': password,})
request.session['cookiecsrf'] = client_session.cookies['csrftoken']
request.session['cookiesession'] = client_session.cookies['sessionid']
And sending it in the gets/posts:
cookies = {'csrftoken' : request.session['cookiecsrf'], 'sessionid': request.session['cookiesession']}
response = requests.get(URL, cookies=cookies)
import requests
import json
import urllib2
data = '{"userId":"faraz#wittyparrot.com","password":"73-rRWk_"}'
response = requests.post(url, data=data, headers=
{"ContentType":"application/json"})
dataa = json.loads(response.content)
a = dataa['accessToken']
print a
tiketId = a['tokenType'] + a['tokenValue']
print tiketId
wit = '{ "name": "wit along with the attachment","parentId": "6d140705-c178-4410-bac3-b15507a5415e", "content": "faraz khan wit", "desc": "This is testing of Authorization wit","note": "Hello auto wit"}'
response = requests.post(URLcreatewit, data=wit , headers={"Content-Type":"application/json","Authorization":tiketId} )
createwit = json.loads(response.content)
print createwit
Id = createwit['id']
WitId = Id
print WitId
so here witId is 2d81dc7e-fc34-49d4-b4a7-39a8179eaa55 that comes as response
now i want to use that witId into below json as a input:
Sharewit = '{ "contentEntityIds":["'+WitId+'"],"userEmailIds": ["ediscovery111#gmail.com"],"permission":{"canComment": false,"canRead": true,"canEditFolderAndWits": false,"canFurtherShare": false,"canEditWits": false}, "inherit":true}'
response = requests.post(URLcreatewit, data= Sharewit , headers={"Content-Type":"application/json","Authorization":tiketId} )
print response.status_code
so in the last json, it seems it does not take the value of witId and gives 400 status error
I was trying to do the similar thing and Here is how I have done.
Assuming the rest api responds with a Json Object.
id = response.json()["id"]
However if the response is a Json Array
Looped in through the array and got the ids appended to an array
item = []
for item in response.json():
ids.append(item["id")
Also, I have used a Json Object - to be able to change values.
Instead of creating it as Json String.
sharewit["userEmailIds"] = ["ediscovery111#gmail.com"]
sharewit["contentEntityIds"] = [id]
response = requests.post(URLcreatewit, data=json.dumps(sharewit), headers={"Content-Type":"application/json","Authorization":tiketId} )