I’m trying to connect to the OPS API but get an error when trying to connect to the url. I get the access_token just fine as detailed in the documentation (page 34), but when I try to connect to the url I’m interested in, I get a ‘Name or Service not found’ error.
The documentation states (page 35) that the client should access the OPS resource over an encrypted HTTPS connection, which I think might be the missing step in my code creating this error (or not).
Below is the code I use (replacing #### with my access_token):
from http.client import HTTPSConnection
c = HTTPSConnection('ops.epo.org/3.2/rest-services/published-data/search?q=Automation', port=443)
headers2 = {'Authorization': ‘Bearer ########kv5’}
c.request('GET', '/', headers=headers2)
res = c.getresponse()
data = res.read()
Many thanks.
Not sure why this issue was happening earlier, but it seems to be fine now when I run the following code:
headers = {'Authorization': 'Bearer %s' % token }
query = requests.get('http://ops.epo.org/3.2/rest-services/published-data/search?q=Automation', headers=headers)
query.content
I get a status response code of 200, and I can parse the content just fine.
Related
I have a Django App, and I am trying to use Auth0 for my Django App's authentication. I have successfully integrated Login and Logout using social-auth-app-django library. But I am facing a lot of hurdles in implementing Auth0's Management API to use direct password change feature in Django? I tried to follow what this Auth0's official documentation's link says to implement Auth0's Management API for direct password change feature, but it is throwing Error Code 500, and I am not understanding what I did wrong.
The link shows the following example to implement Auth0 Management API for firect password change feature in Django:
import http.client
conn = http.client.HTTPSConnection("")
payload = "{\"password\": \"NEW_PASSWORD\",\"connection\": \"CONNECTION_NAME\"}"
headers = { 'content-type': "application/json" }
conn.request("PATCH", "/dev-9fj5kydc.us.auth0.com/api/v2/users/USER_ID", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
And my implementation for the same is:
import http.client
user = self.request.user
NEW_PASSWORD = form.cleaned_data["new_password1"]
CONNECTION_NAME = settings.AUTH0_CONNECTION_NAME
DOMAIN = settings.SOCIAL_AUTH_AUTH0_DOMAIN
USER_ID = user.auth0_id
URL = f"/{DOMAIN}/api/v2/users/{USER_ID}"
conn = http.client.HTTPSConnection("")
payload = f"{{\"password\": \"{NEW_PASSWORD}\",\"connection\": \"{CONNECTION_NAME}\"}}" # Here I am using 'Username-Password-Authentication' as Connection Name
headers = { 'content-type': "application/json" }
conn.request("PATCH", URL, payload, headers)
res = conn.getresponse()
data = res.read()
I have double checked that everything is fine by printing values in console and all variables hold correct values. Can someone help me and tell what wrong I am doing?
I'm trying to use the Hasura API to get the contents of my database. The appropriate endpoint is v1alpha1/pg_dump.
I've tried doing the following in Python:
import requests
api_url = 'http://localhost:9695/v1alpha1/pg_dump'
header = {'Content-Type': 'application/json',
'x-hasura-admin-secret': 'MY_SECRET',
'X-Hasura-Role': 'admin'}
r = requests.post(url=api_url, headers=header)
If I do requests.get, I get information back (html code, although nothing particularly useful). However, if I do requests.post (which is required by Hasura: https://hasura.io/docs/1.0/graphql/core/api-reference/pgdump.html), I get a 404 error. I don't understand why. It's not an authentication error, but a page not found error.
Have I built my url incorrectly? Is there something I'm missing? The port is correct (and if I change it in the code, it gives me a different error telling me the port is invalid/closed). I'm not sure what else to change.
So, I have tried in my own Digital Ocean 1 click deployment environment. I have not secured it so I am not providing any headers. It works fine as follows:
import requests
import json
r = requests.post('http://address_of_hasura/v1alpha1/pg_dump',
data = json.dumps({
'opts' : ['-O', '-x', '--schema-only', '--schema', 'public'],
'clean_output': True
}) )
print r.text
If you have used the HASURA_GRAPHQL_ENABLED_APIS env variable and not included pgdump, that could be a reason it would be disabled.
I'm using python to execute a splunk search query and return the results. I connect with the following string:
service = client.connect(
host=HOST,
port=PORT,
username=USERNAME,
password=PASSWORD
)
The variables have been tested to work, and it connects to splunk, but sometimes, when I run these lines of code:
print "Installed App Names \n"
for app in service.apps:
print app.name
It returns this error:
Request Failed: Session is not logged in
About 50% of the time, the code works, and it executes. Is this inconsistency in code results do to the service = lines of code not actually connecting to the splunk server? Can these connections time out?
connect can take an autologin=True argument to allow the bindings to try to re-connect when authentication fails, instead of raising that error immediately.
Probably you should get the token and session id of splunk using your python code. Please find the below code if this could help you.
import json,os,sys,requests
BASE_URL = "https://SPLUNKLB / SPLUNK WEB URL"
def getToken():
# body for token request
payload = {'username': "",'password': ""}
TOKEN_URL = "/services/auth/login?output_mode=json"
# post token request
res = requests.post(BASE_URL+TOKEN_URL, data=payload, verify=False)
if (res.status_code == 200):
# Get token out of response
resJson = json.loads(res.content)
return resJson.get('sessionKey')
else:
print res.status_code, res.content
I have the below code that I trying to send messages to a Windows Phone using the Pushalot Api as Pushalot haven't got any examples.
I know my api key works fine as the cURL method works fine, but my modified python script isn't working, keep getting -- 400, Bad Request and I'm not sure why.
Any ideas?
#!/usr/bin/python
from urllib import urlencode
from httplib import HTTPSConnection, HTTPException
from ssl import SSLError
pushalot_authorizationtoken = 'xxxxxxxxxxxxxxx'
pushalot_title = 'title'
pushalot_body = 'body'
http_handler = HTTPSConnection("pushalot.com")
data = {'AuthorizationToken': pushalot_authorizationtoken,
'Title': pushalot_title.encode('utf-8'),
'Body': pushalot_body.encode('utf-8') }
try:
http_handler.request("POST",
"/api/sendmessage",
headers = {'Content-type': "application/x-www-form-urlencoded"},
body = urlencode(data))
except (SSLError, HTTPException):
print("Pushalot notification failed.")
response = http_handler.getresponse()
print(response.status, response.reason)
Working today, weird, above code works.
Will leave this here for anyone else that needs the python code for pushalot api
I have some python tools that I would like to have send updates to a hipchat room. I do this elsewhere with shell scripts, so I know it works in our environment, but I can't seem to get the token pushed to the hipchat API. Gotta be something simple.
First, this authenticates properly and delivers a message:
curl -d "room_id=xxx&from=DummyFrom&message=ThisIsATest&color=green" https://api.hipchat.com/v1/rooms/message?auth_token=yyy
But when I try to use the python "requests" module, I am getting stuck.
import requests
room_id_real="xxx"
auth_token_real="yyy"
payload={"room_id":room_id_real,"from":"DummyFrom","message":"ThisIsATest","color":"green"}
headerdata={"auth_token":auth_token_real,"format":"json"}
r=requests.post("https://api.hipchat.com/v1/rooms/message", params=payload, headers=headerdata)
print r.ok, r.status_code, r.text
Here is my error information:
False 401 {"error":{"code":401,"type":"Unauthorized","message":"Auth token not found. Please see: https:\/\/www.hipchat.com\/docs\/api\/auth"}}
Basically I don't seem to be passing the authentication token in properly. How can I get this working?
In case it helps, here's a working V2 API example. I did find the V2 API to be a bit more sensitive about getting the form of the request exactly right. But, it might be more forward-looking to conform to the V2 API (though the original question seemed to pertain to V1).
#!/usr/bin/env python
import json
from urllib2 import Request, urlopen
V2TOKEN = '--V2 API token goes here--'
ROOMID = --room-id-nr-goes-here--
# API V2, send message to room:
url = 'https://api.hipchat.com/v2/room/%d/notification' % ROOMID
message = "It's a<br><em>trap!</em>"
headers = {
"content-type": "application/json",
"authorization": "Bearer %s" % V2TOKEN}
datastr = json.dumps({
'message': message,
'color': 'yellow',
'message_format': 'html',
'notify': False})
request = Request(url, headers=headers, data=datastr)
uo = urlopen(request)
rawresponse = ''.join(uo)
uo.close()
assert uo.code == 204
Another basic example using requests:
import requests, json
amessage = 'Hello World!'
room = 'https://api.hipchat.com/v2/room/18REPLACE35/notification'
headers = {'Authorization':'Bearer UGetYourOwnAuthKey', 'Content-type':'application/json'}
requests.post(url = room, data = json.dumps({'message':amessage}), headers = headers)
As Ianzz said, try including it in the URL query string. Although clunky (you probably want to hash it!), it definitely works.
The other strange quirk is the tokens that you get through Hipchat; I had no end of problems earlier this evening using my own personal token; it seemed to correspond to v2 beta of the API. If you go in through Group Admin and get a token from there, it may help.
Old question is old.
Here's an official list of libs which use the HipChat API v2 interface
https://www.hipchat.com/docs/apiv2/libraries