I have written python wrapper for web interface here to print the result of online computation on the terminal. Input to this computation are given through the code.
The program I have done is:
import re
import mechanize
import sys
import os
import urlparse
def calc_relatedness():
br = mechanize.Browser()
br.open("http://ws4jdemo.appspot.com/")
br.select_form(nr = 0)
br["w1"] = "tree#n#01"
br["w2"] = "trunk#n#01"
response = br.submit()
print response
if __name__ == "__main__":
calc_relatedness()
and output of above program is:
<response_seek_wrapper at 0x1ef2878 whose wrapped object = <closeable_response at 0x1efe170 whose fp = <socket._fileobject object at 0x1e8cb50>>>
Can anyone tell me what is the meaning of this output?
Expected output from web computation is:
wup( tree#n#1 , trunk#n#1 ) = 0.4762
jcn( tree#n#1 , trunk#n#1 ) = 0.0706
lch( tree#n#1 , trunk#n#1 ) = 1.2040
lin( tree#n#1 , trunk#n#1 ) = 0.1620
res( tree#n#1 , trunk#n#1 ) = 1.3696
path( tree#n#1 , trunk#n#1 ) = 0.0833
lesk( tree#n#1 , trunk#n#1 ) = 1066
hso( tree#n#1 , trunk#n#1 ) = 4
The output that you see is actually the string representation of the response object, defined in its class. You see, response actually contains more than the response body itself, it has other information like headers and url, too. Based on this code, if you want to get the response body, you should change the last line in calc_relatedness() to:
print response.read()
You can get some information about response by calling response.info() and response.geturl().
Related
I am making a python script using API of a free test automation website called TestProject.
Link to their API: https://api.testproject.io/docs/v2/
Basically what i want to do is grab pdf of reports of all tests and save them somewhere.
But to make the GET request to do that i first need projectID and jobID which i already wrote functions getting them and saving them in the array.
But now i have a problem where its looping through both lists and not using correct projectID and jobID and its throwing errors because it does not exist.
So what i need is something to check if jobID is in projectID so that way i can make a GET request to get all the executionID's to get the PDF of the report.
I am kinda new to programming so i would love any help i can get. If anyone has any better solutions please feel free to let me know.
My script:
import requests
import json
import csv
from datetime import datetime
from jsonpath_ng import jsonpath, parse
API_key = 'api_key'
headers = {'Authorization':'{}'.format(API_key)}
list_projectId = []
list_jobId = []
list_executionId = []
ParseData_projectId = parse('$..id')
ParseData_jobId = parse('$..id')
ParseData_executionId = parse('$..id')
def parsing (response,ParseData,list_data):
# parses data and appends it to the list
Data = json.loads(response)
Parsaj = ParseData
Podatki = Parsaj.find(Data)
for i in range(0, len(Podatki)):
vrednost = Podatki[i].value
list_data.append(vrednost)
def projectId():
# gets all projectId's and saves them in list_projectId
url = 'https://api.testproject.io/v2/projects?_start=0'
response = requests.get(url,headers=headers)
response_json = response.json()
converted = json.dumps(response_json)
parsing(converted,ParseData_projectId,list_projectId)
def jobId():
# gets all jobId's and saves them in list_jobId
for i in range(0, len(list_projectId)):
id = list_projectId[i]
url = 'https://api.testproject.io/v2/projects/{}'.format(id) + '/jobs?onlyScheduled=false&_start=0'
response = requests.get(url,headers=headers)
response_json = response.json()
converted = json.dumps(response_json)
parsing(converted,ParseData_jobId,list_jobId)
def executionId():
# Their API link:
# https://api.testproject.io/v2/projects/{projectId}/jobs/{jobId}/reports?_start=0
# the for loop below does not work here is where i need the help:
for i in range(0, len(list_projectId)):
project_id = list_projectId[i]
job_id = list_jobId[i]
url = 'https://api.testproject.io/v2/projects/{}'.format(project_id) + '/jobs/{}'.format(job_id) + '/reports?_start=0'
response = requests.get(url,headers=headers)
response_json = response.json()
converted = json.dumps(response_json)
parsing(converted,ParseData_executionId,list_executionId)
projectId()
print("----------LIST PROJECT ID: ----------")
print(list_projectId)
print("")
jobId()
print("----------LIST JOB ID: ----------")
print(list_jobId)
executionId()
print("----------LIST EXECUTION ID: ----------")
print(list_executionId)
you have to use 'in' operator to check the value exist in the list data structure.
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)
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} )
I just used gogole api to search via python and used this script below
import urllib
import json as m_json
query = raw_input ( 'Query: ' )
query = urllib.urlencode ( { 'q' : query } )
response = urllib.urlopen ( 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&' + query ).read()
json = m_json.loads ( response )
results = json [ 'responseData' ] [ 'results' ]
for result in results:
url = result['url'] # was URL in the original and that threw a name error exception
print ( url )
and after that I got result below :
Query: inurl:"readnews.php?id="
http://www.idmantv.az/readnews.php%3Fid%3D14999
http://www.kanda.com/readnews.php%3Fid%3D9
http://www.dcfever.com/news/readnews.php%3Fid%3D12573
http://www.thegrower.org/readnews.php%3Fid%3D6c0p5n0e8i6b
but I want this url in normal form like
http://www.idmantv.az/readnews.php?id=14999
How to do that with python?
Use urllib.unquote or urllib.unquote_plus to decode %-encoded string:
>>> urllib.unquote('http://www.idmantv.az/readnews.php%3Fid%3D14999')
'http://www.idmantv.az/readnews.php?id=14999'
I'm creating a webpy app that has multiple forms that take input and than that input is executed by python, however I keep getting an Attribute Error on Key Error on the first form : AttributeError : 'Pycode' , no clue why this is happening, here's the code :
import web
from Commands import *
import Commands
operations = [method for method in dir(port) if callable(getattr(port, method))]
test = port(0)
def make_text(string):
return string
urls = ('/', 'tutorial')
render = web.template.render('templates/',globals={'oper':operations})
app = web.application(urls, globals())
pythonCode = web.form.Form(
web.form.Textarea(name='', class_='Pycode', id='Pycode')
)
setProportionalGain = web.form.Form(
web.form.Textbox(name='Set Proportional Gain', class_='SG', id='SG')
)
setIntegralGain = web.form.Form(
web.form.Textbox(name='Set Inegral Gain', class_='SI', id='SI')
)
setDerivativeGain = web.form.Form(
web.form.Textbox(name='Set Derivative Gain', class_='SD', id='SD')
)
class tutorial:
def GET(self):
code = pythonCode()
proportional = setProportionalGain()
integral = setIntegralGain()
derivative = setDerivativeGain()
return render.tutorial(code,proportional,integral,derivative, "Input Command for ohm")
def POST(self):
form = pythonCode()
proportional = setProportionalGain()
integral = setIntegralGain()
derivative = setDerivativeGain()
form.validates()
data = web.input()
print data
print data.Pycode
s = data.Pycode
proportionalGain = "test.setProportionalGain(%s)" % data.SG
integralGain = "test.setItegralGain(%s)" % data.SI
derivativeGain = "test.setDerivativeGain(%s)" % data.SD
try:
exec(proportionalGain)
exec(integralGain)
exec(derivativeGain)
exec(data.Pycode)
s = "This is Python!"
except:
pass
return s
if __name__ == '__main__':
app.run()
Check the docs of how to use form inputs. Every input should have name as it first argument and what you have in your name attributes should be description.