I got error from calling json() when trying to running - pandas

Hello i want asking somethin that i got when i tried to run my streamlit, so i got error like this on my frontend page, i import it from backend page:
i will show my code too
Predict = st.button('Predict Satisfacion Rate')
if Predict:
r = requests.post(URL, json=data)
res = r.json()
if res['code'] == 200:
res2 = (res['result']['description'])
if res2 == 'Not Satisfied':
st.markdown('**The Passenger is not Satisfied**')
col4,col5,col6 = st.columns([1,1,1])
with col5 :
st.image('Happy.jpg')
else:
st.markdown('**The Passenger is Satisfied**')
col7,col8,col9 = st.columns([1,1,1])
with col8 :
st.image('NotHappy.jpg')
else:
st.write('**Error**')
st.write(f"Details : {res['result']['description']}")
so how can i do to solve this error?
thank you.

In your code, the conversion res = r.json() is unnecessary. Unless you really need this as JSON somewhere else, you can test the status code directly from the r object as r.status_code.
After if r.status_code == 200:, you can then convert to JSON if you really need to, as you should be confident that the server returned a valid response.

Related

xhtml2pdf in django - issue link_callback

I am trying to generate a pdf from an html-template in django. Therefore i use pretty much the basic methods found in the web. The issue is that in can get it to generate the content of my template, but not the images from my media directory. I always get the following error:
SuspiciousFileOperation at /manager/createpdf/
The joined path is located outside of the base path component
Since i can get some result, i assume that nothing is wrong with my view. Here is my render_to_pdf
def render_to_pdf(template_src, context_dict):
template = get_template(template_src)
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode('UTF-8')), result, link_callback=link_callback)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
and the link_callback:
def link_callback(uri, rel):
result = finders.find(uri)
if result:
if not isinstance(result, (list, tuple)):
result = [result]
result = list(os.path.realpath(path) for path in result)
path=result[0]
else:
sUrl = settings.STATIC_URL
sRoot = settings.STATIC_ROOT
mUrl = settings.MEDIA_URL
mRoot = settings.MEDIA_ROOT
if uri.startswith(mUrl):
path = os.path.join(mRoot, uri.replace(mUrl, ""))
elif uri.startswith(sUrl):
path = os.path.join(sRoot, uri.replace(sUrl, ""))
else:
return uri
# make sure that file exists
if not os.path.isfile(path):
raise Exception( 'media URI must start with %s or %s' % (sUrl, mUrl))
return path
I am pretty much sure that the link_callback doesnt do it's purpose. But my knowledge is to little to patch it. I also assume that i configured the media directory correctly. I can access the media files in other views/templates.
Help is very appreciated, since i spend quiet some hours on this issue... A big thx to all the are going to contribute here!
OK, i found it! In the finders.py i checked the find-method. It turns out that the find method only looks for files in the static directory and disregards the media directory. i just deleted all the lins and it works now. Here is the code:
def link_callback(uri, rel):
sUrl = settings.STATIC_URL
sRoot = settings.STATIC_ROOT
mUrl = settings.MEDIA_URL
mRoot = settings.MEDIA_ROOT
if uri.startswith(mUrl):
path = os.path.join(mRoot, uri.replace(mUrl, ""))
elif uri.startswith(sUrl):
path = os.path.join(sRoot, uri.replace(sUrl, ""))
else:
return uri
if not os.path.isfile(path):
raise Exception( 'media URI must start with %s or %s' % (sUrl, mUrl))
return path

How to get more than 100 rows using Airtable API using offest?

I am really new to the Airtable API and for some reason connecting the API this way did not work.
at = airtable.Airtable('Base_Key', 'Airtable_Key')
But I got it working this way -
get_url = ‘https://api.airtable.com/v0/BASE_ID/TABLE_NAME’
get_headers = {
‘Authorization’: ‘Bearer API_KEY’ }
Response = requests.get(get_url, headers=get_headers)
Response_Table = Response.json()
However, this fetches only the first 100 records and am reading about offset and pagination but I am unable to figure how to incorporate it into this code.
Thank you for the time!
After a lot of issues, I found this solution. Posting it for anyone else facing the same problem.
global offset
offset = '0'
result = []
while True :
url = "https://api.airtable.com/v0/BASE_ID/TABLE_NAME"
querystring = {
"view":"Published View",
"api_key":"YOUR_KEY",
"offset": offset}
try :
response= requests.get(url, params=querystring)
response_Table = response.json()
records = list(response_Table['records'])
result.append(records)
#print(records[0]['id'] , len(records))
try :
offset = response_Table['offset']
#print(offset)
except Exception as ex:
#print(ex , offset)
break
except error as e:
print(e)

Karate framework variable usage

I have this steps:
...
Then status 200
And match response.requests[0].request.url == "/endpoint"
And json body = response.requests[0].request.body
And match body == { "something": "something"}
To simplify, I tried to put response.requests[0].request in a variable called request:
...
Then status 200
And def request = response.requests[0].request
And match request.url == "/endpoint"
And json body = request.body
And match body == { "something": "something"}
I'm having the following error:
'request' is not a variable, use the form '* request <expression>' instead
I read the documentation and the use of request seems to be fine:
Given def color = 'red '
And def num = 5
Then assert color + num == 'red 5'
What am I doing wrong?
Thanks in advance.
Just make this change:
* def req = response.requests[0].request
# other steps
* request req
We simply disallow def request (using request as a variable name) because a lot of newbie users get confused. The error message has worked 99.9% of the time for users to understand what the problem is, but I guess you fall in the 0.1% :)

Invalid Runame In eapy api in getiing session

I am trying to get the ebay session id from ebay python sdk. When i make request to the api. I am getting the error invalid ru_name. I have cross checked with name. It's correct.
This is my GetSession python code, Works good for me.
from ebaysdk.exception import ConnectionError
from ebaysdk.trading import Connection as Trading
myRuName = "XXXXXXXXXXXXMyRuNameXXXXXXXXXXXXXXXXXX"
myAppID = "XXXXXXXXXXXXXMyAppIDXXXXXXXXXXXXXXXXXXX"
myDevID = "XXXXXXXXXXXXXMyDevIDXXXXXXXXXXXXXXXXXX"
myCertID = "XXXXXXXXXXXXXXMyCertIDXXXXXXXXXXXXXXXX"
myFlags = {'RuName': myRuName}
try:
api = Trading(config_file=None, appid=myAppID, devid=myDevID, certid=myCertID)
response = api.execute('GetSessionID',myFlags)
print 'SessionID = '+response.reply.SessionID
except ConnectionError as e:
print(e)
print(e.response.dict())
Hope this helps.

Sending form data with an HTTP PUT request using Grinder API

I'm trying to replicate the following successful cURL operation with Grinder.
curl -X PUT -d "title=Here%27s+the+title&content=Here%27s+the+content&signature=myusername%3A3ad1117dab0ade17bdbd47cc8efd5b08" http://www.mysite.com/api
Here's my script:
from net.grinder.script import Test
from net.grinder.script.Grinder import grinder
from net.grinder.plugin.http import HTTPRequest
from HTTPClient import NVPair
import hashlib
test1 = Test(1, "Request resource")
request1 = HTTPRequest(url="http://www.mysite.com/api")
test1.record(request1)
log = grinder.logger.info
test1.record(log)
m = hashlib.md5()
class TestRunner:
def __call__(self):
params = [NVPair("title","Here's the title"),NVPair("content", "Here's the content")]
params.sort(key=lambda param: param.getName())
ps = ""
for param in params:
ps = ps + param.getValue() + ":"
ps = ps + "myapikey"
m.update(ps)
params.append(NVPair("signature", ("myusername:" + m.hexdigest())))
request1.setFormData(tuple(params))
result = request1.PUT()
The test runs okay, but it seems that my script doesn't actually send any of the params data to the API, and I can't work out why. There are no errors generated, but I get a 401 Unauthorized response from the API, indicating that a successful PUT request reached it, but obviously without a signature the request was rejected.
This isn't exactly an answer, more of a workaround that I came up with, that I've decided to post since this question hasn't yet received any responses, and it may help anyone else trying to achieve the same thing.
The workaround is basically to use the httplib and urllib modules to build and make the PUT request instead of the HTTPClient module.
import hashlib
import httplib, urllib
....
params = [("title", "Here's the title"),("content", "Here's the content")]
params.sort(key=lambda param: param[0])
ps = ""
for param in params:
ps = ps + param[1] + ":"
ps = ps + "myapikey"
m = hashlib.md5()
m.update(ps)
params.append(("signature", "myusername:" + m.hexdigest()))
params = urllib.urlencode(params)
print params
headers = {"Content-type": "application/x-www-form-urlencoded"}
conn = httplib.HTTPConnection("www.mysite.com:80")
conn.request("PUT", "/api", params, headers)
response = conn.getresponse()
print response.status, response.reason
print response.read()
conn.close()
(Based on the example at the bottom of this documentation page.)
You have to refer to the multi-form posting example in Grinder script gallery, but changing the Post to Put. It works for me.
files = ( NVPair("self", "form.py"), )
parameters = ( NVPair("run number", str(grinder.runNumber)), )
# This is the Jython way of creating an NVPair[] Java array
# with one element.
headers = zeros(1, NVPair)
# Create a multi-part form encoded byte array.
data = Codecs.mpFormDataEncode(parameters, files, headers)
grinder.logger.output("Content type set to %s" % headers[0].value)
# Call the version of POST that takes a byte array.
result = request1.PUT("/upload", data, headers)