Windows PowerShell & InfluxDB: Unable to Write Data to Bucket - python

I am new to InfluxDB. Understand we need to use Windows Powershell to interact with InfluxDB.
Using Python in the shell, I tried to write data to the bucket using the below code
import influxdb_client, os, time
from influxdb_client import InfluxDBClient, Point, WritePrecision
from influxdb_client.client.write_api import SYNCHRONOUS
token = os.environ.get("INFLUXDB_TOKEN")
org = "nil"
url = "https://us-west-2-1.aws.cloud2.influxdata.com/"
client = influxdb_client.InfluxDBClient(url=url, token=token, org=org)
bucket="MyBucket"
write_api = client.write_api(write_options=SYNCHRONOUS)
for value in range(5):
point = (
Point("measurement1")
.tag("tagname1", "tagvalue1")
.field("field1", value)
)
write_api.write(bucket=bucket, org="nil", record=point)
time.sleep(1) # separate points by 1 second
But I get the error
influxdb_client.rest.ApiException: (401)
Reason: Unauthorized
HTTP response headers: HTTPHeaderDict({'Date': 'Thu, 29 Dec 2022 01:44:17 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': '55', 'Connection': 'keep-alive', 'trace-id': '5374d7ae5df282f4', 'trace-sampled': 'false', 'x-platform-error-code': 'unauthorized', 'Strict-Transport-Security': 'max-age=15724800; includeSubDomains', 'X-Influxdb-Request-ID': '2e52a39e6d7442b5fc7eb7306ef004d4', 'X-Influxdb-Build': 'Cloud'})
HTTP response body: {"code":"unauthorized","message":"unauthorized access"}

401 indicates that there should something wrong with the authorization header. Could you try to enable to debug log as follows to see the details:
client = influxdb_client.InfluxDBClient(url=url, token=token, org=org, debug=True) // see that **debug=True** will enable verbose logging of HTTP requests
Both HTTP request headers and body will be logged to standard output. And please check the HTTP header to see whether there is "Authorization: Token" header, which is similar to
Authorization: 7mexfXXXXXXXXXXXXX
Please double check if the header is missing or malformed.

Related

Tornado Google+ Oauth Error Code 400

I have problem in Google+ OAuth using tornado framework. I used AngularJS as front end and python tornado as backend with nginx server. I send HTTP request to Google+ API from AngularJS and my tornado API is redirects to Google login. After successfully login it redirects back to my app. At the time of redirect I think it refresh automatically, i.e there two redirect calls from Google.
See there are two HTTP redirect call from tornado OAuth2
This is my code:
class GoogleOAuth2LoginHandler(tornado.web.RequestHandler, tornado.auth.GoogleOAuth2Mixin):
#tornado.gen.coroutine
def get(self):
if self.get_argument('code', False):
user = yield self.get_authenticated_user(
redirect_uri='http://your.site.com/auth/google',
code=self.get_argument('code')
)
# Save the user with e.g. set_secure_cookie
else:
yield self.authorize_redirect(
redirect_uri='http://your.site.com/auth/google',
client_id=self.settings['google_oauth']['key'],
scope=['profile', 'email'],
response_type='code',
extra_params={'approval_prompt': 'auto'}
Error:
Google auth error: HTTPResponse(_body=None,buffer=<_io.BytesIO object at 0xb37809bc>,code=400,effective_url='https://accounts.google.com/o/oauth2/token',error=HTTPError('HTTP 400: Bad Request',),headers={'X-Consumed-Content-Encoding': 'gzip', 'Alternate-Protocol': '443:quic,p=1', 'X-Xss-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'Transfer-Encoding': 'chunked', 'Set-Cookie': 'NID=76=iaY_jJFPzvLg3_h3eqUFMt4fecbELKk9_bGJju-mwsHBNlxeDqSrtmpyazsrJ3mDgtDnTnzsw5_fjIfV8GcUAegoNgxGi5ynpcfg0vEWULSeVXKio_ANxEoK9C-F5oRs;Domain=.google.com;Path=/;Expires=Sat, 13-Aug-2016 10:17:46 GMT;HttpOnly', 'Expires': 'Fri, 12 Feb 2016 10:17:46 GMT', 'Server': 'GSE', 'Connection': 'close', 'Cache-Control': 'private, max-age=0', 'Date': 'Fri, 12 Feb 2016 10:17:46 GMT', 'P3p': 'CP="This is not a P3P policy! See https://support.google.com/accounts/answer/151657?hl=en for more info."', 'Alt-Svc': 'quic=":443"; ma=604800; v="30,29,28,27,26,25"', 'Content-Type': 'application/json; charset=utf-8', 'X-Frame-Options': 'SAMEORIGIN'},reason='Bad Request',request=,request_time=0.4158029556274414,time_info={})
We had the same problem with exactly same config (Tornado+nginx+angularjs). I just rewrote OAuth authentication part without tornado and problem resolved. You can use tornado's AsyncHttpClient but I used aiohttp since I have hosted tornado inside asyncio.
Following is the new code and commented parts are the old code.
from backend.helpers.async_oauth2.client import Client
oauth_client = Client(app_settings.security.google.client_id, app_settings.security.google.client_secret,
app_settings.security.google.redirect_uri, "https://accounts.google.com/o/oauth2/auth"
, "https://accounts.google.com/o/oauth2/token")
access = await oauth_client.get_token(code, grant_type="authorization_code")
# access = await self.get_authenticated_user(
# redirect_uri=app_settings.security.google.redirect_uri,
# code=code)
# user = await self.oauth2_request(
# "https://www.googleapis.com/oauth2/v1/userinfo",
# access_token=str(access["access_token"]))
user = await oauth_client.http_get(
"https://www.googleapis.com/oauth2/v1/userinfo?{}".format(
url_parse.urlencode({'access_token':str(access["access_token"])})))

How to change request headers

How do I set request headers? I am downloading image from instagram and I want to change its filename, get the file size. These many request headers are there wiki
This is what I have done until now
import requests
#app.route('/try')
def trial():
img = 'https://igcdn-photos-e-a.akamaihd.net//hphotos-ak-xaf1//t51.2885-15//e35//12093691_1082288621781484_1524190206_n.jpg'
imgData = requests.get(img)
return imgData # this gives me error: Response object is not callable
Edit : I want to set the content-disposition header . Another question : when I set the headers, then how would I give the image to the client side?
I read on Internet that to send the file to client side I should set the request header. But how do I send the file is my another question? Sorry for asking another question in the same
The query which you asked has nothing to do with Flask. Flask is a web framework. Requests is a HTTP library which will help solve your issue
You just need to create a dict with your headers (key: value pairs where the key is the name of the header and the value is, well, the value of the pair) and pass that dict to the headers parameter on the .get or .post method.
headers = {'Content-Type': 'text/plain'}
r = requests.get('http://example.com', headers=headers)
If you wish to check the header values set when the request was sent then you can simple do this:
print r.headers
print r.headers['Content-Type'] # Output - 'text/html'
resp = requests.get('https://igcdn-photos-e-a.akamaihd.net/hphotos-ak-xaf1/t51.2885-15/e35/12093691_1082288621781484_1524190206_n.jpg')
resp.headers
And you will get the response like this ..
{'content-length': '73921', 'last-modified': 'Fri, 30 Oct 2015 15:18:29 GMT', 'connection': 'keep-alive', 'cache-control': 'max-age=1209600', 'date': 'Wed, 18 Nov 2015 08:44:15 GMT', 'access-control-allow-origin': '*', 'content-type': 'image/jpeg', 'timing-allow-origin': '*'}
You can get headers... check out the content-length. And you will not gonna get the file name I believe because content-disposition will not be there. So try something else to get the file name.

HTTP request with requests in python returning text instead of json

def thready(name,count):
payload={'Accept': 'application/json;charset=utf-8', 'X-Mashape-Key': 'key'
}
link = "https://montanaflynn-gender-guesser.p.mashape.com/?name=" + name
r=requests.get(link ,headers=payload)
print r.headers
data=r.json()
print data
count=0
thready("bob",count)
So I just tried to do a simple HTTP request in python. In the r.header i get
{'date': 'Wed, 22 Jul 2015 06:30:12 GMT', 'content-length': '178', 'content-type
': 'text/html', 'connection': 'keep-alive', 'server': 'Mashape/5.0.6'}
In the header I said it should return json. The return is text though? Very confused about this fact? Some insight would be very helpful because I'm trying to do the simple
There is nothing wrong with the code.
I have inspected your API request upstream by going to the source: the API provider's page and it looks like the API is defunct/not working as expected.
Which is exactly why you're getting errors.
Solution:
1) Contact the provider to try to resolve the problem, its on them not on you to fix it
2) Find an alternative API from the same portal: https://www.mashape.com/explore?query=gender
Good luck

Linkedin Api for python not working correctly

Linkedin Documents are confusing like crazy. I just want to get some basic information. I need to get a company's recent updates, comments for the update, and how many likes the update got. I tried to follow the documentation and this is my code:
from linkedin import linkedin
import oauth2 as oauth
import httplib2
api_key = '9puxXXXXXXX'
secret_key = 'brtXoXEkXXXXXXXXX'
auth_token = '75e15760-XXXXXXXXXXXXXXXXXXXXXX'
auth_secret = '10d8caXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
RETURN_URL = 'http://localhost:8000'
cos = oauth.Consumer(api_key,secret_key)
access_token = oauth.Token(key=auth_token, secret=auth_secret)
client = oauth.Client(cos,access_token)
resp,content = client.request("http://api.linkedin.com/v1/companies/1219692/updates?start=0&count=10", "GET", "")
This code is supposed to get the 10 recent updates for apple, but this is what I get when I
print resp
print content
{'status': '200', 'content-length': '78', 'content-location': u'http://api.linkedin.com/v1/companies/216984/updates?count=10&oauth_body_hash=2jmj7l5rSw0yVb%2FvlWAYkK%2FYBwk%3D&oauth_nonce=87365476&oauth_timestamp=1372347259&oauth_consumer_key=9puxXXXXXXX&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&start=0&oauth_token=75e1576XXXXXXX&oauth_signature=EhcMiQXXXXXXX%3D', 'transfer-encoding': 'chunked', 'vary': '*', 'server': 'Apache-Coyote/1.1', 'connection': 'close', '-content-encoding': 'gzip', 'date': 'Thu, 27 Jun 2013 15:34:18 GMT', 'x-li-request-id': '84BXIU5ZQK', 'x-li-format': 'xml', 'content-type': 'text/xml;charset=UTF-8'}
what am I doing wrong?
Your code does not make sense, you imported linkedin module, which seems to be this module, but I can't see you are using that API wrapper in your code. If I'm wrong you can still use the wrapper above and easily handle data back from LinkedIn. Just take a look at this example:
Querying updates
sample:
from linkedin import server
application = server.quick_api(KEY, SECRET)
application.get_company_updates(1035, params={'count': 2})
where 1035 is the ID of the company you are trying to get updates from.

LinkedIn out of network API calls returning "unauthorized" error

I'm trying to access out-of-network profiles using the LinkedIn API, following the instructions from here.
I'm writing my code in Python.
As I understand it, I just add an extra header to my HTTPSConnection request:
normal call:
connection.request(method, relative_url, body = body, headers={'Authorization': OAuth_header})
out-of-network call:
// these values were extracted from the http-header I received
name = x-li-auth-token
value = name:R8Y4
connection.request(method, relative_url, body = body, headers={'Authorization': OAuth_header, name: value})
When I do the out-of-network call, I get an error:
error:
status: 401
timestamp: 1330027911625
request-id: VHUSL0J7TL
error-code: 0
message: [unauthorized]. OAU:k1tofeoqr4id|2dc38f4e-73d1-4d31-9330-dd82aca89616|*01|*01:1330027911:CRc7YYYQRe2VS6woJpGX+qYVa/Q=
I've been testing this on both my own profile and an actual out-of-network profile, no change in error.
From various API requests, the "value" changes slightly, and I have tried all variants:
"name:R8Y4"
"search-name:R8Y4"
"OUT_OF_NETWORK:R8Y4"
I'm guessing it has to do with the HTTP headers, but I have no idea what is wrong.
Please help! Thank you.
I'm not sure why your call is failing. Here's the sequence using the tested oauth2 library in python, including the entire HTTP conversation.
First, do the search:
http://api.linkedin.com/v1/people-search:(people:(distance,id,first-name,last-name,headline,api-standard-profile-request))
Parameters (I'm using OAuth in the parameters for this call)
oauth_body_hash=2jmj7l5rSw0yVb%2FvlWAYkK%2FYBwk%3D
oauth_nonce=41358038
oauth_timestamp=1330098205
oauth_consumer_key=xxx
oauth_signature_method=HMAC-SHA1
facet=network%2CO
oauth_version=1.0
oauth_token=xxx
keywords=Schneider+Electric
oauth_signature=xxx
Response includes:
<person>
<distance>-1</distance>
<id>UBAQYFeiHo</id>
<first-name></first-name>
<last-name>Private</last-name>
<headline>Assistant Engineer at Schneider Electric</headline>
<api-standard-profile-request>
<url>http://api.linkedin.com/v1/people/UBAQYFeiHo</url>
<headers total="1">
<http-header>
<name>x-li-auth-token</name>
<value>OUT_OF_NETWORK:wHti</value>
</http-header>
</headers>
</api-standard-profile-request>
</person>
Second call, to get the profile:
http://api.linkedin.com/v1/people/UBAQYFeiHo:(id,first-name,last-name)
Request headers:
Host: api.linkedin.com
x-li-auth-token: OUT_OF_NETWORK:wHti
accept-encoding: gzip, deflate
user-agent: Python-httplib2/$Rev$
Response:
{'status': '200', 'content-length': '158', 'content-location': u'http://api.linkedin.com/v1/people/UBAQYFeiHo:(id,first-name,last-name)?oauth_body_hash=2jmj7l5rSw0yVb%2FvlWAYkK%2FYBwk%3D&oauth_nonce=27886786&oauth_timestamp=1330098212&oauth_consumer_key=xxx&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_token=xxx&oauth_signature=xxx', 'transfer-encoding': 'chunked', 'vary': '*', 'server': 'Apache-Coyote/1.1', '-content-encoding': 'gzip', 'date': 'Fri, 24 Feb 2012 15:43:34 GMT', 'x-li-request-id': 'N368G241EA', 'x-li-format': 'xml', 'content-type': 'text/xml;charset=UTF-8'}
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
<id>UBAQYFeiHo</id>
<first-name></first-name>
<last-name>Private</last-name>
</person>
The python code to make the second part work with the oauth2 library is:
import oauth2 as oauth
import time
url = "http://api.linkedin.com/v1/people/UBAQYFeiHo:(id,first-name,last-name)"
consumer = oauth.Consumer(
key="xxx",
secret="xxx")
token = oauth.Token(
key="xxx",
secret="xxx")
client = oauth.Client(consumer, token)
resp, content = client.request(url, headers={'x-li-auth-token':'OUT_OF_NETWORK:wHti'})
print resp
print content

Categories

Resources