Spotipy: User_create_playlist - Method Not Allowed for url - python

Using the spotipy library, I'm trying to create a playlist. However, the user_create_playlist method is not allowed for my url. Here is part of my code to show an example of how I'm authenticating my app and what I'm using to run the method:
username = 'my-username'
token = util.prompt_for_user_token(username = username,
scope = 'playlist-modify-public'
client_id='my-spotify-client-id',
client_secret='my-spotify-client-secret-id',
redirect_uri='https://developer.spotify.com/')
spotifyObject = spotipy.Spotify(auth=token)
playlist_name = "Test Playlist"
playlist_description = "This is a test playlist."
playlists = spotifyObject.user_playlist_create(username, playlist_name,
playlist_description)
pprint.pprint(playlists)
Do you know why I am getting the following error message?
Traceback (most recent call last):
File "C:\Users....\spotipy\client.py", line 121, in _internal_call
r.raise_for_status()
File "C:\Users....requests\models.py", line 935, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 405 Client Error: Method Not Allowed for url: https://api.spotify.com/v1/users/'username'/playlists
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users....\SpotifyTest.py", line 108, in
main()
File "C:\Users....\SpotifyTest.py", line 53, in main
playlists = spotifyObject.user_playlist_create(username, playlist_name, playlist_description)
File "C:\Users....\spotipy\client.py", line 415, in user_playlist_create
return self._post("users/%s/playlists" % (user,), payload=data)
File "C:\Users.....\spotipy\client.py", line 180, in _post
return self._internal_call('POST', url, payload, kwargs)
File "C:\Users....\spotipy\client.py", line 129, in _internal_call
-1, '%s:\n %s' % (r.url, 'error'), headers=r.headers)
spotipy.client.SpotifyException: http status: 405, code:-1 - https://api.spotify.com/v1/users/'username'/playlists:
error

Related

Receiving EPIPE error when streaming from PSQL copy function

I am trying to write a streaming implementation of dumping a table from psql into a pre-signed URL on S3. Unfortunately, it seems to error out at a seemingly random time in the upload. I have tried many combinations of opening/closing the file descriptors at different times. I for the life of me cannot figure out why this is occurring.
The strangest thing is when I mock the requests library and analyze the sent data, it works as intended. The socket is raising an EPIPE error at a certain amount through the stream
from psycopg2 import connect
import threading
import requests
import requests_mock
import traceback
from base64 import b64decode
from boto3 import session
r_fd, w_fd = os.pipe()
connection = connect(host='host', database='db',
user='user', password='pw')
cursor = connection.cursor()
b3_session = session.Session(profile_name='profile', region_name='us-east-1')
url = b3_session.client('s3').generate_presigned_url(
ClientMethod='put_object',
Params={'Bucket': 'bucket', 'Key': 'test_streaming_upload.txt'},
ExpiresIn=3600)
rd = os.fdopen(r_fd, 'rb')
wd = os.fdopen(w_fd, 'wb')
def stream_data():
print('Starting stream')
with os.fdopen(r_fd, 'rb') as rd:
requests.put(url, data=rd, headers={'Content-type': 'application/octet-stream'})
print('Ending stream')
to_thread = threading.Thread(target=stream_data)
to_thread.start()
print('Starting copy')
with os.fdopen(w_fd, 'wb') as wd:
cursor.copy_expert('COPY table TO STDOUT WITH CSV HEADER', wd)
print('Ending copy')
to_thread.join()
The output is always the same:
Starting stream
Starting copy
Exception in thread Thread-1:
Traceback (most recent call last):
File "/venv/lib/python3.9/site-packages/urllib3/contrib/pyopenssl.py", line 342, in _send_until_done
return self.connection.send(data)
File "/venv/lib/python3.9/site-packages/OpenSSL/SSL.py", line 1718, in send
self._raise_ssl_error(self._ssl, result)
File "/venv/lib/python3.9/site-packages/OpenSSL/SSL.py", line 1624, in _raise_ssl_error
raise SysCallError(errno, errorcode.get(errno))
OpenSSL.SSL.SysCallError: (32, 'EPIPE')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/venv/lib/python3.9/site-packages/requests/adapters.py", line 473, in send
low_conn.send(b'\r\n')
File "/Users/me/.pyenv/versions/3.9.7/lib/python3.9/http/client.py", line 995, in send
self.sock.sendall(data)
File "/venv/lib/python3.9/site-packages/urllib3/contrib/pyopenssl.py", line 354, in sendall
sent = self._send_until_done(
File "/venv/lib/python3.9/site-packages/urllib3/contrib/pyopenssl.py", line 349, in _send_until_done
raise SocketError(str(e))
OSError: (32, 'EPIPE')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/me/.pyenv/versions/3.9.7/lib/python3.9/threading.py", line 973, in _bootstrap_inner
self.run()
File "/Users/me/.pyenv/versions/3.9.7/lib/python3.9/threading.py", line 910, in run
self._target(*self._args, **self._kwargs)
File "/Users/me/Library/Application Support/JetBrains/PyCharm2021.2/scratches/scratch_60.py", line 37, in stream_data
requests.put(url, data=rd, headers={'Content-type': 'application/octet-stream'})
File "/venv/lib/python3.9/site-packages/requests/api.py", line 131, in put
return request('put', url, data=data, **kwargs)
File "/venv/lib/python3.9/site-packages/requests/api.py", line 60, in request
return session.request(method=method, url=url, **kwargs)
File "/venv/lib/python3.9/site-packages/requests/sessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "/venv/lib/python3.9/site-packages/requests/sessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "/venv/lib/python3.9/site-packages/requests/adapters.py", line 498, in send
raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: (32, 'EPIPE')
Am I missing something obvious? Is this a memory error? I appreciate any insight I can get because this is killing me. I can verify that the socket is being written to anywhere from 1.5 to 2.5k times before this error occurs.

How to add constraints in client.services.create while creating a new service in existing docker swarm Python Docker SDK?

I want to create a service in existing swarm network using python docker sdk. I have a swarm network named test_net.
Installation of library : pip3 install docker
Below is the code used for creating the service
import docker
from docker.types import RestartPolicy, Placement
def python_sdk():
client = docker.DockerClient(base_url='unix://var/run/docker.sock')
service_created = client.services.create(
image='python:3.7-alpine',
command='python /home/ubuntu/python.py',
constraints=Placement(constraints=['worker']),
mounts='/home/ubuntu/deployment/python.py:/home/ubuntu/python.py:rw',
networks=['test_net'],
restart_policy=RestartPolicy(condition='none'),
name='python_sdk'
)
print("Created service : ", service_created)
Below is the error which I got by executing above code :
Traceback (most recent call last):
File "/home/ubuntu/deployment/dags/venv/lib/python3.6/site-packages/docker/api/client.py", line 268, in _raise_for_status
response.raise_for_status()
File "/home/ubuntu/deployment/dags/venv/lib/python3.6/site-packages/requests/models.py", line 943, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: http+docker://localhost/v1.41/services/create
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "client.py", line 20, in <module>
python_sdk()
File "client.py", line 16, in python_sdk
name='python_sdk'
File "/home/ubuntu/deployment/dags/venv/lib/python3.6/site-packages/docker/models/services.py", line 227, in create
service_id = self.client.api.create_service(**create_kwargs)
File "/home/ubuntu/deployment/dags/venv/lib/python3.6/site-packages/docker/utils/decorators.py", line 34, in wrapper
return f(self, *args, **kwargs)
File "/home/ubuntu/deployment/dags/venv/lib/python3.6/site-packages/docker/api/service.py", line 190, in create_service
self._post_json(url, data=data, headers=headers), True
File "/home/ubuntu/deployment/dags/venv/lib/python3.6/site-packages/docker/api/client.py", line 274, in _result
self._raise_for_status(response)
File "/home/ubuntu/deployment/dags/venv/lib/python3.6/site-packages/docker/api/client.py", line 270, in _raise_for_status
raise create_api_error_from_http_exception(e)
File "/home/ubuntu/deployment/dags/venv/lib/python3.6/site-packages/docker/errors.py", line 31, in create_api_error_from_http_exception
raise cls(e, response=response, explanation=explanation)
docker.errors.APIError: 400 Client Error for http+docker://localhost/v1.41/services/create: Bad Request ("json: cannot unmarshal object into Go struct field Placement.TaskTemplate.Placement.Constraints of type []string")
I am referring to this documentation.
How can I use Placement object to use constraints?
I also tried constraints = ["Placement(constraints=['worker']"]
I got the answer for the above issue. In the documentation, it is mentioned that the list of str needs to be passed in constraints.
The mentioned parameter is documentation : constraints (list of str) – Placement constraints.
So the final code will be,
import docker
from docker.types import RestartPolicy, Placement
def python_sdk():
client = docker.DockerClient(base_url='unix://var/run/docker.sock')
service_created = client.services.create(
image='python:3.7-alpine',
command='python /home/ubuntu/python.py',
constraints=['node.role == worker']),
mounts='/home/ubuntu/deployment/python.py:/home/ubuntu/python.py:rw',
networks=['test_net'],
restart_policy=RestartPolicy(condition='none'),
name='python_sdk'
)
print("Created service : ", service_created)

Python Script Returning an error when trying to Obtain TFS work Items

I have written the following Pythin script to try and gather TFS (Team Foundation Server) work item data. Below is my script:-
from tfs import TFSAPI
user="andrew.xxxx"
password="xxxxxxxx"
tfsAddress = "http://man-tfsmig-1:8080/"
print(tfsAddress)
client = TFSAPI(tfsAddress, project="DefaultCollection/xxxxxxxx", user=user, password=password)
work_item = client.get_workitem(28274)
When I run the code I get the following error, but I do not know what the problem is:-
Traceback (most recent call last):
File ".\TFS_Release_Notes_app.py", line 13, in <module>
work_item = client.get_workitem(28274)
File "C:\Python\lib\site-packages\tfs\connection.py", line 70, in get_workitem
return self.get_workitems(id_, fields)[0]
File "C:\Python\lib\site-packages\tfs\connection.py", line 80, in get_workitems
work_items_batch_info = self.__get_workitems(work_items_batch, fields=fields, expand=expand)
File "C:\Python\lib\site-packages\tfs\connection.py", line 65, in __get_workitems
object_class=Workitem)
File "C:\Python\lib\site-packages\tfs\connection.py", line 46, in get_tfs_object
raw = self.rest_client.send_get(uri=uri, payload=payload, project=project)
File "C:\Python\lib\site-packages\tfs\connection.py", line 323, in send_get
return self.__send_request('GET', uri, None, payload=payload, project=project, json=json)
File "C:\Python\lib\site-packages\tfs\connection.py", line 360, in __send_request
response.raise_for_status()
File "C:\Python\lib\site-packages\requests\models.py", line 939, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: http://xxxx-xxxxx-1:8080/DefaultCollection/_apis/wit/workitems?ids=28274&$expand=all&api-version=1.0
It's telling you the error: 404, not found.
That means the URI you're providing for the API is incorrect.
It's generating this URI: http://xxxx-xxxxx-1:8080/DefaultCollection/_apis/wit/workitems. Validate if that is correct.
Usually, when TFS is running on port 8080 over HTTP, there's a /tfs/ virtual directory.
I needed to add the following line to authenticate:-
# Use NTLM authorization
from requests_ntlm import HttpNtlmAuth
client = TFSAPI("https://tfs.tfs.ru/tfs/", user=user, password=password, auth_type=HttpNtlmAuth)

422 Client Error: Unknown Error Soundcloud API Track Upload

Having some problems uploading a track using the soundcloud python library to interact with the Soundcloud api.
Error Log:
Traceback (most recent call last):
File "uploadToSoundcloud.py", line 25, in <module>
'asset_data': open('/home/jhvisser/Music/driveAt5_'+now.strftime("%y%m%d")+'.mp3', 'rb')
File "/usr/local/lib/python2.7/dist-packages/soundcloud/client.py", line 130, in _request
return wrapped_resource(make_request(method, url, kwargs))
File "/usr/local/lib/python2.7/dist-packages/soundcloud/request.py", line 134, in make_request
result.raise_for_status()
File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 722, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.422 Client Error: Unknown Error
Code causing error. Line 25 refers to the assest_data line.
#Upload driveAtFive to SoundCloud
driveAtFive = client.post('/tracks', driveAtFive={
'title': 'Drive at 5 - ' + now.strftime("%Y-%m-%d"),
'sharing': 'public',
'asset_data': open('/home/jhvisser/Music/driveAt5_'+now.strftime("%y%m%d")+'.mp3', 'rb')
})
You need to pass the track keyword argument. Here you've named it driveAtFive which is incorrect. Change the code example to this:
driveAtFive = client.post('/tracks', track={
'title': 'Drive at 5 - ' + now.strftime("%Y-%m-%d"),
'sharing': 'public',
'asset_data': open('/home/jhvisser/Music/driveAt5_'+now.strftime("%y%m%d")+'.mp3', 'rb')
})
Let me know if that helps.

Working with Twitter API v1.1

I launched this code via terminal via command python py/twi.py and it shows no reaction:
import oauth, tweepy
from time import sleep
message = "hello"
def init():
global api
#confident information
consumer_key = "***"
consumer_secret = "***"
callback_url = "https://twitter.com/Problem196"
access_key="***"
access_secret="***"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret, callback_url)
auth.set_access_token(access_key, access_secret)
api=tweepy.API(auth)
init()
api.update_status(message)
But it supposed to post tweet "hello" on page https://twitter.com/problem196 .
I have updated tweepy, it's fine. Why it's not posting? I have no idea. Please help.
UPD: After I put code print api.last_response.msg terminal showed me some errors:
artem#artem-VirtualBox:~$ python py/twi.py
Traceback (most recent call last):
File "py/twi.py", line 20, in <module>
api.update_status(message)
File "/usr/local/lib/python2.7/dist-packages/tweepy-2.1-py2.7.egg/tweepy/binder.py", line 197, in _call
return method.execute()
File "/usr/local/lib/python2.7/dist-packages/tweepy-2.1-py2.7.egg/tweepy/binder.py", line 154, in execute
raise TweepError('Failed to send request: %s' % e)
tweepy.error.TweepError: Failed to send request: [Errno -2] Name or service not known
artem#artem-VirtualBox:~$ python py/twi.py
Traceback (most recent call last):
File "py/twi.py", line 20, in <module>
api.update_status(message)
File "/usr/local/lib/python2.7/dist-packages/tweepy-2.1-py2.7.egg/tweepy/binder.py", line 197, in _call
return method.execute()
File "/usr/local/lib/python2.7/dist-packages/tweepy-2.1-py2.7.egg/tweepy/binder.py", line 173, in execute
raise TweepError(error_msg, resp)
tweepy.error.TweepError: [{'message': 'Status is a duplicate', 'code': 187}]

Categories