json.dumps gives me AttributeError: 'str' object has no attribute 'get' - python

I am getting this error message:
AttributeError: 'str' object has no attribute 'get'
I know that it is my json.dumps that triggers the error. Here is my code:
from django.http import HttpResponse
import os
import datetime
import json
SUNDAY = 6
SATURDAY = 5
weekdayBookingTimes = ["10:00","10:30","11:00","11:30","12:00", "12:30", "13:00","13:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30", "18:00"]
def sendBookingForDate(request):
dateToFetchBookings = request.GET.get('date','')
#Check if date is SUNDAY
if checkDayOfWeek(dateToFetchBookings) == SUNDAY:
pass
#Check if day is Saturday
elif checkDayOfWeek(dateToFetchBookings) == SATURDAY:
if os.path.isfile((dateToFetchBookings+".txt")):
pass #tbt
else:
createBookingsForSaturday(dateToFetchBookings)
#Check if day is normal day
else:
if os.path.isfile(dateToFetchBookings+'.txt'):
pass
else:
createBookingsForNormalDays(dateToFetchBookings)
with open('/home/MScissorss/mysite/mysite/'+dateToFetchBookings+'.txt') as f:
bookingsToSend = json.load(f)
#return HttpResponse(dateToFetchBookings)
return json.dumps(bookingsToSend)
def checkDayOfWeek(date):
tempDateStorage = date.split('-')
year = int(tempDateStorage[0])
month = int(tempDateStorage[1])
day = int(tempDateStorage[2])
return datetime.datetime(year,month,day).weekday()
def createBookingsForSaturday(date):
normalBookings = {}
for x in range(0,11):
normalBookings[x] = {"bookingTime":weekdayBookingTimes[x], "booked":"false", "bookieName":"", "bookieNumber":""}
with open('/home/MScissorss/mysite/mysite/'+date+'.txt', "w") as file:
file.write(json.dumps(normalBookings))
def createBookingsForNormalDays(date):
#Test data
bookings = {}
for x in range(0,17):
bookings[x] = {"bookingTime":weekdayBookingTimes[x], "booked":"false", "bookieName":"", "bookieNumber":""}
with open('/home/MScissorss/mysite/mysite/'+date+'.txt', "w") as file:
file.write(json.dumps(bookings))
Check the end of the first function. That is where i do the return. I also thought that my dictionary was wrongly formatted, but i checked and it looks good:
{
"0": {"bookingTime": "10:00", "booked": "false", "bookieName": "", "bookieNumber": ""},
"1": {"bookingTime": "10:30", "booked": "false", "bookieName": "", "bookieNumber": ""},
"2": {"bookingTime": "11:00", "booked": "false", "bookieName": "", "bookieNumber": ""},
"3": {"bookingTime": "11:30", "booked": "false", "bookieName": "", "bookieNumber": ""}
}
The return that is commented above json.dumps works well. I get no errors when running that. Any ideas on what the problem could be?
UPDATE - Full traceback added
2018-11-15 23:53:05,718: Internal Server Error: /getBookings/
Traceback (most recent call last):
File "/home/MScissorss/.virtualenvs/django2/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/MScissorss/.virtualenvs/django2/lib/python3.7/site-packages/django/utils/deprecation.py", line 93, in __call__
response = self.process_response(request, response)
File "/home/MScissorss/.virtualenvs/django2/lib/python3.7/site-packages/django/middleware/clickjacking.py", line 26, in process_response
if response.get('X-Frame-Options') is not None:
AttributeError: 'str' object has no attribute 'get'

As #Barmar pointed out in the comments. All i needed to do was to change my return from return json.dumps(bookingsToSend) to return JsonResponse(bookingsToSend)

Related

Problem with cycled import in datetime in python

Hi I have 2 functions these functions have a different types of import of datetime. I know where is problem but I do not know how to solute it
my code:
from datetime import datetime
import datetime
def upload_video(title,description,tags,upload_year,uplaod_month,upload_day):
upload_date_time = datetime.datetime(upload_year,uplaod_month,upload_day, 8, 00, 0).isoformat() + '.000Z'
print(f"this is a upload time {upload_date_time}")
request_body = {
'snippet': {
'categoryI': 19,
'title': title,
'description': description,
'tags': tags
},
'status': {
'privacyStatus': 'private',
'publishAt': upload_date_time,
'selfDeclaredMadeForKids': False,
},
'notifySubscribers': False
}
mediaFile = MediaFileUpload('output.MP4')
response_upload = service.videos().insert(
part='snippet,status',
body=request_body,
media_body=mediaFile
).execute()
def date_calculator():
days_in_months = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31}
year = datetime.now().year
month = datetime.now().month
# Read the last used date from the text file
with open("last_used_date.txt", "r") as f:
last_used_date = f.read().strip()
# If the file is empty or the date is invalid, set the last used date to the current date
if not last_used_date or not all(c.isdigit() for c in last_used_date.split(".")):
last_used_day = datetime.now().day
last_used_month = month
else:
last_used_day, last_used_month = map(int, last_used_date.split(".")[:2])
# Generate new dates until the next one is greater than the current date
number = 0
number_test = 1
while True:
date = "{}.{}.{}".format(last_used_day, last_used_month, year)
number += 1
if last_used_day == days_in_months[month]:
last_used_month += 1
last_used_day = 1
else:
last_used_day += 1
if number == 2:
last_used_day += 1
number = 0
number_test += 1
if (last_used_month > month or
(last_used_month == month and last_used_day > datetime.now().day)):
with open("last_used_date.txt", "w") as f:
f.write("{}.{}.{}".format(last_used_day, last_used_month, year))
break
return last_used_day,last_used_month,year
error:
Traceback (most recent call last): File
"c:\Users\Lukas\Dokumenty\python_scripts\Billionare
livestyle\main.py", line 233, in
day,month,year = date_calculator() File "c:\Users\Lukas\Dokumenty\python_scripts\Billionare
livestyle\main.py", line 162, in date_calculator
year = datetime.now().year AttributeError: module 'datetime' has no attribute 'now'
if I will change imports like this:
import datetime
from datetime import datetime
error will look like that:
Traceback (most recent call last): File
"c:\Users\Lukas\Dokumenty\python_scripts\Billionare
livestyle\main.py", line 235, in
upload_video(title,"#Shorts", ["motivation", "business", "luxury", "entrepreneurship", "success", "lifestyle", "inspiration", "wealth",
"financial freedom", "investing", "mindset", "personal development",
"self-improvement", "goals", "hustle", "ambition", "rich life",
"luxury lifestyle", "luxury brand", "luxury travel", "luxury
cars"],year,month,day) File
"c:\Users\Lukas\Dokumenty\python_scripts\Billionare
livestyle\main.py", line 74, in upload_video
upload_date_time = datetime.datetime(upload_year,uplaod_month,upload_day, 8, 00,
0).isoformat() + '.000Z' AttributeError: type object
'datetime.datetime' has no attribute 'datetime'
Unfortunately, the datetime module and the datetime class inside it are spelled exactly the same way. You need to pick one of those things to import and then use it consistently. i.e. either:
import datetime # I want the whole datetime module
datetime.datetime.now() # Must use the fully qualified class name
datetime.date.today() # But I can also use other classes from the module
Or:
from datetime import datetime # I only want the datetime class
datetime.now() # Use the class directly
The name datetime can only mean one thing at a time, so if you do both imports, all that's happening is that the second meaning overwrites the first one.

Reading out json file, checking if keys are existing and using their values

My goal is to check a json file if some keys exist and if true, using its values. My first approach was with standart json lib, and the json file:
{
"M65 PRO RGB": 1,
"K55 RGB": 2
}
I did this:
from os import times
from config import config_from_json
from cuesdk import CueSdk
import json
import sacn
import time
sdk = CueSdk() #Corsair iCue SDK
sdk.connect()
sdk.set_layer_priority(128)
with open('config.json') as f: #Config
conf = json.load(f)
print(conf)
device_count = sdk.get_device_count() #setup Corsair devices config
for device_index in range(device_count):
device_name = sdk.get_device_info(device_index)
exists = device_name in conf
print(exists)
if exists == False:
print(f"Device {device_name} not found")
But with this, the keys are read out as 'M65 PRO RGB' and 'K55 RGGB' instead of just plain M65 PRO RGB and K55 RGB.device_name can be M65 PRO RGB, K55 RGB, H100i PLATINUM or Lighting Node CORE. So ofcourse is exists = False. I dont know anything about string manipulation and tried another aproach with the lib python-config and re-arrenged my json to this:
{
"1": {
"name": "M65 PRO RGB",
"universe": 1
},
"2": {
"name": "K55 RGB",
"universe": 2
},
"3": {
"name": "H100i",
"universe": 3
}
}
Now i wanna iterate trhough the keys 1,2,3 and check if the value of the key name is present and if true, return the value from universe, else iterate from the key 1 to the next.I went with
def check_config_for_device(device_name):
key_count = len(cfg.keys())
for i in range(key_count):
if cfg[i].name == device_name:
print("found")
return cfg[i].universe
sdk = CueSdk() #Corsair iCue SDK
sdk.connect()
sdk.set_layer_priority(128)
#with open('config.json') as f: #Config
# conf = json.load(f)
# print(conf)
device_count = sdk.get_device_count() #setup Corsair devices config
for device_index in range(device_count):
device_name = sdk.get_device_info(device_index)
universe = check_config_for_device(device_name)
setup_receiver(universe, device_index)
Now i get this traceback:
Traceback (most recent call last):
File "c:\Users\tenn0\Documents\Projects\icue2sacn\src\main.py", line 64, in <module>
universe = check_config_for_device(device_name)
File "c:\Users\tenn0\Documents\Projects\icue2sacn\src\main.py", line 38, in check_config_for_device
if cfg[i].name == device_name:
File "C:\Python39\lib\site-packages\config\configuration.py", line 152, in __getitem__
v = self._get_subset(item)
File "C:\Python39\lib\site-packages\config\configuration.py", line 132, in _get_subset
d = {
File "C:\Python39\lib\site-packages\config\configuration.py", line 135, in <dictcomp>
if k.startswith(prefix + ".")
TypeError: unsupported operand type(s) for +: 'int' and 'str'
If i convert i to a string by altering check_config_for_device to
key_count = len(cfg.keys())
for i in range(key_count):
iStr = str(i)
if cfg[iStr].name == device_name:
print("found")
return cfg[i].universe
i get This:
File "c:\Users\tenn0\Documents\Projects\icue2sacn\src\main.py", line 65, in <module>
universe = check_config_for_device(device_name)
File "c:\Users\tenn0\Documents\Projects\icue2sacn\src\main.py", line 39, in check_config_for_device
if cfg[iStr].name == device_name:
File "C:\Python39\lib\site-packages\config\configuration.py", line 155, in __getitem__
raise KeyError(item)
KeyError: '0'
I dont know any further, how to fix this or work around it.

How to troubleshoot and resolve "TypeError: 'NoneType' object is not subscriptable" in python

I have a piece of code that fetches data from the ticketmaster API using a function I've named get_event_info. The first revision of the code worked as desired, subsequently I modified the original function to make use of header based authentication instead of URL based. I also added a few lines to the function which were intended to validate the response status code. After making these changes the code began producing the following TypeError:
Traceback (most recent call last):
File "ticketmaster_only_w_headers.py", line 146, in <module>
for event in ticket_search["_embedded"]["events"].items():
TypeError: 'NoneType' object is not subscriptable
I've read quite a bit about this type of error but I'm still unable to determine why my code is producing it in this instance. I would really appreciate an explanation on why my code is producing this error and what troubleshooting methods I should have used to uncover the source error. I'm fairly comfortable with programming but certainly no expert so the simpler the language used the better.
(Function Definition)
def get_event_info(search):
if search in CACHE_DICTION:
d = CACHE_DICTION[search]
else:
api_url = '{0}events/'.format(api_url_base)
payload = {"keyword": search, "apikey": api_token,
"format": "json", "dmaId": "366", "size": 200, "radius": "2"}
response = requests.get(api_url, headers=headers, params=payload)
if response.status_code == 200:
d = json.loads(response.text)
CACHE_DICTION[search] = d
f = open(CACHE_FNAME, 'w')
f.write(json.dumps(CACHE_DICTION))
f.close()
else:
d = None
return d
(Code snippet that triggers the error)
ticket_search = get_event_info("")
for event in ticket_search["_embedded"]["events"]:
a = event["id"]
b = event["name"]
if "dateTime" in event["dates"]["start"]:
c = event["dates"]["start"]["dateTime"].replace(
"T", " ").replace("Z", "")
else:
c = "NONE"
if "end" in event["dates"] and "dateTime" in event["dates"]["end"]:
j = event["dates"]["end"]["dateTime"].replace(
"T", " ").replace("Z", "")
else:
j = "NONE"
(Code that creates, opens, and writes to the cache used in the above code)
CACHE_FNAME = "ticketmaster_cache.json"
try:
cache_file = open(CACHE_FNAME, "r")
cache_contents = cache_file.read()
CACHE_DICTION = json.loads(cache_contents)
cache_file.close()
except:
CACHE_DICTION = {}
The previous revision of the get_event_info function shown below which does not produce any TypeError:
def get_event_info(search, ticketmaster_key = ticketmaster_key):
if search in CACHE_DICTION:
d = CACHE_DICTION[search]
else:
data = requests.get("https://app.ticketmaster.com/discovery/v2/events",
params = {"keyword": search, "apikey": ticketmaster_key,
"format":"json", "dmaId": "366", "size": 200, "radius": "2"})
print(data.url)
d = json.loads(data.text)
CACHE_DICTION[search] = d
f = open(CACHE_FNAME, 'w')
f.write(json.dumps(CACHE_DICTION))
f.close()
return d
Traceback & Error message I see when I run the latest revision of the code:
Traceback (most recent call last):
File "ticketmaster_only_w_headers.py", line 146, in <module>
for event in ticket_search["_embedded"]["events"]:
TypeError: 'NoneType' object is not subscriptable
Whenever you have a function that can explicitly return None, you should always check the return value first:
def func(a):
if a == 1:
return list(range(10)) # could return a list
else:
return None # or it could return None
a = 10
f = func(a)
f[1]
# raises TypeError: NoneType is not subscriptable
# check for NoneType first
if f is not None:
print(f[1])
# otherwise, kick out different result
else:
print('Got "None" for f!')
# Got "None" for f!
Your ticket_search is returned as None, but because your for loop is trying to do a key-lookup, it's failing, because None doesn't support that operation. Your logic, following from the above, should look like:
if ticket_search is not None:
for event in ticket_search["_embedded"]["events"]:
a = event["id"]
else:
raise TypeError
# or do something else
Well, the interpreter is explicitly telling you that you are trying to evaluate something like a[i], where a is None (instead of the intended type, like a list or a dict). In your case, it is either ticket_search itself, or ticket_search["_embedded"].
In any case, if you can rerun your code at all, putting a print(ticket_search) under ticket_search = get_event_info("") should make everything clear.

TypeError: cannot concatenate 'str' and 'Response' objects

(Ignoring that g.text and p.content return "You're not authorised to view this content" from plug.dj) I get the error
Traceback (most recent call last):
File "plugling.py", line 20, in <module>
r.send('{"a":"auth","p":"'+g+'","t":'+t+'}')
TypeError: cannot concatenate 'str' and 'Response' objects
When running this code:
import time
from websocket import create_connection
import requests
import calendar
slug = 'sfoc'
r = create_connection("wss://godj.plug.dj/socket")
t = calendar.timegm(time.gmtime())
token = 'https://plug.dj/_/auth/token'
join = 'https://plug.dj/_/rooms/join'
pl = {'slug': 'sfoc'}
g = requests.get(token)
print g.text
p = requests.post(join, data=pl)
print p.content
r.send('{"a":"auth","p":"'+g+'","t":'+t+'}')
result = r.recv()
print result
r.close()
It didn't like me using %s for the variables either. I don't know what I'm doing wrong. Thanks in advance and let me know if I haven't explained something clearly.
You are trying to concatenate a Response object:
g = requests.get(token)
# ...
r.send('{"a":"auth","p":"'+g+'","t":'+t+'}')
g is the response object. You wanted to get the text value:
r.send('{"a": "auth", "p": "' + g.text + '", "t":' + t + '}')
You may want to look at the json module if you are trying to send JSON data there:
r.send(json.dumps({'a': 'auth', 'p': g.text, 't': t}))

AttributeError: 'unicode' object has no attribute 'success'

I have a simple script using requests to validate a list of emails. Relevant code:
def ___process_email(email, output_file=None):
profile = request(email)
if profile and profile.success != 'nothing_useful':
logger.info('Found match for {0}'.format(email))
print(profile)
if output_file:
output_file.write(str(profile) + '\n')
else:
print("No information found\n")
This ran through 5 loops successfully then threw:
Traceback (most recent call last):
File "app.py", line 147, in <module> main()
File "app.py", line 141, in main ___process_email(arg, output)
File "app.py", line 107, in ___process_email if profile and profile.success != 'nothing_useful':
AttributeError: 'unicode' object has no attribute 'success'
Here's the model:
class Profile(object):
def __init__(self, person):
if person:
self.name = person.get('name')
self.jobinfo = [
(occupation.get('job_title'), occupation.get('company'))
for occupation in person.get('occupations', [])
]
self.memberships = [
(membership.get('site_name'), membership.get('profile_url'))
for membership in person.get('memberships', [])
]
self.success = person.get('success')
def __str__(self):
return dedent("""
Name: {0}
{1}
{2}
""").format(
self.name,
"\n".join(
"{0} {1}".format(title, company)
for title, company in self.jobinfo),
"\n".join(
"\t{0} {1}".format(site_name, url)
for site_name, url in self.memberships)
)
Request:
import requests
def request(email):
status_url = STATUS_URL.format(email)
response = requests.get(status_url).json()
session_token = response.get('session_token')
# fail gracefully if there is an error
if 'error' in response:
return response['error']
elif response['status'] == 200 and session_token:
logger.debug('Session token: {0}'.format(session_token))
url = URL.format(email)
headers = {'X-Session-Token': session_token}
response = requests.get(url, headers=headers).json()
if response.get('success') != 'nothing_useful':
return Profile(response.get('contact'))
return {}
Anyone see why my strings are unicode? thanks
If there is an error in the response, you return the error string:
if 'error' in response:
return response['error']
That's your unicode value there. Note that the same function returns either the 'error' value, a new Profile() instance, or an empty dictionary. You may want to make this more consistent, return only Profile() istances and None instead.
Instead of the error string, raise an exception and handle the exception in your ___process_email method:
class EmailValidationError(Exception):
pass
and in your request() function:
if 'error' in response:
raise EmailValidationError(response['error'])
then handle this in __process_email() with something like:
try:
profile = request(email)
if profile and profile.success != 'nothing_useful':
logger.info('Found match for {0}'.format(email))
print(profile)
if output_file:
output_file.write(str(profile) + '\n')
else:
print("No information found\n")
except EmailValidationError:
# Do something here

Categories

Resources