Http post successes with poster, but fails in python - python

In the code below, I'm trying to create a repository with http post, but I always get 400 bad request, when I send the http post with poster, I got 201 created, what's wrong with this code?
token = raw_input('Access Token: ')
url = 'https://api.github.com/user/repos?access_token=' + token
values = {"name":"newnewnewnew"}
data = urllib.urlencode(values)
req = urllib2.Request(url,data)
response = urllib2.urlopen(req)
the_page = response.read();
print the_page
Poster:

According to the GitHub API v3 documentation, for POST request, the parameters should be encoded with json and the content-type should be application/json:
import json
....
token = raw_input('Access Token: ')
url = 'https://api.github.com/user/repos?access_token=' + token
values = {"name": "newnewnewnew"}
data = json.dumps(values) # <---
req = urllib2.Request(url, data, headers={'Content-Type': 'application/json'}) # <---
response = urllib2.urlopen(req)
the_page = response.read()
print the_page

Related

I want to send email to user from API response in Django?

[data image][1]I want to send email to user after this function calling so in first function i m creating customer on razor pay and after fetching customer id i m passing to other function and on.
so in this function get_virtual_account() i am getting all the response from API provided by razor-pay and i need to send that response to user who created the account so how can i do that i am not able to send this response in email.
def create_razor_customer(data):
logger.info("Inside create_razor_customer")
headers = {'Content-Type': 'application/json',}
data=json.dumps(data)
response = requests.post(settings.API_RAZORPAY+'/customers', headers=headers, data=data, auth=(settings.API_RAZORPAY_KEY, settings.API_RAZORPAY_SECRET))
logger.info(json.loads(response.content))
json_response = response.json()
customer_id = json_response['id']
logger.info(customer_id)
get_razor_customer(customer_id)
return response
def get_razor_customer(customer_id):
logger.info("Inside get_razor_customer")
headers = {'Content-Type': 'application/json',}
response = requests.get(settings.API_RAZORPAY+'/customers/'+customer_id, headers=headers, auth=(settings.API_RAZORPAY_KEY, settings.API_RAZORPAY_SECRET))
logger.info(json.loads(response.content))
create_razor_virtual_account(customer_id)
return response
def create_razor_virtual_account(customer_id):
logger.info("Inside create_razor_virtual_account")
headers = {'Content-Type': 'application/json',}
data = {"receivers": {"types": ["bank_account"]},"description": "razorpay","customer_id": customer_id,"close_by": 1761615838,"notes": {"reference_key": "reference_value"}}
data=json.dumps(data)
response = requests.post(settings.API_RAZORPAY+'/virtual_accounts', headers=headers, data=data, auth=(settings.API_RAZORPAY_KEY, settings.API_RAZORPAY_SECRET))
json_response = response.json()
virtual_id = json_response['id']
logger.info(virtual_id)
logger.info(json_response)
return response
def get_virtual_account(virtual_id):
logger.info("Inside get_virtual_account")
logger.info(virtual_id)
headers = {'Content-Type': 'application/json',}
response = requests.get(settings.API_RAZORPAY+'/virtual_accounts/'+virtual_id,headers=headers, auth=(settings.API_RAZORPAY_KEY, settings.API_RAZORPAY_SECRET))
json_response = response.json()
logger.info(json_response)
send_account_details()
return response
def send_account_details():
logger.info('Inside send_account_details')
send_mail('Account Details', 'Details for Razorpay account', settings.EMAIL_HOST_USER, ['abhishek#byond.travel',])
logger.info("sent")
return "sent"
[1]: https://i.stack.imgur.com/proIH.png
Suppose your response JSON is
res_data={"duration":1201,"number":6,"result":"FAILURE","url":"http://localhost:8080/job/git_checkout/6/"}
Then you need to pass this into send_account_details function.
def send_account_details(res_data):
import json
logger.info('Inside send_account_details')
body = "JSON Response is : " + json.dumps(res_data) + "\n\n" + "Details for Razorpay account"
send_mail('Account Details', body, settings.EMAIL_HOST_USER, ['abhishek#byond.travel',])
logger.info("sent")
return "sent"
Using json.dumps(res_data) you can add your JSON to body of email.

How do I perform oauth2 for Sabre Dev Network using python?

I am trying to get an authentication token from the Sabre Dev Studio. I am following the generic directions given here https://developer.sabre.com/docs/read/rest_basics/authentication(need to login to view) but I cannot figure out how to obtain a token using Python - specifically using the python-oauth2 library as it seems to be recommended to simplify the process.
Here's a sample of my code:
config = ConfigParser.ConfigParser()
config.read("conf.ini")
clientID = config.get('DEV', 'Key').strip()
clientSecret = config.get('DEV', 'SharedSecret').strip()
consumer = oauth.Consumer(key=base64.b64encode(clientID),
secret=base64.b64encode(clientSecret))
# Request token URL for Sabre.
request_token_url = "https://api.sabre.com/v1/auth/token"
# Create our client.
client = oauth.Client(consumer)
# create headers as per Sabre Dev Guidelines https://developer.sabre.com/docs/read/rest_basics/authentication
headers = {'Content-Type':'application/x-www-form-urlencoded'}
params = {'grant_type':'client_credentials'}
# The OAuth Client request works just like httplib2 for the most part.
resp, content = client.request(request_token_url, "POST", headers=headers)
print resp
print content
The response is a type 401. Where the credentials are incomplete or misformed.
Any suggestions appreciated.
I could not with oauth2, but I did with requests package I think you can get it from here
My code is:
import requests
import base64
import json
def encodeBase64(stringToEncode):
retorno = ""
retorno = base64.b64encode(stringToEncode)
return retorno
parameters = {"user": "YOUR_USER", "group": "YOUR_GROUP", "domain": "YOUR_DOMAIN", "password": "YOUR_PASSWORD"}
endpoint = "https://api.test.sabre.com/v1"
urlByService = "/auth/token?="
url = endpoint + urlByService
user = parameters["user"]
group = parameters["group"]
domain = parameters["domain"]
password = parameters["password"]
encodedUserInfo = encodeBase64("V1:" + user + ":" + group + ":" + domain)
encodedPassword = encodeBase64(password)
encodedSecurityInfo = encodeBase64(encodedUserInfo + ":" + encodedPassword)
data = {'grant_type':'client_credentials'}
headers = {'content-type': 'application/x-www-form-urlencoded ','Authorization': 'Basic ' + encodedSecurityInfo}
response = requests.post(url, headers=headers,data=data)
print "Post Request to: " + url
print response
print "Response Message: " + response.text
Regards,
First get your credentials:
Register in https://developer.sabre.com/member/register
Sign in into https://developer.sabre.com
Go to https://developer.sabre.com/apps/mykeys and get your credentials. They should look like this (where spam and eggs will look like garbage):
client_id = 'V1:spam:DEVCENTER:EXT'
client_secret = 'eggs'
Then call the /v2/auth/token endpoint in order to get an access token:
import requests
credentials = ":".join([part.encode('base64').strip()
for part in (client_id, client_secret)]
).encode('base64').strip()
url = 'https://api.test.sabre.com/v2/auth/token'
headers = {'Authorization': 'Basic ' + credentials}
params = {'grant_type': 'client_credentials'}
r = requests.post(url, headers=headers, data=params)
assert r.status_code is 200, 'Oops...'
token = r.json()
print(token)
You should get something like this:
{u'access_token': u'T1RLAQJwPBoAuz...x8zEJg**',
u'token_type': u'bearer',
u'expires_in': 604800}
Now you can call others endpoints using an Authorization header containing your access token. For example, if you want the list of supported countries:
headers = {'Authorization': 'Bearer ' + token[u'access_token']}
endpoint = 'https://api.test.sabre.com/v1/lists/supported/countries'
r = requests.get(endpoint, headers=headers)
assert r.status_code is 200, 'Oops...'
print (r.json())
If everything went well, you should receive the list of supported countries:
{u'DestinationCountries': [
{u'CountryName': u'Antigua And Barbuda', u'CountryCode': u'AG'},
{u'CountryName': u'Argentina', u'CountryCode': u'AR'},
{u'CountryName': u'Armenia', u'CountryCode': u'AM'},
{u'CountryName': u'Aruba', u'CountryCode': u'AW'},
...
}
I'm pretty sure you're using this oauth library: https://pypi.python.org/pypi/oauth2 Despite being named "oauth2" it does not implement the OAuth 2 specification. Here is the best library I could find that provides OAuth 2 support and has documentation: http://requests-oauthlib.readthedocs.org/en/latest/oauth2_workflow.html

oauth1, rsa-sha1, header params

I have been using requests-oauthlib, which do have rsa-sha1 signature algorithm, but there can't seem to be a way to add extra params to the authorization header, and if i do modify the header manually before making the request i get
"The request contains an incomplete or invalid oauth_signature."
because it had already created the oauth_signature when i have added the new oauth_body_hash to the authorization header.
i have pasted the code, the first call using oauth passes correctly, but the second one is giving the error.
any possible way to workaround this ? another library that has both options to add extra params and provide rsa-sha1 signature ?
oauth = OAuth1(
consumer_key,
signature_method='RSA-SHA1',
signature_type='auth_header',
rsa_key=key,
callback_uri=callback_uri
)
oauth.client.realm = 'eWallet'
r = requests.post(url=request_token_url, auth=oauth)
credentials = parse_qs(r.content)
# end of request
# post shopingcart
root = ET.fromstring(shopping_cart_xml)
root.find('OAuthToken').text = credentials['oauth_token'][0]
xml = ET.tostring(root, encoding="us-ascii", method="xml")
sha1 = hashlib.sha1()
sha1.update(xml)
oauth_body_hash = sha1.digest()
oauth_body_hash = base64.b64encode(oauth_body_hash)
oauth.client.oauth_body_hash = oauth_body_hash
req = Request('POST', shopping_cart_url, data=xml, auth=oauth)
prepped = req.prepare()
auth_header = prepped.headers['Authorization'] + ', oauth_body_hash="%s"' % (oauth_body_hash)
headers = {'Content-Type': 'application/xml', 'Authorization': auth_header}
r = requests.post(url=shopping_cart_url, headers=headers, data=xml)

Making curl-like request with Python requests?

I need to make a python request, like this:
curl --header "Authorization: XXXXXXXXXXXXX"
https://api.getnomi.com/v2/reports/conversion?account=XXXXXXXXXXXXXX
\&store=XXXXXXXXXX\&date_from=1329238082\&date_to=1360860473
I tried this:
import requests as r
auth_code = "XXXXXXXXXXX"
account_id = "XXXXXXXXXXX"
store_id = "XXXXXXXXXXXXXX"
test_url = "https://api.getnomi.com/v2/reports/conversion?"
header = {"Authorization": auth_code}
payload = {"account": account_id, "store": store_id,
"date_from": 1398272878, "date_to": 1398359278}
data = r.get(test_url, params=payload, headers=header)
and I keep getting this response <Response [404]>
Any idea why?

Problems with authorization

I have problems with authorization in python. I want automatic enter to website, but i can't. I used many libraries: Grab, urlib2, request, but i never entered(
For check myself i enter pege with account data
It's real site, login and password
URL="http://pin-im.com/accounts/login/"
LOGIN="testuser"
PASSWORD="test12345user"
urlib2:
def authorization():
import urllib2
gh_url = 'http://pin-im.com/accounts/login/'
gh_user= 'testuser'
gh_pass = 'test12345user'
req = urllib2.Request(gh_url)
password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None, gh_url, gh_user, gh_pass)
auth_manager = urllib2.HTTPBasicAuthHandler(password_manager)
opener = urllib2.build_opener(auth_manager)
urllib2.install_opener(opener)
handler = urllib2.urlopen(req)
Grab:
def autorization():
g = Grab()
g.setup(post={'username':'testuser', 'Password':'test12345user', 'act': 'submit'})
g.go("http://pin-im.com/accounts/login/")
g.go("http://pin-im.com/user/my-profile/")
print g.response.code
Request(i used all methods in Request Lib for authorization, one of them):
from requests.auth import HTTPBasicAuth
requests.get('http://pin-im.com/accounts/login/', auth=HTTPBasicAuth('testuser', 'test12345user'))
r. get("http://pin-im.com/user/my-profile/")
r.status_code
I'm despair, can you help me login to this site? and what i did wrong?
userData = "Basic " + ("testuser:test12345user").encode("base64").rstrip()
req = urllib2.Request('http://pin-im.com/accounts/login')
req.add_header('Accept', 'application/json')
req.add_header("Content-type", "application/x-www-form-urlencoded")
req.add_header('Authorization', userData)
res = urllib2.urlopen(req)
This site uses CSRF protection, so you should get csrftoken cookie and send it back to server with your request:
import Cookie
from urllib import urlencode
import httplib2
URL="http://pin-im.com/accounts/login/"
LOGIN="testuser"
PASSWORD="test12345user"
http = httplib2.Http()
response, _ = http.request(URL)
cookies = Cookie.BaseCookie()
cookies.load(response["set-cookie"])
csrftoken = cookies["csrftoken"].value
headers = {'Content-type': 'application/x-www-form-urlencoded'}
headers['Cookie'] = response['set-cookie']
data = {
"csrfmiddlewaretoken": csrftoken,
"username":LOGIN,
"password": PASSWORD
}
response, _ = http.request(URL, "POST", headers=headers, body=urlencode(data))
response, content = http.request(
"http://pin-im.com/user/my-profile/",
"GET",
headers={'Cookie': response['set-cookie']}
)
print response, content

Categories

Resources