I'm trying to get the voting API working, but I get the error .error.USER_REQUIRED. Can't figure out why, but I assume I must either be sending the modhash or the session cookie the wrong way, as the login goes trough fine
My code looks something like this:
UP = {'user': username, 'passwd': password, 'api_type': 'json',}
client = requests.session()
r = client.post('http://www.reddit.com/api/login', data=UP)
j = json.loads(r.text)
mymodhash = j['json']['data']['modhash']
url = 'http://www.reddit.com/api/vote/.json'
postdata = {'id': thing, 'dir': newdir, 'uh': mymodhash}
vote = client.post(url, data=json.dumps(newdata))
Error:
{"jquery": [[0, 1, "refresh", []], [0, 2, "attr", "find"], [2, 3, "call", [".error.USER_REQUIRED"]], [3, 4, "attr", "show"], [4, 5, "call", []], [5, 6, "attr", "text"], [6, 7, "call", ["please login to do that"]], [7, 8, "attr", "end"], [8, 9, "call", []]]}
To login you should post to ssl.reddit.com so that you are not posting your credentials in plain-text. Also, you should set a User-Agent.
The below is a working example to vote on your /r/redditdev submission.
import requests
# Login
client = requests.session(headers={'User-Agent': 'Requests test'})
data = {'user': 'USERNAME', 'passwd': 'PASSWORD', 'api_type': 'json'}
r = client.post('https://ssl.reddit.com/api/login', data=data)
modhash = r.json['json']['data']['modhash']
# Vote
data = {'id': 't3_11mr32', 'dir': '1', 'uh': modhash, 'api_type': 'json'}
r = client.post('http://www.reddit.com/api/vote', data=data)
print r.status_code # Should be 200
print r.json # Should be {}
Also, unless you are really interested in how reddit's API works under the covers, I suggest you use PRAW.
You can use session object with with statement.
import requests
UP = {'user': username, 'passwd': password, 'api_type': 'json'}
url_prefix = "http://www.reddit.com"
with requests.session() as client:
client.post(url_prefix + '/login', data=UP)
<...something else what you want...>
Related
I am using OdooRPC to send sign request in Odoo.
The process consist in 4 Parts:
Send the document to Sign to Odoo.
Send the fields to sign in the document, can be text field type or sign field.
Prepare the email template with the document and the signers (contacts from Odoo) to sign request.
Send the sign request email.
The code to prepare the request is:
request_fields = {
'template_id': template_id,
'signer_ids': [[0, 'virtual_25', {'role_id': 2, 'partner_id': employee_id1}],
[0, "virtual_37", {'role_id': 3, 'partner_id': employee_id2}]],
'signer_id': False,
'signers_count': 2,
'has_default_template': True,
'is_user_signer': False,
'follower_ids': [[6, False, []]],
'subject': 'Sign Request',
'filename': 'document_to_sign.pdf',
'message_cc': '<p><br></p>',
'attachment_ids': [[6, False, []]],
'message': '<p>Hi.</p><p>Sign this document, no reply</p>'
}
# Prepare email request
sign_email = self.odoo.env['sign.send.request']
email_id = sign_email.create(request_fields)
After create the email template, I can tell Odoo to send the sign request
# Prepare email request
sign_email = self.odoo.env['sign.send.request']
email_id = sign_email.create(request_fields) # int type
request_sign = sign_email.send_request(email_id)
The answer method doesn't show any error:
{'name': 'file_name.pdf', 'type': 'ir.actions.client', 'tag': 'sign.Document', 'context': {'id': 1234, 'token': 'abcd-1234-efgh-5678', 'sign_token': None, 'create_uid': 9, 'state': 'sent', 'request_item_states': {'1234': False, '1235': False}}}
The method 'send_request' create the email in Odoo, but it doesn't deliver the email to the recipents.
have you configured outgoing mail server in odoo which is in settings>technical>outgoing mail server if not please configure it, if yes then check in settings>technical>email if the email is sent from your side then a record will be created in it. please check it and update those information in the question in order to help you better.
I got the email message now.
removed the 'is_user_signer' key from the request_fields dictionary.
request_fields = {
'template_id': template_id,
'signer_ids': [[0, 'virtual_25', {'role_id': 2, 'partner_id': employee_id1}],
[0, "virtual_37", {'role_id': 3, 'partner_id': employee_id2}]],
'signer_id': False,
'signers_count': 2,
'has_default_template': True,
'follower_ids': [[6, False, []]],
'subject': 'Sign Request',
'filename': 'document_to_sign.pdf',
'message_cc': '<p><br></p>',
'attachment_ids': [[6, False, []]],
'message': '<p>Hi.</p><p>Sign this document, no reply</p>'
}
Now, it sends email messages with the sign request.
From this example, how do I get the IP address from the response?
import requests
URL = "https://security.cloudflare-dns.com/dns-query?name=test.com"
session = requests.session()
r = session.get(URL, headers={"Accept": "application/dns-json"})
r = r.json()
print("Type:", type(r))
print("Len:", len(r))
print("Content:", r)
IP = r['Answer'][-1]
print("IP:", IP)
Output:
Type: <class 'dict'>
Len: 8
Content: {'Status': 0, 'TC': False, 'RD': True, 'RA': True, 'AD': False, 'CD': False, 'Question': [{'name': 'test.com', 'type': 1}], 'Answer': [{'name': 'test.com', 'type': 1, 'TTL': 3261, 'data': '69.172.200.235'}]}
IP: {'name': 'test.com', 'type': 1, 'TTL': 3261, 'data': '69.172.200.235'}
Like this?:
IP = r['Answer'][-1]['data']
print("IP:", IP)
Output:
IP: 69.172.200.235
The reply is:
r['Answer'][0]['data']
But I would like to give you a tip on how you could find this.
I like to use the code module to run an interactive console inside my script:
import requests
import code
URL = "https://security.cloudflare-dns.com/dns-query?name=test.com"
session = requests.session()
r = session.get(URL, headers={"Accept": "application/dns-json"})
r = r.json()
print("Type:", type(r))
print("Len:", len(r))
print("Content:", r)
code.interact(banner="after get request", locals=locals()) #interactive console is created here
IP = r['Answer'][-1]
print("IP:", IP)
From there, you can play with local variables and test until you find what you need.
I hope that will helps.
I am working on a program that includes a strawpoll. As far as I can tell this code should work to create a poll however it is returning an error page instead of a poll. Here is the api
json = json.dumps({"title": "Question", "options": ["option1", "option2", "option3"]})
poll = requests.post("http://strawpoll.me/api/v2/polls", data = json, headers = {"Content-Type": "application/json"})
This is the url it returns
https://www.strawpoll.me/error?aspxerrorpath=/api/v2/polls
Unfortunately, strawpoll.me' api have been broken for quite some time now. You can still retrieve the polls but creating one redirects you to the error landing page.
Try posting your request to https://www.strawpoll.me/api/v2/polls:
data = {"title": "Question", "options": ["option1", "option2", "option3"]}
poll = requests.post("https://www.strawpoll.me/api/v2/polls", json=data,
headers={"Content-Type": "application/json"})
print(poll.url)
# https://www.strawpoll.me/api/v2/polls
print(poll.json())
# {'multi': False, 'title': 'Question', 'votes': [0, 0, 0], 'id': 16578754,
# 'captcha': False, 'dupcheck': 'normal', 'options': ['option1', 'option2', 'option3']}
Have a function to update a field in Netbox via API. The same data works on the Django web interface so I know it's not that, just something in my script that I'm doing wrong.
def change_allocated_server_status(api_token="", limit="",jira_access=""):
api_token_here = "Token " + api_token
headers = {'Authorization': api_token_here}
params = {'limit': limit}
sites = "https://my-url.com/api/dcim/devices/?role=server-planned"
session = requests.Session()
site_response = session.get(sites, headers=headers, params=params)
site_results = site_response.json()['results']
allocated_servers = get_devices_by_dc_loca(api_token, limit, jira_access)
url = "https://my-url.com/api/dcim/devices/239"
update = {
"device_role": 41
}
change = requests.patch(url, headers=headers, data=update)
change_results = change.json()
print change_results
The output of print change_results is
{u'status': 2, u'device_role': 40, u'name': u'device-name', u'site': 1, u'comments': u'', u'rack': 4, u'asset_tag': None, u'platform': None, u'primary_ip4': None, u'device_type': 7, u'primary_ip6': None, u'custom_fields': {}, u'position': 5, u'serial': u'', u'face': 0, u'id': 239, u'tenant': 1}
device_role isn't being changed. Doing a print change.status_code returns 200 so I know I'm hitting the API without a authentication problem, just guessing it's something simple I'm missing
Was missing a '/' from the end of my url, stopping the PATCH from being called but throwing no error.
I am trying to make a call to the SugarCRM v10 api to get the output of a report without having to log into the web interface and click the export button. I would like to get this report as data that can be written into csv format using python and the requests library.
I can authenticate successfully and get a token but whatever I try all I get as a response from reports is Error Method does not exist, by which they mean that you cannot use /csv at the end of the second url in this code block.
url = "https://mydomain.sugarondemand.com/rest/v10/oauth2/token"
payload = {"grant_type":"password","username":"ursername","password":"password","client_id":"sugar", "platform":"myspecialapp"}
r = requests.post(url, data=json.dumps(payload))
response = json.loads(r.text)
token = response[u'access_token']
print 'Success! OAuth token is ' + token
#What export methods are available? ###################################
#WRONG url = "https://mydomain.sugarondemand.com/rest/v10/Reports/report_id/csv"
#Following paquino's suggestion I used Base64
url = "https://mydomain.sugarondemand.com/rest/v10/Reports/report_id/Base64"
headers = { "Content-Type" : "application/json", "OAuth-Token": token }
r = requests.get(url, headers=headers);
response = r.text.decode('base64')
print response`
My question is this: what Export Methods are available via an api call to v10 of the SugarCRM api.
Edit: Using Base64 in the request url unfortunately returns ab object that I don't know how to parse...
%PDF-1.7
3 0 obj
<</Type /Page
/Parent 1 0 R
/MediaBox [0 0 792.00 612.00]
/Resources 2 0 R
/Contents 4 0 R>>
endobj
4 0 obj
<</Length 37217>>
stream
8.cܬR≈`ä║dàQöWºáW╙µ
The Reports Api accepts "Base64" and "Pdf"
Python Wrapper for SugarCRM REST API v10
https://github.com/Feverup/pysugarcrm
Quickstart
pip install pysugarcrm
from pysugarcrm import SugarCRM
api = SugarCRM('https://yourdomain.sugaropencloud.e', 'youruser', 'yourpassword')
# Return info about current user
api.me
# A more complex query requesting employees
api.get('/Employees', query_params={'max_num': 2, 'offset': 2, 'fields': 'user_name,email'})
{'next_offset': 4,
'records': [{'_acl': {'fields': {}},
'_module': 'Employees',
'date_modified': '2015-09-09T13:40:32+02:00',
'email': [{'email_address': 'John.doe#domain.com',
'invalid_email': False,
'opt_out': False,
'primary_address': True,
'reply_to_address': False}],
'id': '12364218-7d79-80e0-4f6d-35ed99a8419d',
'user_name': 'john.doe'},
{'_acl': {'fields': {}},
'_module': 'Employees',
'date_modified': '2015-09-09T13:39:54+02:00',
'email': [{'email_address': 'alice#domain.com',
'invalid_email': False,
'opt_out': False,
'primary_address': True,
'reply_to_address': False}],
'id': 'a0e117c0-9e46-aebf-f71a-55ed9a2b4731',
'user_name': 'alice'}]}
# Generate a Lead
api.post('/Leads', json={'first_name': 'John', 'last_name': 'Smith', 'business_name_c': 'Test John', 'contact_email_c': 'john#smith.com'})
from pysugarcrm import sugar_api
with sugar_api('http://testserver.com/', "admin", "12345") as api:
data = api.get('/Employees', query_params={'max_num': 2, 'offset': 2, 'fields': 'user_name,email'})
api.post('/Leads', json={'first_name': 'John', 'last_name': 'Smith', 'business_name_c': 'Test John', 'contact_email_c': 'john#smith.com'})
# Once we exit the context manager the sugar connection is closed and the user is logged out