Python - How to Save 2 values outputf.write - python

I am trying to save user:password if got 200 response status code to a textfile.
but it only saves one value "User" I dunno why. I've tried to add multi values with failed attempts.
outputFilepath = "validaccounts.txt"
def OutPut(text):
with open(outputFilepath, "a") as outputf:
outputf.write("{}\n".format(text))
#headers removed#
#Payload removed#
response = requests.post(url, data=payload, headers=headers, proxies=proxies, timeout=10)
#print(response.text)
if response.status_code == 200:
OutPut(user, password)
except:
pass
How to make it save User:password format in textfile what needed to be edited in outputf.write?
Note: I've removed the payload + headers, I just need to fix the output save user:password part.
Thank you,
regards.

Fixed by doing the following:
def OutPut(text, text1):
with open(outputFilepath, "a") as outputf:
outputf.write("{}:{}\n".format(text, text1))
output(user, password)

Related

Pysnow Usage of sysparm_query_category

As I cannot see any reference on how to use properly the sysparm_query_category, may I confirm on how did you append the sysparm_query_category in get request?
Added below line of codes. I hope someone can help and guide me as I'm new to ServiceNow. Thanks!
from pysnow import Client
...
resource = self.client.resource(api_path=F"/table/{table}")
resource.parameters.add_custom({"sysparm_query_category": "cat_read_generic"})
request = resource.get(query=query, fields=fields)
https://developer.servicenow.com/dev.do#!/reference/api/sandiego/rest/c_TableAPI
I am not aware pysnow API. I hope this helps. Else refer to the comment above.
#Need to install requests package for python
#easy_install requests
import requests
# Set the request parameters
url = 'https://demonightlycoe.service-now.com/api/now/table/incident?sysparm_query=category%3Dcat_read_generic&sysparm_limit=1'
# Eg. User name="admin", Password="admin" for this code sample.
user = 'admin'
pwd = 'admin'
# Set proper headers
headers = {"Content-Type":"application/json","Accept":"application/json"}
# Do the HTTP request
response = requests.get(url, auth=(user, pwd), headers=headers )
# Check for HTTP codes other than 200
if response.status_code != 200:
print('Status:', response.status_code, 'Headers:', response.headers, 'Error Response:',response.json())
exit()
# Decode the JSON response into a dictionary and use the data
data = response.json()
print(data)
Upon checking and testing, we can use the add_custom
client.parameters.add_custom({'foo': 'bar'})
that would be additional to the parameters like &foo=bar
https://pysnow.readthedocs.io/en/latest/usage/parameters.html

Python file upload using request multipartencoder with json bdoy

I have the following python function where im trying to upload a file over to an API that accepts a file as multipart stream. The API correctly works with postman, however im struggling to identify the problem here.
I have parameters (json body) to post to the API along with the file which I have tried to encode inside my mp_encoder variable.
def callAPIwithFile(apiData,apiUrl):
file_ids = ''
jsonData = {'type':apiData['type'],'fromId':apiData['fromid'],'toUserIds':apiData['userIds'],'toGroupIds1':apiData['groupIds'],'toDepartmentIds1':apiData['departmentIds'],'subject':apiData['subject'],'body':apiData['body'],'attachment':apiData['attachment'],'report':apiData['report']}
mp_encoder = MultipartEncoder(fields={'type':apiData['type'],'fromId':apiData['fromid'],'toUserIds':apiData['userIds'],'toGroupIds1':apiData['groupIds'],'toDepartmentIds1':apiData['departmentIds'],'subject':apiData['subject'],'body':apiData['body'],'attachment':apiData['attachment'],'report':apiData['report'],'file': (apiData["attachment"], open(apiData["attachment"], 'rb'), 'application/vnd.ms-excel')})
print mp_encoder
headers = {'Authorization': 'Bearer jwt'}
resp = requests.post(apiUrl,headers=headers,data=mp_encoder)
print resp.text
print "status code " + str(resp.status_code)
if resp.status_code == 201:
print ("Success")
data = json.loads(resp.text)
file_ids = data['file_ids']
print file_ids
else:
print ("Failure")
On running the code I get the following errors :
{"statusCode":400,"message":["type must be a valid alpha, beta, Or gamma","body should not be empty"],"error":"Bad Request"}
status code 400
Failure
As per my understanding the JSON Body that im trying to post to the API is not being recognised correctly. How do I go about this?
Please note, I have tried using request.post(apiUrl,file=files,data=data,header=header) which results in an error of unexpected field.
The below answer could solve my problem :
headers = {'Authorization': 'Bearer '+token}
mydict = dict(type=apiData['type'], fromId=apiData['fromid'], toUserIds1=apiData['userIds'], toGroupIds=apiData['groupIds'], toDepartmentIds1= apiData['departmentIds'], subject= apiData['subject'], body= apiData['body'], attachment= apiData['attachment'], report= apiData['report'])
resp=requests.post(apiUrl, headers = headers, files=dict(attachment=(apiData["attachment"], open(apiData["attachment"], 'rb'), 'application/vnd.ms-excel')),data=mydict)

Slack Webhook - returning invalid_payload

I'm trying to send data to a slack webhook but I keep getting an invalid_payload response.
My results variable from below looks like this if i print it in my script:
{u'results': [{u'TunnelID': 11111}]}
webhook_url = 'https://hooks.slack.com/services/xxx/xxx/xxx'
response = requests.post(
webhook_url, data=json.dumps(results),
headers={'Content-Type': 'application/json'}
)
if response.status_code != 200:
raise ValueError(
'Request to slack returned an error %s, the response is:%s'
% (response.status_code, response.text)
)
I'm sure its a problem with the way my results variable is formatted, but I can't seem to find the right way to format it.
Perhaps you mean to include results as the message itself? In which case, something like this?
response = requests.post(
webhook_url, json={'text': str(results)},
headers={'Content-Type': 'application/json'}
)

Issue with writing recursive function. discord

I am trying to adapt this script so that even if multiple messages are sent at the same time the script will just keep trying until they are let through.
The original script is: https://github.com/4rqm/dhooks
My version is:
def post(self):
"""
Send the JSON formated object to the specified `self.url`.
"""
headers = {'Content-Type': 'application/json'}
result = requests.post(self.url, data=self.json, headers=headers)
if result.status_code == 400 or result.status_code == 429:
print(result.status_code)
#its the line below that does not work.
post(self)
else:
print("Payload delivered successfuly")
print("Code : "+str(result.status_code))
time.sleep(2)

How to upload IMAGE as run attachment in QC with HP ALM REST API

I have searched for days and trying to solve the problem by myself, unsuccessfully.
I found that is possible to attach files to QC Run (using Python or Ruby) with something like this (send it in a Rest Request):
Content example:
headers = {'accept': 'application/xml', 'Content-Type': 'multipart/form-data; boundary=exampleboundary'}
--exampleboundary
Content-Disposition: form-data; name="filename"
example.txt
--exampleboundary
Content-Disposition: form-data; name="description"
Here is the text that describes example.txt
--exampleboundary
Content-Disposition: form-data; name="file"; filename="example.txt"
Content-Type: text/plain
ContentOfFile
--exampleboundary--
This really works but (apparently) only for text files (.txt). I really need to upload some images like test evidences/screenshots.
How can I achieve that? Can anyone help me to solve this problem?
I am sending the request content like this:
import requests
#login
response = requests.get("http://"+server+"/qcbin/authentication-point/authenticate", auth=(user,pwd))
# Get ALM token in dict format
token = response.cookies.get_dict()
requests.post(url, content, cookies=token, headers=headers_image)
Thank you.
Referring to Barney's comment I leave here the answer that solved the problem.
def upload_result_file(self, run_id, report_file, token):
url = "http://%s/qcbin/rest/domains/%s/projects/%s/runs/%s/attachments" % (server, domain, project, run_id)
payload = open(report_file, 'rb')
headers_file = {}
headers_file['Content-Type'] = "application/octet-stream"
headers_file['slug'] = "test-results." + report_file[report_file.rfind(".")+1: ]
response = requests.post(url, headers=headers_file, data=payload, cookies=token)
if not (response.status_code == 200 or response.status_code == 201):
print "Attachment step failed!", response.text, response.url, response.status_code
return
From:
https://github.com/macroking/ALM-Integration/blob/master/ALM_Integration_Util.py
In API:
if not request.form:
abort(405)
request.form.get('file', "")
file = file.read().encode("base64")
In POST call:
-F 'file=#/var/path/to/my/file/test.png' http://xxx.xx.xx.xxx:8080/todo/api/v1.0/tasks
Thank koxta for sharing this solution.
With this solution, I can upload a RobotFramework's log file as an attachment of a test run successfully.
Share my code:
def upload_log(self, entity_type, entity_id, file_name):
qurl = '%s/qcbin/rest/domains/%s/projects/%s/%s/%s/attachments' %(self._url, self._domain, self._project, entity_type, entity_id)
headers = self._headers
headers['Content-Type'] = 'application/octet-stream'
headers['slug'] = 'log.' +file_name[file_name.rfind(".")+1: ]
print (headers)
if os.path.isfile(file_name):
with open(file_name, 'rb') as log_file:
binary_data = log_file.read()
print (binary_data)
response = self.session.post(qurl, data=binary_data, headers=headers)
print (response.text)
if response.status_code != 201:
raise Exception('Failed to upload %s - code=%s message=%s' %(file_name, response.status_code, response.text))

Categories