Python requests 0.x code port to 2.x - python

I had a really simple piece of code working with Python requests 0.x but when I updated to 2.x it no longer works.
The code would return me the color contained within 'field1':
import time
import requests
# Read the thingspeak feed to get the current colour
while True:
cheerlights = requests.get('http://api.thingspeak.com/channels/1417/field/1/last.json').json['field1']
print(cheerlights)
time.sleep(16)
When I run this not I get this error:
Traceback (most recent call last):
File "cheelightsJsonHELP.py", line 7, in
cheerlights = requests.get('http://api.thingspeak.com/channels/1417/field/1/last.json').json['field1']
TypeError: 'instancemethod' object has no attribute 'getitem'
I have read the documentation on migrating from 0.x to 2.x but unfortunately this is not a strong area of mine, can anybody help?

response.json() is now a method, where in the past it was a property; add () to call it:
response = requests.get('http://api.thingspeak.com/channels/1417/field/1/last.json')
cheerlights = response.json()['field1']
Demo:
>>> import requests
>>> response = requests.get('http://api.thingspeak.com/channels/1417/field/1/last.json')
>>> response.json()['field1']
'orange'

Related

'str' object has no attribute 'from_directory_url' in python

I am trying to make the call
from azure.storage.fileshare import ShareDirectoryClient
shrdDirClient = ShareDirectoryClient.from_directory_url
(detailedFileURI,snapshot=None, credential=None)
but resulted in the error above.
I tried
if hasattr(ShareDirectoryClient, 'from_directory_url'):
print("Present")
But it did not go into the loop.
My full code is too long. This is another approach I tried resulting in 'str' object is not callable error
from azure.storage.fileshare import ShareDirectoryClient
from datetime import timedelta,datetime
now = datetime.now(timezone('UTC'))
sasToken = generate_share_sas(accountName, shareName, accountKey,\
permission=AccountSasPermissions(read=True, \
write=False, \
delete=False, \
list=True, create=True), expiry=now + timedelta(days=3650)\
)
accountURL = "https://nsclusterhdistorage.file.core.windows.net"
shareName = "dev-archived-data"
detailedFileURI = accountURL+'/'+shareName
sh = ShareDirectoryClient()
sh.from_directory_url(detailedFileURI,snapshot=None, credential=sasToken)
I am relatively new to python azure storage file share.
can someone help
Sorry, I can't reproduce this.
I ran the following code:
from azure.storage.fileshare import ShareDirectoryClient
detailedFileURI = "Something"
shrdDirClient = ShareDirectoryClient.from_directory_url(detailedFileURI,snapshot=None, credential=None)
and it generated the following error:
Traceback (most recent call last):
File "D:\StackOverflow\azure_storage_test.py", line 4, in <module>
shrdDirClient = ShareDirectoryClient.from_directory_url(detailedFileURI,snapshot=None, credential=None)
File "C:\Python37\lib\site-packages\azure\storage\fileshare\_directory_client.py", line 164, in from_directory_url
credential=credential, **kwargs)
File "C:\Python37\lib\site-packages\azure\storage\fileshare\_directory_client.py", line 96, in __init__
raise ValueError("Please specify a share name.")
ValueError: Please specify a share name.
Now clearly this isn't successful execution. If I'm honest, I don't know what to set detailedFileURI to. But that's not the point. The point is that the code sample above is enough to prove that I can get in to the from_directory_url method, and this is clear from the traceback.
However, if I run the following code:
from azure.storage.fileshare import ShareDirectoryClient
ShareDirectoryClient = "some string"
detailedFileURI = "Something"
shrdDirClient = ShareDirectoryClient.from_directory_url(detailedFileURI,snapshot=None, credential=None)
then I do encounter the same error:
Traceback (most recent call last):
File "D:\StackOverflow\azure_storage_test.py", line 5, in <module>
shrdDirClient = ShareDirectoryClient.from_directory_url(detailedFileURI,snapshot=None, credential=None)
AttributeError: 'str' object has no attribute 'from_directory_url'
Of course, there's not a lot of point in importing ShareDirectoryClient if you're then going to assign a string to it. You may as well remove the import statement. However, doing this reproduces your error message. In the absence of any further code in your question I can only conclude that your code does the same as this, although perhaps more subtly.
The only other suggestion I have is that your installation of the azure-storage-file-share package has somehow got broken. If you run a Python script containing the following two lines only, you should get either <class 'type'> or <class 'str'> as output. I get <class 'type'>, and I would expect that anyone else using this package would get the same. However, if you get <class 'str'>, then it is likely that the package has got corrupted and you may want to try reinstalling it.
from azure.storage.fileshare import ShareDirectoryClient
print(type(ShareDirectoryClient))
For some reason ‘ ShareDirectoryClient’ is of type {string}. You either import it as a string, i.e. ‘ azure.storage.fileshare’ simply has this defined as a string, or, you assign it to a string later in your code (not visible in the part that has been shared). Please try this:
X = ‘some_string’
X()
… and you will get the string-is-not-callable error which means a string cannot be invoked (i.e. it is not a function one can call)
Then another experiment:
Y = ‘another_string’
Y.bla()
… and you get the other error that a string object has no attribute named ‘bla’.
In Python everything is an object. If you define
class MyClass()
pass
And then try ‘MyClass.bla()’ you will get MyClass does does not have attribute ‘bla’.
Can you try to import ShareDirectoryClient and then type(ShareDirectoryClient) and we’ll see what type of object gets imported.

How to make screenshot from web page? [duplicate]

This question already has answers here:
ModuleNotFoundError: What does it mean __main__ is not a package?
(6 answers)
Closed 4 years ago.
How to make screenshot from any url (web page)?
I was trying:
from .ghost import Ghost
ghost = Ghost(wait_timeout=4)
ghost.open('http://www.google.com')
ghost.capture_to('screen_shot.png')
Result:
No module named '__main__.ghost'; '__main__' is not a package
I was trying also:
Python Webkit making web-site screenshots using virtual framebuffer
Take screenshot of multiple URLs using selenium (python)
Fastest way to take a screenshot with python on windows
Take a screenshot of open website in python script
I've also tried other methods that are not listed here.
Nothing succeeded. Or an error or module is not found .. or or or.
I'm tired. Is there an easy way to make a screenshot of a web page using Python 3.X?
upd1:
C:\prg\PY\PUMA\tests>py save-web-html.py
Traceback (most recent call last):
File "save-web-html.py", line 2, in <module>
from .ghost import Ghost
ModuleNotFoundError: No module named '__main__.ghost'; '__main__' is not a package
upd2:
C:\prg\PY\PUMA\tests>py save-web-html.py
Exception ignored in: <bound method Ghost.__del__ of <ghost.ghost.Ghost object at 0x0000020A169CF860>>
Traceback (most recent call last):
File "C:\Users\Coar\AppData\Local\Programs\Python\Python36\lib\site-packages\ghost\ghost.py", line 325, in __del__
self.exit()
File "C:\Users\Coar\AppData\Local\Programs\Python\Python36\lib\site-packages\ghost\ghost.py", line 315, in exit
self._app.quit()
AttributeError: 'NoneType' object has no attribute 'quit'
Traceback (most recent call last):
File "save-web-html.py", line 4, in <module>
ghost = Ghost(wait_timeout=4)
TypeError: __init__() got an unexpected keyword argument 'wait_timeout'
In the late 80's this may have been a simple task, just render some html to an image instead of the screen.
But these days web-pages require client-side execution to build parts of its DOM and re-render based on client-side initiated AJAX (or equivalent) requests... it's a whole thing "web 2.0" thing.
Rendering a web-site such as http://google.com as a simple html return should be easy, but rendering something like https://www.facebook.com/ or https://www.kogan.com/ will have many back & fourth comms to display what you're expecting to see.
So restricting this to a pure python solution may not be plausible; I'm not aware of a python-based browser.
Consider running a separate service to take the screenshots, and use your core application (in python) to fetch requested screenshots.
I just tried a few with docker, many of them struggle with https and the aforementioned ajax behaviour.
earlyclaim/docker-manet appears to work demo page
edit: from your comments, you need the data from a graph that's rendered using a 2nd request.
you just need the json return from https://www.minnowbooster.net/limit/chart
try:
from urllib.request import urlopen # py3
except ImportError:
from urllib2 import urlopen # py2
import json
url = 'https://www.minnowbooster.net/limit/chart'
response = urlopen(url)
data_str = response.read().decode()
data = json.loads(data_str)
print(data)

AttributeError: 'DocsClient' object has no attribute 'GetDocumentListFeed'

I'm currently trying to build a Script that interacts with Google's API's, but I keep getting an Attribute error:
Traceback (most recent call last):
File "service_catalog_automation.py", line 18, in <module>
feed = client.GetDocumentListFeed()
AttributeError: 'DocsClient' object has no attribute 'GetDocumentListFeed'
This is the code I'm trying to use
import gdata.gauth
import gdata.docs.client
import sys
def sys_print(text):
sys.stdout.write(str(text))
sys.stdout.flush()
CONSUMER_KEY = 'domain.com'
CONSUMER_SECRET = 'abcde1234'
requestor_id = 'myuser#domain.com'
client = gdata.docs.client.DocsClient(source='my-script-v1')
client.auth_token = gdata.gauth.TwoLeggedOAuthHmacToken(
CONSUMER_KEY, CONSUMER_SECRET, requestor_id)
# Retrieve user's list of Google Docs
feed = client.GetDocumentListFeed()
for entry in feed.entry:
sys_print(entry.title.text)
sys_print('\n')
I've pulled client.getDocumentListFeed() portion of code from their sample code here and have even tried a bare minimum approach using their sample code under the 2LeggedOAuth section here. (I also have tried GetDocList() from that example with the same error)
I have downloaded Google's gdata-python-client to a linux vm's home directory and installed it by running python setup.py install and ran the test python all_tests.py with no errors.
Any help would be greatly apperciated
In the first example, they're assigning their client object as the return of gdata.docs.service.DocsService().
The second example also returns the client object as a DocsService type:
client = gdata.docs.service.DocsService(source='yourCompany-YourAppName-v1')
This would seem to imply that gd_client is of type DocsService, not DocsClient

Error when calling flickrapi.photosets.getPhotos method

I am trying to use flickrapi from #sybren on python 3.4.
Therefore i cloned the main branch of the repo and installed the package.
Some function calls do work, but some give me this error:
Traceback (most recent call last):
File "D:\personal works\flickrWorks\flickr_derpage.py", line 20, in <module>
flickr.photosets.getPhotos(set_id)
TypeError: __call__() takes 1 positional argument but 2 were given
The call to the function is this one:
import flickrapi
import xml.etree.ElementTree as ET
# config stuff
api_key = 'fuhsdkjfsdjkfsjk'
api_secret = 'fdjksnfkjsdnfkj'
user_tbp_dev = "fednkjfnsdjkfnjksdn5"
# le program
flickr = flickrapi.FlickrAPI(api_key, api_secret)
sets = flickr.photosets.getList(user_id=user_tbp_dev)
set0 = sets.find('photosets').findall('photoset')
set_id = set0[0].get('id')
sett_photos = flickr.photosets.getPhotos(set_id)
print(ET.dump(sett_photos))
Another method which gives the same error is:
flickr.reflection.getMethodInfo("flickr.photos.search")
Any ideas what might i do wrong, or if the library has some issues (as the python3 branch is still under development).
Thanks!
The flickrapi expects the parameters to the functions to be named arguments, not positional. This works for me:
flickr.photosets_getPhotos(photoset_id=set_id, extras="license, date_upload, date_taken")
To get a list of the argument names for the Flickr calls, see the documentation here: https://www.flickr.com/services/api/flickr.photosets.getPhotos.html

Error when using astWCS trying to create WCS object

I'm running python2.5 and trying to use the astLib library to analyse WCS information in astronomical images. I try and get the object instanciated with the following skeleton code:
from astLib import astWCS
w = astWCS.WCS('file.fits') # error here
where file.fits is a string pointing to a valid fits file.
I have tried using the alternate method of passing a pyfits header object and this fails also:
import pyfits
from astLib import astWCS
f = pyfits.open('file.fits')
header = f[0].header
f.close()
w = astWCS.WCS(header, mode='pyfits') # error here also
The error is this:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/home/astro/phrfbf/build/lib/python2.6/site-packages/astLib/astWCS.py", line 79, in __init__
self.updateFromHeader()
File "/home/astro/phrfbf/build/lib/python2.6/site-packages/astLib/astWCS.py", line 119, in updateFromHeader
self.WCSStructure=wcs.wcsinit(cardstring)
File "/home/astro/phrfbf/build/lib/python2.6/site-packages/PyWCSTools/wcs.py", line 70, in wcsinit
return _wcs.wcsinit(*args)
TypeError: in method 'wcsinit', argument 1 of type 'char *'
When I run in ipython, I get the full error here on the pastebin
I know the astWCS module is a wrapped version of WCStools but i'd prefer to use the Python module as the rest of my code is in Python
Can anyone help with this problem?
Just found out the updated version of this library has fixed the problem, thanks for everyone's help
Oh sorry, I should have seen. Looking at the pastebin in more detail, the only error I can think of is that, for some reason the header has unicode in it. It can't be converted to char *, and you get the error. I tried searching for something in the header, but everything looks okay. Can you do this and post the output in another pastebin?
import pyfits
f = pyfits.open('file.fits')
header = f[0].header
f.close()
for x, i in enumerate(header.iteritems()):
if len(str(i[1])) >= 70:
print x, str(i[1])
cardlist = header.ascardlist()
cardstring = ""
for card in cardlist:
cardstring = cardstring + str(card)
print repr(cardstring)
Or, if you can check the header of your fits file for "funny" characters, getting rid of them should solve the issue.

Categories

Resources