from picamera import PiCamera
import time
import json
import pybase64
import datetime
import requests
//CAPTURING A PICTURE AND SAVING IT//
camera = PiCamera()
camera.start_preview()
time.sleep(0.5)
camera.capture("/home/pi/Desktop/rasppi/images/image2.jpg")
camera.stop_preview()
//CONVERTING INTO BASE64 STRING//
with open("/home/pi/Desktop/rasppi/images/image2.jpg", "rb") as file:
string = pybase64.b64encode(file.read())
file.close()
url = "192.168.139.87:9000/upload"
payload = string
//USING POST REQUEST TO UPLOAD IMAGE ON URL//
response = requests('post', url, data = payload)
now = datetime.datetime.now()
time = str(now)
obj = json.loads(response.text)
id = ["emp_id"]
var = "Identified person is : " + id
print(var)
print(time)
It generates following error:
Traceback (most recent call last):
File "get_image.py", line 22, in <module>
response = requests('post', url, data = payload)
TypeError: 'module' object is not callable
This code deals with the program for capturing a picture with the help of raspberry pi and then POST it on the url. The POST request command shows some error.
You want:
response = requests.post(url, data=payload)
Related
It´s muy first time developing an API. It's very simple. here is my code:
from flask import Flask, Response
from flask import request
from flask import jsonify
import pyodbc
from sqlalchemy import create_engine,Integer
import pandas as pd
import urllib
app = Flask(__name__)
params = urllib.parse.quote_plus("DRIVER={SQL Server Native Client 11.0};"
"SERVER=xxx.xx.x.x;"
"DATABASE=xxxxx;"
"UID=xxxx;"
"PWD=xxxx")
engine = create_engine('mssql+pymssql://xxxx:xxxx#xxx.xx.x.x/xxxx')
sql_talle = "RSCV_TALLE_PARA_CADA_MARCA.sql"
fd1 = open(sql_talle, 'r')
sqlFile1 = fd1.read()
fd1.close()
DF1 = pd.read_sql_query(sqlFile1,engine)
DF1.insert(14, 'PROVEEDOR', DF1.pop('PROVEEDOR'))
periodo=DF1['YEARMONTH_DATE'].drop_duplicates()
NIKE=DF1.loc[DF1['MARCA'] == 'NIKE']
NIKE=NIKE.to_dict('records')
#app.route('/NIKE',methods = ['GET'])
def show_codigo_Agrupador():
if request.method == 'GET':
response = jsonify({'NIKE':NIKE})
response.status_code = 200
return response
if __name__ == "__main__":
app.run(debug=True)
it´s working fine!
when I run the .py on a terminal I get that it´s Running on http://127.0.0.1:5000
After that I try to do a request on another .py, simulating an external user:
import requests
import json
url = 'http://127.0.0.1:5000/NIKE'
r=requests.get(url)
response=r.text
j=response.json()
print(j)
but I get this error:
Traceback (most recent call last):
File "c:\Users\mvazquez\DABRA\FLASK_API\prueba_request_api.py", line 7, in <module>
j=response.json()
AttributeError: 'str' object has no attribute 'json'
I have these questions:
what am I doing wrong here?
my data is based on an sql query, I need to run the script every day to have refresehed data or it is refreshed when request is done? (sorry if it's stupid, I have no idea about API)
thanks in advance!
I am trying to write a lambda function in 3.8 version but I am getting error while doing a get requests
[ERROR] AttributeError: module 'botocore.vendored.requests' has no attribute 'get' Traceback (most recent call last): File "/var/task/lambda_function.py"
import json
from botocore.vendored import requests
def lambda_handler(event, context):
request = event['Records'][0]['cf']['request']
print (request)
print(request['headers'])
token = request['headers']['cookie'][0]['value'].partition("=")[2]
print (token)
print(type(request['uri']))
consumer_id = request['uri'].rpartition('/')[-1]
print (consumer_id)
#Take the token and send it somewhere
token_response = requests.get(url = 'https://url/api/files/' + consumer_id, params = {'token': token})
print (token_response)
return request
I tried following this blog https://aws.amazon.com/blogs/compute/upcoming-changes-to-the-python-sdk-in-aws-lambda/
but not able to identify which layer to add. Could anyone please help
According to the link you provided and assuming that request was correctly installed you should be using
import requests
instead of
from botocore.vendored import requests
I am trying to send a compressed numpy array (compressed with zlib) to the flask server with post request, but the compressed bytes object is getting changed in the server end. How to properly send the bytes object with requests post request so that I can decompress on the server end?
server.py
from flask import Flask
from flask_restful import Resource, Api, reqparse
import json
import numpy as np
import base64
# compression
import zlib
app = Flask(__name__)
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument('imgb64')
class Predict(Resource):
def post(self):
data = parser.parse_args()
if data['imgb64'] == "":
return {
'data':'',
'message':'No file found',
'status':'error'
}
img = data['imgb64']
print('rec')
# decompress
print(type(img))
print(img)
dec = zlib.decompress(img) # this gives me error
if img:
pass
return json.dumps({
'data': 'done',
'message':'darknet processed',
'status':'success'
})
return {
'data':'',
'message':'Something when wrong',
'status':'error'
}
api.add_resource(Predict,'/predict')
if __name__ == '__main__':
app.run(debug=True, host = '0.0.0.0', port = 5000, threaded=True)
client.py
import numpy as np
import base64
import zlib
import requests
frame = np.random.randint(0,255,(5,5,3)) # dummy rgb image
# compress
data = zlib.compress(frame)
print('b64 encoded')
print(data)
print(len(data))
print(type(data))
r = requests.post("http://127.0.0.1:5000/predict", data={'imgb64' : data}) # sending compressed numpy array
This gives me the following error:
TypeError: a bytes-like object is required, not 'str'
So, I tried to convert the string to bytes object:
dec = zlib.decompress(img.encode()) # this gives me error
But, this one also gives me an error:
zlib.error: Error -3 while decompressing data: incorrect header check
I tried with other encodings, they also failed.
One thing I noticed is, when I print the compressed bytes in the client end, it reads:
b'x\x9c-\xcf?J\x82q\x00\x06\xe0\x0ftrVP\\C\xf4\x06\x9268\t\xcdR\x8ej.F\xa0\xe0\xd0\xa6\xa3\xe0V\x07\x10\x1cL\xc8\xd1\x03\xd4\xe4\t\x0c\x12\x84\xb6D\x0c#\xbc\x80O\xf0\x1b\x9e\xf5\xfdS\x89\xa2h\xcf\x9a\x03\xef\xc4\xf8cF\x92\r\xbf4i\x11g\xc83\x0f\x8c\xb9\xa2#\x8e\x1bn\xd91g\xc0\x91%\xd7\xdc\xf3M\x83<i:L\xa8\xf1\x19\xfa\xffw\xfd\xf0\xc5\x94:O\x9cH\x85\xcc6#\x1e\xc3\xf6\x05\xe5\xa0\xc7\x96\x04]J\\\x90\xa1\x1f~Ty\xe1\x8d\x15w|P\xe4\x95K\xb2!\xe3\x0cw)%I'
But on the server end, the received string is completely different:
�4ig�3���#�n�1g��%���M�<i:L����w��Ŕ:O�H��6#���ǖ]J\��~Ty�w|P�K�!�w)%I
I also tried to send the bytes as string, by
r = requests.post("http://127.0.0.1:5000/predict", data={'imgb64' : str(data)})
But, I can't decompress the data on the server end.
It seems, I can't send the zlib compressed bytes directly, so I used base64 to encode the data into ascii string.
So, in summary this worked for me, numpy array/any non-string data -> zlib compression -> base64 encode -> post request -> flask -> base64 decode -> zlib decompress
client.py
import numpy as np
import base64
import zlib
import requests
frame = np.random.randint(0,255,(5,5,3)) # dummy rgb image
# compress
data = zlib.compress(frame)
data = base64.b64encode(data)
data_send = data
data2 = base64.b64decode(data)
data2 = zlib.decompress(data2)
fdata = np.frombuffer(data2, dtype=np.uint8)
print(fdata)
r = requests.post("http://127.0.0.1:5000/predict", data={'imgb64' : data_send})
server.py
from flask import Flask
from flask_restful import Resource, Api, reqparse
import json
import numpy as np
import base64
# compression
import zlib
import codecs
app = Flask(__name__)
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument('imgb64', help = 'type error')
class Predict(Resource):
def post(self):
data = parser.parse_args()
#print(data)
if data['imgb64'] == "":
return {
'data':'',
'message':'No file found',
'status':'error'
}
#img = open(data['imgb64'], 'r').read() # doesn't work
img = data['imgb64']
data2 = img.encode()
data2 = base64.b64decode(data2)
data2 = zlib.decompress(data2)
fdata = np.frombuffer(data2, dtype=np.uint8)
print(fdata)
if img:
return json.dumps({
'data': 'done',
'message':'darknet processed',
'status':'success'
})
return {
'data':'',
'message':'Something when wrong',
'status':'error'
}
api.add_resource(Predict,'/predict')
if __name__ == '__main__':
app.run(debug=True, host = '0.0.0.0', port = 5000, threaded=True)
I have the following code that I am trying to make an API call to Poloniex according to their instructions
import urllib
import urllib.request
import json
import time
import hashlib
import codecs
import hmac
import time
Key = "whatever your key is"
Sign = "whatever your secret is"
def returnBalances(balances):
nonce = int(round(time.time()-599900000)*10)
parms = {"returnBalances":balances,
"nonce":nonce}
parms = urllib.parse.urlencode(parms)
hashed = hmac.new(b'Sign',digestmod=hashlib.sha512)
signature = hashed.hexdigest()
headers = {"Content-type":"application/x-www-form-urlencoded",
"Key":Key,
"Sign":signature}
conn = urllib.request.urlopen("https://poloniex.com")
conn.request("POST","/tradingApi",parms,headers)
response = conn.getresponse()
print(response.status,response.reason)
returnBalances('balances')
When I run this I get this error message
HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden
Can someone please help?
You can catch HTTP errors with urllib.error.HTTPError
POST data should be bytes, so you have to encode parms
urllib.request.urlopen returns a HTTPResponse object, which has no request method.
If you want to set headers and other parameters you should use urllib.request.Request
According to the api docs the post parameters should be 'nonce' and 'command', so i modified your function to accept 'returnBalances' as a parameter and use it in parms["command"]
def api_call(command):
nonce = int(round(time.time()-599900000)*10)
parms = {"command":command, "nonce":nonce}
parms = urllib.parse.urlencode(parms).encode()
hashed = hmac.new(Sign.encode(), parms, digestmod=hashlib.sha512)
signature = hashed.hexdigest()
headers = {"Key":Key, "Sign":signature}
req = urllib.request.Request("https://poloniex.com/tradingApi", headers=headers)
try:
conn = urllib.request.urlopen(req, data=parms)
except urllib.error.HTTPError as e:
conn = e
print(conn.status,conn.reason)
return json.loads(conn.read().decode())
balances = api_call("returnBalances")
Here is the related code
import logging
logging.getLogger('googleapicliet.discovery_cache').setLevel(logging.ERROR)
import datetime
import json
from flask import Flask, render_template, request
from flask import make_response
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
from oauth2client.client import AccessTokenCredentials
...
#app.route('/callback_download')
def userselectioncallback_with_drive_api():
"""
Need to make it a background process
"""
logging.info("In download callback...")
code = request.args.get('code')
fileId = request.args.get('fileId')
logging.info("code %s", code)
logging.info("fileId %s", fileId)
credentials = AccessTokenCredentials(
code,
'flex-env/1.0')
http = httplib2.Http()
http_auth = credentials.authorize(http)
# Exports a Google Doc to the requested MIME type and returns the exported content. Please note that the exported content is limited to 10MB.
# v3 does not work? over quota?
drive_service = build('drive', 'v3', http=http_auth)
drive_request = drive_service.files().export(
fileId=fileId,
mimeType='application/pdf')
b = bytes()
fh = io.BytesIO(b)
downloader = MediaIoBaseDownload(fh, drive_request)
done = False
try:
while done is False:
status, done = downloader.next_chunk()
logging.log("Download %d%%.", int(status.progress() * 100))
except Exception as err:
logging.error(err)
logging.error(err.__class__)
response = make_response(fh.getbuffer())
response.headers['Content-Type'] = 'application/pdf'
response.headers['Content-Disposition'] = \
'inline; filename=%s.pdf' % 'yourfilename'
return response
It is based on some code example of drive api. I am trying to export some files from google drive to pdf format.
The exception comes from the line
response = make_response(fh.getbuffer())
It throws the exception:
TypeError: 'memoryview' object is not callable
How can I retrieve the pdf content properly from the fh? Do I need to further apply some base 64 encoding?
My local runtime is python 3.4.3
I have used an incorrect API. I should do this instead:
response = make_response(fh.getvalue())