I have been trying to use the Instagram API with python. After getting valid access_token, client_id, client_secret, I have tried to use the function user_recent_media.
access_token -
access_token, user_info = unauthenticated_api.exchange_code_for_access_token(code)
setting connection
api = client.InstagramAPI(access_token=access_token, client_secret=client_secret)
The connection is established successfully and then I wanted to get the user_recent media:
recent_media, next = api.user_recent_media(user_id = user_info['id'], count = 10)
Then I get the following error:
Traceback (most recent call last):
File "C:/instagram/main.py", line 57, in <module>
recent_media, next = api.user_recent_media(user_id = user_info['id'], count = 10)
File "C:\Users\user-pc\Anaconda\lib\site-packages\instagram\bind.py", line 197, in _call
return method.execute()
File "C:\Users\user-pc\Anaconda\lib\site-packages\instagram\bind.py", line 189, in execute
content, next = self._do_api_request(url, method, body, headers)
File "C:\Users\user-pc\Anaconda\lib\site-packages\instagram\bind.py", line 151, in _do_api_request
obj = self.root_class.object_from_dictionary(entry)
File "C:\Users\user-pc\Anaconda\lib\site-packages\instagram\models.py", line 99, in object_from_dictionary
for comment in entry['comments']['data']:
KeyError: 'data'
Someone knows what is the problem? I have checked everywhere and couldn't find the reason for this error.
Related
I am testing the python-youtube package, using the following code:
from pyyoutube import Api
api = Api(
client_id="yes-my-client-id-here-i-know",
client_secret="yes-my-client-secret-here-i-know")
authorization_url = api.get_authorization_url()
access_token = api.generate_access_token(authorization_response=authorization_url[0])
print('authorization_url : >>>>>> ', authorization_url)
print('access_token : >>>>>> ', access_token)
I get the following error.
Traceback (most recent call last):
File "main.py", line 10, in <module>
access_token = api.generate_access_token(authorization_response=authorization_url[0])
File "/Users/sleento/production/python-youtube-api/env/lib/python3.8/site-packages/pyyoutube/api.py", line 263, in generate_access_token
token = oauth_session.fetch_token(
File "/Users/sleento/production/python-youtube-api/env/lib/python3.8/site-packages/requests_oauthlib/oauth2_session.py", line 244, in fetch_token
self._client.parse_request_uri_response(
File "/Users/sleento/production/python-youtube-api/env/lib/python3.8/site-packages/oauthlib/oauth2/rfc6749/clients/web_application.py", line 220, in parse_request_uri_response
response = parse_authorization_code_response(uri, state=state)
File "/Users/sleento/production/python-youtube-api/env/lib/python3.8/site-packages/oauthlib/oauth2/rfc6749/parameters.py", line 284, in parse_authorization_code_response
raise MissingCodeError("Missing code parameter in response.")
oauthlib.oauth2.rfc6749.errors.MissingCodeError: (missing_code) Missing code parameter in response.
I solve that, I was using client_id instead of api_key parameter.
from pyyoutube import Api
api = Api(
api_key="yes-my-APi-key-here-i-know")
authorization_url = api.get_authorization_url()
print('authorization_url : >>>>>> ', authorization_url)
I just want to learn how to store data in Firestore using Python and Google Cloud Platform, so I'm calling an API to query some example data.
For it, I'm using requests library and Firebase library from google.cloud package.
Here is the code that I'm running at Cloud Shell:
import requests
from google.cloud import firestore
url = "https://api.coindesk.com/v1/bpi/currentprice.json"
r = requests.get(url)
resp: str = r.text
if not (resp=="null" or resp=="[]"):
db = firestore.Client()
doc_ref=db.collection("CoinData").add(r.json())
When the code try to connect to Firebase to add the json of the API response I got this error:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/google/api_core/grpc_helpers.py", line 66, in error_remapped_callable
return callable_(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/grpc/_channel.py", line 946, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "/usr/local/lib/python3.7/dist-packages/grpc/_channel.py", line 849, in _end_unary_response_blocking
raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
status = StatusCode.INVALID_ARGUMENT
details = "Invalid resource field value in the request."
debug_error_string = "{"created":"#1634689546.004704998","description":"Error received from peer ipv4:74.125.134.95:443","file":"src/core/lib/surface/call.cc","file_line":1070,"grpc_message":"Invalid resource field value in the request.","grpc_status":3}"
>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/antonyare_93/cloudshell_open/pruebas/data_coin_query.py", line 11, in <module>
doc_ref=db.collection("CoinData").add(r.json())
File "/home/antonyare_93/.local/lib/python3.7/site-packages/google/cloud/firestore_v1/collection.py", line 107, in add
write_result = document_ref.create(document_data, **kwargs)
File "/home/antonyare_93/.local/lib/python3.7/site-packages/google/cloud/firestore_v1/document.py", line 99, in create
write_results = batch.commit(**kwargs)
File "/home/antonyare_93/.local/lib/python3.7/site-packages/google/cloud/firestore_v1/batch.py", line 60, in commit
request=request, metadata=self._client._rpc_metadata, **kwargs,
File "/home/antonyare_93/.local/lib/python3.7/site-packages/google/cloud/firestore_v1/services/firestore/client.py", line 815, in commit
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
File "/usr/local/lib/python3.7/dist-packages/google/api_core/gapic_v1/method.py", line 142, in __call__
return wrapped_func(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/google/api_core/retry.py", line 288, in retry_wrapped_func
on_error=on_error,
File "/usr/local/lib/python3.7/dist-packages/google/api_core/retry.py", line 190, in retry_target
return target()
File "/usr/local/lib/python3.7/dist-packages/google/api_core/grpc_helpers.py", line 68, in error_remapped_callable
raise exceptions.from_grpc_error(exc) from exc
google.api_core.exceptions.InvalidArgument: 400 Invalid resource field value in the request.
Anyone knows how I can fix it?
I've just got it.
It was a little mistake, I was missing the name of the project at the firestore client method call, here's the code working:
import requests
from google.cloud import firestore
url = "https://api.coindesk.com/v1/bpi/currentprice.json"
r = requests.get(url)
resp: str = r.text
if not (resp=="null" or resp=="[]"):
db = firestore.Client(project="mytwitterapitest")
doc_ref=db.collection("CoinData").add(r.json())
I have a config.ini file that looks like this
[REDDIT]
client_id = 'myclientid23jd934g'
client_secret = 'myclientsecretjf30gj5g'
password = 'mypassword'
user_agent = 'myuseragent'
username = 'myusername'
When I try to use reddit's API praw like this:
import configparser
import praw
class redditImageScraper:
def __init__(self, sub, limit):
config = configparser.ConfigParser()
config.read('config.ini')
self.sub = sub
self.limit = limit
self.reddit = praw.Reddit(client_id=config.get('REDDIT','client_id'),
client_secret=config.get('REDDIT','client_secret'),
password=config.get('REDDIT','password'),
user_agent=config.get('REDDIT','user_agent'),
username=config.get('REDDIT','username'))
def get_content(self):
submissions = self.reddit.subreddit(self.sub).hot(limit=self.limit)
for submission in submissions:
print(submission.id)
def main():
scraper = redditImageScraper('aww', 25)
scraper.get_content()
if __name__ == '__main__':
main()
I get this traceback
Traceback (most recent call last):
File "config.py", line 30, in <module>
main()
File "config.py", line 27, in main
scraper.get_content()
File "config.py", line 22, in get_content
for submission in submissions:
File "C:\Users\Evan\Anaconda3\lib\site-packages\praw\models\listing\generator.py", line 61, in __next__
self._next_batch()
File "C:\Users\Evan\Anaconda3\lib\site-packages\praw\models\listing\generator.py", line 71, in _next_batch
self._listing = self._reddit.get(self.url, params=self.params)
File "C:\Users\Evan\Anaconda3\lib\site-packages\praw\reddit.py", line 454, in get
data = self.request("GET", path, params=params)
File "C:\Users\Evan\Anaconda3\lib\site-packages\praw\reddit.py", line 627, in request
method, path, data=data, files=files, params=params
File "C:\Users\Evan\Anaconda3\lib\site-packages\prawcore\sessions.py", line 185, in request
params=params, url=url)
File "C:\Users\Evan\Anaconda3\lib\site-packages\prawcore\sessions.py", line 116, in _request_with_retries
data, files, json, method, params, retries, url)
File "C:\Users\Evan\Anaconda3\lib\site-packages\prawcore\sessions.py", line 101, in _make_request
params=params)
File "C:\Users\Evan\Anaconda3\lib\site-packages\prawcore\rate_limit.py", line 35, in call
kwargs['headers'] = set_header_callback()
File "C:\Users\Evan\Anaconda3\lib\site-packages\prawcore\sessions.py", line 145, in _set_header_callback
self._authorizer.refresh()
File "C:\Users\Evan\Anaconda3\lib\site-packages\prawcore\auth.py", line 328, in refresh
password=self._password)
File "C:\Users\Evan\Anaconda3\lib\site-packages\prawcore\auth.py", line 138, in _request_token
response = self._authenticator._post(url, **data)
File "C:\Users\Evan\Anaconda3\lib\site-packages\prawcore\auth.py", line 31, in _post
raise ResponseException(response)
prawcore.exceptions.ResponseException: received 401 HTTP response
However when I manually insert the credentials, my code runs exactly as expected. Also, if I run the line
print(config.get('REDDIT', 'client_id'))
I get the output 'myclientid23jd934g' as expected.
Is there some reason that praw won't allow me to pass my credentials using configparser?
Double check what your inputs to praw.Reddit are:
kwargs = dict(client_id=config.get('REDDIT','client_id'),
client_secret=config.get('REDDIT','client_secret'),
password=config.get('REDDIT','password'),
user_agent=config.get('REDDIT','user_agent'),
username=config.get('REDDIT','username')))
print(kwargs)
praw.Reddit(**kwargs)
You're overcomplicating configuration here — PRAW will take care of this for you.
If you rename config.ini to praw.ini, you can replace your whole initialization with just
self.reddit = praw.Reddit('REDDIT')
This is because PRAW will look for a praw.ini file and parse it for you. If you want to give the section a more descriptive name, make sure to update it in the praw.ini as well as in the single parameter passed to Reddit (which specifies the section of the file to use).
See https://praw.readthedocs.io/en/latest/getting_started/configuration/prawini.html.
As this page notes, values like username and password should not have quotation marks around them. For example,
password=mypassword
is correct, but
password="mypassword"
is incorrect.
I'm using manual on https://www.dropbox.com/developers/core/start/python .
Have made everything equal to manual, including creation of my app in account, copy-past of app keys, allowing to use the app using the key (in fact I open the link in my browser, click allow and copy confirmation code).
After this, I want to finish authorization, but I get such error text:
>>> access_token, user_id = flow.finish(code)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/dropbox/client.py", line 1233, in finish
return self._finish(code, None)
File "/usr/local/lib/python2.7/dist-packages/dropbox/client.py", line 1101, in _finish
response = self.rest_client.POST(url, params=params)
File "/usr/local/lib/python2.7/dist-packages/dropbox/rest.py", line 316, in POST
return cls.IMPL.POST(*n, **kw)
File "/usr/local/lib/python2.7/dist-packages/dropbox/rest.py", line 254, in POST
post_params=params, headers=headers, raw_response=raw_response)
File "/usr/local/lib/python2.7/dist-packages/dropbox/rest.py", line 218, in request
preload_content=False
File "/usr/lib/python2.7/dist-packages/urllib3/poolmanager.py", line 112, in urlopen
conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme)
File "/usr/lib/python2.7/dist-packages/urllib3/poolmanager.py", line 84, in connection_from_host
pool = pool_cls(host, port, **self.connection_pool_kw)
TypeError: __init__() got an unexpected keyword argument 'ssl_version'
P.S. Flow object is alive => http://screencloud.net/v/nDi0
Is seems you use urllib3 version 1.5 or older. Upgrade it to 1.6 or 1.7.
I'm following the tutorial on https://github.com/Shopify/shopify_python_api but at step 4 I always get an "500 Internal Server Error".
I'm not sure whether I do follow the steps correctly.
After step 3 I visit the URL in permission_url in my browser click "Install" and then copy the data from the URL I get redirected to into a python dict called params.
On executing step 4 I get:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File ".../lib/python2.7/site-packages/shopify/session.py", line 53, in __init__
self.token = self.request_token(params['code'])
File ".../lib/python2.7/site-packages/shopify/session.py", line 90, in request_token
response = connection.post(access_token_path, ShopifyResource.headers)
File ".../lib/python2.7/site-packages/pyactiveresource/connection.py", line 313, in post
return self._open('POST', path, headers=headers, data=data)
File ".../lib/python2.7/site-packages/shopify/base.py", line 18, in _open
self.response = super(ShopifyConnection, self)._open(*args, **kwargs)
File ".../lib/python2.7/site-packages/pyactiveresource/connection.py", line 258, in _open
response = Response.from_httpresponse(self._handle_error(err))
File ".../lib/python2.7/site-packages/pyactiveresource/connection.py", line 367, in _handle_error
raise ServerError(err)
ServerError: HTTP Error 500: Internal Server Error
For a private application you do not need to go through the authorization steps to get a token. The token is simply private applications password. So activating a session just requires doing:
session = shopify.Session(SHOP_URL)
session.token = PRIVATE_APPLICATION_PASSWORD
shopify.ShopifyResource.activate_session(session)