Printing out post data - python

i have a small script that reads and parse emails and check them against a database to assist me with resetting passwords,
unfortunately i have a bug and i can't seems to find it, currently i'm trying to visually check if there's a difference in the details (hopefully finding a pattern).
this is the relevant parts of the code:
def send_device_match_reset(username, email):
return requests.post(
'https://api.parse.com/1/requestPasswordReset',
headers=parse_headers,
data=json.dumps({
'username': username.upper(),
'email': email.encode('ascii', 'xmlcharrefreplace'),
'code': '*********'
})
)
and
if user.has_key('emailAddress'):
if user.get('emailAddress') == email:
reset_response = send_device_match_reset(username.encode('ascii', 'xmlcharrefreplace'), email.encode('ascii', 'xmlcharrefreplace'))
print "response code", reset_response.status_code
if reset_response.status_code != 200:
log.error('send_device_match_reset failed with %s:%s'%(username,email))
log.error('logging msg: %s'%(reset_response.text))
log.error('email: %s'%(email.encode('ascii', 'xmlcharrefreplace')))
log.error('username: %s'%(username.encode('ascii', 'xmlcharrefreplace')))
return
log.info('Recovered using verified email')
return message_processed(message, 'RecoveredByEmail', user=user)
now i'm trying to figure out how to print the actual headers from the #1st section "data"
inside my "log.error" debug lines.
i've been trying a direct approach by doing:
log.error(requests.post);
or
log.error(requests.post(data));
but it doesn't work - and i don't know python good enough to understand why.

log.error(requests.post); prints the function pointer
log.error(requests.post(data)); prints the result of the function, since data ist defined globally -> error
Try log.error(parse_headers) since this variable seems to be defined globally, it should work for you.
However, I normally stringify my variables like '{0}'.format(var) to enure, that I am working with a string afterwards.
EDITED:
def send_device_match_reset(username, email):
data = json.dumps({
'username': username.upper(),
'email': email.encode('ascii', 'xmlcharrefreplace'),
'code': '*********'
})
log.error('sending: data = {0}'.format(data))
return requests.post(
'https://api.parse.com/1/requestPasswordReset',
headers = parse_headers,
data = data
)

Related

Code does not post all output using jira-python in Jira

So I’m having some difficulty with my code. The code works but for some reason it only post one string instead of having all the strings posted in Jira. for example, up to the point that you see the #print(username, response), in the terminal I see all responses being printed in on screen. So it works great up to that point but the moment I send the same variable such as response through the Jira Dictionary called issue_dict, it creates the Jira but with only one of the responses and not all. I’ve tried doing something like response[x] but it just gives me an error that string indices must be integers. I’m not quite sure what else to do to be able to iterate through this so I can post all the results in the Description/body of a Jira ticket.
Ideally I would love to have both the user and the response in the description part. I’ve tried to do this with a List but I seem to get the same results where only one string gets printed. Anyone have done anything similar to post results in Jira?
Here is the code:
import jira from JIRA
for i in range(1,3):
user = os.getenv(‘USER’ + str(i))
pass = os.getenv(‘PASS’+ str(i))
headers = {
'X-Requested-With': 'Curl',
}
response =requests post('https://API-Address', headers=headers, auth=(USER,PASS))
root = ET.fromString(response.text) # Parses the JSON into text
for x in root.iter(’text’): #all this is doing is iterating through the file root and finding the text and saving the substring in response.
response = x[2].text
#print(username, response)
issue_dict = {
'project': {'id': 123},
'summary’:’My Jira Using Py',
'description': response, #This is the current issue!
'issuetype': {'name': 'Bug'},
}
new_issue = jira.create_issue(fields=issue_dict)

Smartsheet Send Email Failed by API

I'm trying to follow the API document and send an email by using my sheet.
Here is the code:
email = smartsheet.models.MultiRowEmail()
email.send_to = smartsheet.models.Recipient({
'email': 'testtest#gmail.com'
})
email.row_ids=[rowId]
email.column_ids = [columnID]
# Send rows via email
response = smartsheet_client.Sheets.send_rows(
sheet_id, # sheet_id
email)
It keeps giving me error message below,
{"response": {"statusCode": 400, "reason": "Bad Request", "content": {"errorCode": 1012, "message": "Required object attribute(s) are missing from your request: multipleRowsEmail.rowIds[], multipleRowsEmail.includeAttachments, multipleRowsEmail.includeDiscussions.", "refId": "lvre2gkxtm8m"}}}
Please advise, Thanks
Part of the problem is that you need to also specify the include_attachments property and the include_discussions property on the email object. These properties are required. (As a sidenote, I notice that the Python code snippet for Send Rows via Email in the API docs incorrectly omits these two properties...hopefully someone from Smartsheet sees this thread and can fix that issue in the docs.)
Not sure why the error message indicates that row IDs are missing from the request, as it looks like you're populating Row IDs. I'd suggest that you investigate to make sure that your [rowId] property (that you're using to set the value of email.row_ids in the request) actually is a populated array of Row IDs.
The following code example successfully sends an email that contains the specified 4 rows and 2 columns of data:
# specify IDs
sheet_id = 3932034054809476
row_ids = [4324392993613700, 5225480965908356, 657918269646724, 721881338537860]
column_ids = [6101753539127172, 4055216160040836]
# build email object
email = smartsheet.models.MultiRowEmail()
email.send_to = smartsheet.models.Recipient({
'email': 'testtest#gmail.com'
})
email.row_ids = row_ids
email.column_ids = column_ids
email.include_attachments = False
email.include_discussions = False
# send rows via email
response = smartsheet_client.Sheets.send_rows(
sheet_id,
email)

Python request.post Missing Required Param

I've been looking around and trying to get a post request to work, but I haven't found any luck. I keep getting a MISSING_REQUIRED_PARAM each time the request is being made. My following code is shown below.
def create_sign_group(group_name, header, url):
temp_header = header
temp_header['Content-Type'] = 'application/json'
temp_header['Accept'] = 'application/json'
data = {
"GroupCreationInfo": {
"groupName": group_name
}
}
res = requests.post(url + 'groups', headers=temp_header, data=json.dumps(data))
if res.status_code == 200:
print('{} Group Created...'.format(group_name))
else:
print(res.status_code)
print(res.headers)
print(res.text)
exit(res.status_code)
I've tried using json instead of data, but still getting the same error. Using a the REST API client I was able to successfully make the call. The rest client is shown below:
If anyone can point shine some knowledge and point me in the right direction I would greatly appreciate it. Take care.
You should assign headers=temp_header not headers=header. MISSING_REQUIRED_PARAM is often griping about the content type header, which, as you can see IS being included in your screenshot test.
So I figured it out, I guess I was passing the wrong payload into the data param. I changed the code to:
data = {
"groupName": group_name
}
It looks like I didn't need the "GroupCreationInfo" parameter.

Creating POST request in python, need to send data as multipart/form-data?

I'm in the process of writing a very simple Python application for a friend that will query a service and get some data in return. I can manage the GET requests easily enough, but I'm having trouble with the POST requests. Just to get my feet wet, I've only slightly modified their example JSON data, but when I send it, I get an error. Here's the code (with identifying information changed):
import urllib.request
import json
def WebServiceClass(Object):
def __init__(self, user, password, host):
self.user = user
self.password = password
self.host = host
self.url = "https://{}/urldata/".format(self.host)
mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
mgr.add_password(None, "https://{}".format(self.host), self.user, self.password)
self.opener = urllib.request.build_opener(urllib.request.HTTPDigestAuthHandler(mgr))
username = "myusername"
password = "mypassword"
service_host = "thisisthehostinfo"
web_service_object = WebServiceClass(username, password, service_host)
user_query = {"searchFields":
{
"First Name": "firstname",
"Last Name": "lastname"
},
"returnFields":["Entity ID","First Name","Last Name"]
}
user_query = json.dumps(user_query)
user_query = user_query.encode("ascii")
the_url = web_service_object.url + "modules/Users/search"
try:
user_data = web_service_object.opener.open(the_url, user_query)
user_data.read()
except urllib.error.HTTPError as e:
print(e.code)
print(e.read())
I got the class data from their API documentation.
As I said, I can do GET requests fine, but this POST request gives me a 500 error with the following text:
Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
In researching this error, my assumption has become that the above error means I need to submit the data as multipart/form-data. Whether or not that assumption is correct is something I would like to test, but stock Python doesn't appear to have any easy way to create multipart/form-data - there are modules out there, but all of them appear to take a file and convert it to multipart/form-data, whereas I just want to convert this simple JSON data to test.
This leads me to two questions: does it seem as though I'm correct in my assumption that I need multipart/form-data to get this to work correctly? And if so, do I need to put my JSON data into a text file and use one of those modules out there to turn it into multipart, or is there some way to do it without creating a file?
Maybe you want to try the requests lib, You can pass a files param, then requests will send a multipart/form-data POST instead of an application/x-www-form-urlencoded POST. You are not limited to using actual files in that dictionary, however:
import requests
response = requests.post('http://httpbin.org/post', files=dict(foo='bar'))
print response.status_code
If you want to know more about the requests lib, and specially in sending multipart forms take a look at this:
http://docs.python-requests.org/en/master/
and
http://docs.python-requests.org/en/master/user/advanced/?highlight=Multipart-Encoded%20Files

Trying to call Lifx API and getting Error in one case but not the other

Okay to save on space I will post pieces of the code. Secondly I am not a Python coder. I am usually C#. So I did my best especially when finding out there was no SWITCH STATEMENT.
So I have one method in my class to talk to Lifx Cloud API and it works fine.
def GetAllLifxs(self):
selector = 'all';
uri = '%s%s' % (self._baseUri, selector)
response = requests.get(uri, headers = self._headers)
result = LifxProxyResult(999, {})
if response:
result = LifxProxyResult(response.status_code, json.loads(response.text))
return result
The above code ends up hitting the API URL: https://api.lifx.com/v1/lights/all
I am attempting to call (this is not the only method that has this same issue) the toggle api call. I have tried a few different selectors still nothing.
The toggle code is as such:
def ToggleLight(self, value, selectorType = 'all'):
if not selectorType == 'all':
if value == None:
raise TypeError('[value] cannot be None.')
typeSwitch = {
'id': 'id:%s' % value,
'label': 'label:%s' % value,
'group_id': 'group_id:%s' % value,
'group': 'group:%s' % value,
'location_id': 'location_id:%s' % value,
'location': 'location:%s' % value,
'scene_id': 'scene_id:%s' % value
}
#If nothing just for fun Toggle ALL lights
selector = '%s/toggle' % typeSwitch.get(selectorType, 'all')
uri = '%s%s' % (self._baseUri, selector)
response = requests.get(uri, headers = self._headers)
return response
Three attempts have a Response Code of 404. The ToggleLight method in each case produces these URLs.
https://api.lifx.com/v1/lights/label:DreLight/toggle
https://api.lifx.com/v1/lights/id:d073d5127a6e/toggle
https://api.lifx.com/v1/lights/all/toggle
None of them work when I call the ToggleLight method. But here is the kicker. When I copy the URLs generated urls into this plain Python file and run it functions and manipulates the light properly.
import requests
token = "MyMagicKeyHere"
headers = {
"Authorization": "Bearer %s" % token,
}
response = requests.post('https://api.lifx.com/v1/lights/label:DreLight/toggle', headers=headers)
Python is so new to me I don't understand what my issue is. As the function that works and sets the header information with the token is the same for every method so I don't think it could be that.
Thanks in advance for the second pair of eyes. Business.
EDIT:---------------------
To go along with the answer I was given I could pay closer attention to my method chart and what I type. I messed up pretty stupidly (new word). Lesson here kids is walk away when you get stuck then come back. more staring doesn't help.
The issue appears to be calling a request.get in ToggleLight, instead of requests.post, like in the stand alone program.

Categories

Resources