EDIT: I wonder if you think the issue might be that I'm trying to store an entire dictionary row returned from database in a session variable?
Here's the error (full error printout is at bottom of this post):
TypeError: Object of type User is not JSON serializable
FYI: I'm not using JSON anywhere in my code.
Here's the relevant parts of my code (main.py):
class User():
def __init__(self, t_id_user=None, t_email=None):
self.t_id_user = t_id_user
self.t_email = t_email
def create_or_update(self, t_create_or_edit="Edit"):
#How necessary are the "=None" below?
#self.t_id_user = userCreate(self, t_id_user=None, t_email=None):
#How necessary are the "=None" above?
if t_create_or_edit == "Create":
self.t_id_user = userCreate(
self.t_email
)
else:
self.t_id_user = userUpdate(
self.t_id_user_edit,
self.t_email
)
def get_from_id(self, t_id_user):
# logic to retrieve your user's data from your database of choice
myData = usersGet(
t_id_user="0",
t_email=""
)
self.t_id_user = myData["t_id_user"]
self.t_email = myData["t_email"]
return self
def userClearSession(t_which="user_current"):
logging.debug("Start of userClearSession()")
t_id_user = "0"
t_email = ""
user_instance = User(t_id_user, t_email)
if t_which == "user_current":
session["user_current"] = user_instance
else:
session["user_edit"] = user_instance
return
#app.route('/', methods=['GET', 'POST'])
#app.route('/userRegister', methods=['GET', 'POST'])
def index(t_title="Login or Register", t_message=""):
if "user_current" not in session:
userClearSession(t_which="user_current")
return render_template(
"userRegister.html",
t_message=t_message,
t_js="userRegister.js",
t_title=t_title
)
def userCreate(t_which="current"):
id_user = 0
db_cursor = data_cursor()
q = ""
q += "INSERT INTO tbl_users "
q += " ( "
q += " i_security_level"
q += ", t_email"
q += " ) "
q += " VALUES "
q += " ( "
q += " %(t_security_level)s"
q += ", '%(t_email)s'"
q += " ) "
try:
if t_which == "current":
user_instance = session["user_current"]
else:
user_instance = session["user_edit"]
vars = {
't_security_level': int(session["user_instance"].t_security_level),
't_email': AsIs(session["user_instance"].t_email)
}
db_cursor.execute(q,vars)
except Exception as e:
t_message = "Error"
else:
id_found = userIsInDB(session["user_instance"].t_email)
if id_found >= 1:
t_id_user = id_found
if t_which == "current":
session["user_current"].t_id_user = t_id_user
else:
session["user_edit"].t_id_user = t_id_user
t_message = "User Created"
db_cursor.close()
db_conn.close()
The full error message:
I'm having a hard time getting any meaning out of this error message and need help. It doesn't appear to point to any parts of main.py, though I know the error is somewhere in there and I'm pretty sure I narrowed it down to the code you see above:
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python\Python38\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 1953, in full_dispatch_request
return self.finalize_request(rv)
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 1970, in finalize_request
response = self.process_response(response)
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 2269, in process_response
self.session_interface.save_session(self, ctx.session, response)
File "C:\Python\Python38\Lib\site-packages\flask\sessions.py", line 378, in save_session
val = self.get_signing_serializer(app).dumps(dict(session))
File "C:\Python\Python38\Lib\site-packages\itsdangerous\serializer.py", line 166, in dumps
payload = want_bytes(self.dump_payload(obj))
File "C:\Python\Python38\Lib\site-packages\itsdangerous\url_safe.py", line 42, in dump_payload
json = super(URLSafeSerializerMixin, self).dump_payload(obj)
File "C:\Python\Python38\Lib\site-packages\itsdangerous\serializer.py", line 133, in dump_payload
return want_bytes(self.serializer.dumps(obj, **self.serializer_kwargs))
File "C:\Python\Python38\Lib\site-packages\flask\json\tag.py", line 305, in dumps
return dumps(self.tag(value), separators=(",", ":"))
File "C:\Python\Python38\Lib\site-packages\flask\json\__init__.py", line 211, in dumps
rv = _json.dumps(obj, **kwargs)
File "C:\Python\Python38\Lib\json\__init__.py", line 234, in dumps
return cls(
File "C:\Python\Python38\Lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Python\Python38\Lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Python\Python38\Lib\site-packages\flask\json\__init__.py", line 100, in default
return _json.JSONEncoder.default(self, o)
File "C:\Python\Python38\Lib\json\encoder.py", line 179, in default
Open an interactive python shell in this frameraise TypeError(f'Object of type {o.__class__.__name__}
Related
I'm new to coding in general (little experience from Javascript before) and python to be specific. Tried out Leetcode, but now am stuck as I get an error. I compiled the script first in VS Code, and there it runs fine. But in Leetcode i get the following error:
`
TypeError: Parameters to generic types must be types. Got 0.
raise TypeError(f"{msg} Got {arg!r:.100}.")
Line 175 in _type_check (/usr/lib/python3.10/typing.py)
params = tuple(_type_check(p, msg) for p in params)
Line 1126 in <genexpr> (/usr/lib/python3.10/typing.py)
params = tuple(_type_check(p, msg) for p in params)
Line 1126 in __getitem__ (/usr/lib/python3.10/typing.py)
return func(*args, **kwds)
Line 311 in inner (/usr/lib/python3.10/typing.py)
shortestWord = min(filter(None, List), key=len)
Line 4 in longestCommonPrefix (Solution.py)
ret = Solution().longestCommonPrefix(param_1)
Line 41 in _driver (Solution.py)
_driver()
Line 52 in <module> (Solution.py)
Also line 4 is highlighted in red and with exclamation mark:
shortestWord = min(filter(None, List), key=len)
This is my code in Leetcode. It differs from the one I use in VS Code only in that I don't have the class Solution and def includes only (List) as a parameter:
`class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
testCharacter = []
shortestWord = min(filter(None, List), key=len)
length = len(shortestWord)
result = ""
for i in range(0,length):
testCharacter.append(i)
testCharacter[i] = ""
for words in List:
counter = 0
for index, char in enumerate(words):
testCharacter[index] += char
counter += 1
if counter == length:
break
for i in range(0,length):
if testCharacter[i] == testCharacter[i][0]*len(List):
result += testCharacter[i][0]
else:
break
return result
The task at hand is to return the longest common prefix for a list of strings. For example, ["bull", "bully", "but"] should return "bu".
I am trying to execute the codes from this link
https://zulko.github.io/blog/2014/06/21/some-more-videogreping-with-python/
import re # module for regular expressions
def convert_time(timestring):
""" Converts a string into seconds """
nums = map(float, re.findall(r'\d+', timestring))
return 3600*nums[0] + 60*nums[1] + nums[2] + nums[3]/1000
with open("Identity_2003.srt") as f:
lines = f.readlines()
times_texts = []
current_times , current_text = None, ""
for line in lines:
times = re.findall("[0-9]*:[0-9]*:[0-9]*,[0-9]*", line)
if times != []:
current_times = map(convert_time, times)
elif line == '\n':
times_texts.append((current_times, current_text))
current_times, current_text = None, ""
elif current_times is not None:
current_text = current_text + line.replace("\n"," ")
print (times_texts)
from collections import Counter
whole_text = " ".join([text for (time, text) in times_texts])
all_words = re.findall("\w+", whole_text)
counter = Counter([w.lower() for w in all_words if len(w)>5])
print (counter.most_common(10))
cuts = [times for (times,text) in times_texts
if (re.findall("please",text) != [])]
from moviepy.editor import VideoFileClip, concatenate
video = VideoFileClip("Identity_2003.mp4")
def assemble_cuts(cuts, outputfile):
""" Concatenate cuts and generate a video file. """
final = concatenate([video.subclip(start, end)
for (start,end) in cuts])
final.to_videofile(outputfile)
assemble_cuts(cuts, "please.mp4")
But the assemble_cuts function is not working . I am using python3.x
it is giving me an error
Traceback (most recent call last):
File "<ipython-input-64-939ee3d73a4a>", line 47, in <module>
assemble_cuts(cuts, "please.mp4")
File "<ipython-input-64-939ee3d73a4a>", line 44, in assemble_cuts
for (start,end) in cuts])
File "<ipython-input-64-939ee3d73a4a>", line 43, in <listcomp>
final = concatenate([video.subclip(start, end)
File "<ipython-input-64-939ee3d73a4a>", line 6, in convert_time
return 3600*nums[0] + 60*nums[1] + nums[2] + nums[3]/1000
TypeError: 'map' object is not subscriptable
Could you help me to solve this problem?
Fixed it.
def convert_time(timestring):
""" Converts a string into seconds """
nums = list(map(float, re.findall(r'\d+', timestring)))
return 3600*nums[0] + 60*nums[1] + nums[2] + nums[3]/1000
I declared a global variable in python and still i'm facing error saying that variable is not defined. Can someone please please help me.
def _pick_server (self, key, inport):
global scount1
global scount2
global scount3
server1wt = 4
server2wt = 1
server3wt = 2
liveservers = sorted(self.live_servers.keys())
for i in liveservers:
print(i)
if (scount1 < server1wt):
scount1 += scount1
print(scount1)
print (liveservers[0])
return liveservers[0]
elif (scount2 < server3wt):
scount2 += scount2
print (liveservers[1])
return liveservers[1]
elif (scount3 < server3wt):
scount3 += scount3
print (liveservers[2])
return liverservers[2]
else:
scount1 = 1
scount2 = 0
scount3 = 0
liveservers[0]
The error i'm getting is as below:
Traceback (most recent call last):
File "/home/mininet/pox/pox/lib/revent/revent.py", line 231, in
raiseEventNoErrors
return self.raiseEvent(event, *args, **kw)
File "/home/mininet/pox/pox/lib/revent/revent.py", line 278, in raiseEvent
rv = event._invoke(handler, *args, **kw)
File "/home/mininet/pox/pox/lib/revent/revent.py", line 156, in _invoke
return handler(self, *args, **kw)
File "/home/mininet/pox/ext/ents_loadbalancer.py", line 307, in
_handle_PacketIn
server = self._pick_server(key, inport)
File "/home/mininet/pox/ext/ents_loadbalancer.py", line 203, in _pick_server
if (scount1 < server1wt):
NameError: global name 'scount1' is not defined
your using scount1 before defining it
how can you test its value when it is unknown?
Solution
scount1 = 1
before
if (scount1 < server1wt)
I recently got a raspberry pi and a book to go along with it(Raspberry Pi Cookbook). One of the projects is controlling the GPIO pins on the RPi via a webpage. When I first ran the code after typing it out, I received a bunch of errors so, I tried running the code listed on the books github page:
from bottle import route, run
import RPi.GPIO as GPIO
host = '192.168.1.8'
GPIO.setmode(GPIO.BCM)
led_pins = [18, 23, 24]
led_states = [0, 0, 0]
switch_pin = 25
GPIO.setup(led_pins[0], GPIO.OUT)
GPIO.setup(led_pins[1], GPIO.OUT)
GPIO.setup(led_pins[2], GPIO.OUT)
GPIO.setup(switch_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def switch_status():
state = GPIO.input(switch_pin)
if state:
return 'Up'
else:
return 'Down'
def html_for_led(led):
l = str(led)
result = " <input type='button' onClick='changed(" + l + ")' value='LED " + l + "'/>"
return result
def update_leds():
for i, value in enumerate(led_states):
GPIO.output(led_pins[i], value)
#route('/')
#route('/<led>')
def index(led="n"):
print(led)
if led != "n":
led_num = int(led)
led_states[led_num] = not led_states[led_num]
update_leds()
response = "<script>"
response += "function changed(led)"
response += "{"
response += " window.location.href='/' + led"
response += "}"
response += "</script>"
response += '<h1>GPIO Control</h1>'
response += '<h2>Button=' + switch_status() + '</h2>'
response += '<h2>LEDs</h2>'
response += html_for_led(0)
response += html_for_led(1)
response += html_for_led(2)
return response
run(host=host, port=80)
When I run the code(sudo python web_control.py) I get a invalid literal for int() with base 10: 'favicon.ico' error. Here is the traceback:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/bottle.py", line 744, in _handle
return route.call(**args)
File "/usr/lib/python2.7/dist-packages/bottle.py", line 1480, in wrapper
rv = callback(*a, **ka)
File "web_control.py", line 42, in index
response += " window.location.href='/' + led"
UnboundLocalError: local variable 'response' referenced before assignment
192.168.0.108 - - [29/Dec/2014 21:31:46] "GET / HTTP/1.1" 500 740
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/bottle.py", line 744, in _handle
return route.call(**args)
File "/usr/lib/python2.7/dist-packages/bottle.py", line 1480, in wrapper
rv = callback(*a, **ka)
File "web_control.py", line 36, in index
led_num = int(led)ValueError: invalid literal for int() with base 10: 'favicon.ico'
Any idea what is going on here? Any help is greatly appreciated.
what does your
print led
show ?
they say that led is not an int so the error could be from there
I'm beginner in Python. I'm using multi-processing to batch program such as xcopy from host PC to remote PCs. I got a permissionerror such as *DUPLICATE_SAME_ACCESS*. any help would be very helpful.
IDE Env. :
Kepler
Python-3.x
error message
Traceback (most recent call last):
File "C:\Users\Administrator\.eclipse\org.eclipse.platform_4.3.0_1709980481_win32_win32_x86_64\plugins\org.python.pydev_2.8.2.2013090511\pysrc\pydevd.py", line 1446, in <module>
debugger.run(setup['file'], None, None)
File "C:\Users\Administrator\.eclipse\org.eclipse.platform_4.3.0_1709980481_win32_win32_x86_64\plugins\org.python.pydev_2.8.2.2013090511\pysrc\pydevd.py", line 1092, in run
pydev_imports.execfile(file, globals, locals) #execute the script
File "C:\Users\Administrator\.eclipse\org.eclipse.platform_4.3.0_1709980481_win32_win32_x86_64\plugins\org.python.pydev_2.8.2.2013090511\pysrc\_pydev_execfile.py", line 38, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc) #execute the script
File "C:\Users\Administrator\Documents\Kepler\workspace\kr.caleb.python.first\src\fileCopy\xCopyPython.py", line 92, in <module>
dist_files(server_list, 'C:\\Users\\Public\\jvision')
File "C:\Users\Administrator\Documents\Kepler\workspace\kr.caleb.python.first\src\fileCopy\xCopyPython.py", line 79, in dist_files
Process(target=multi_distribute_file,args=(lock, server, dirpath, filename, path)).start()
File "C:\Python33\lib\multiprocessing\process.py", line 111, in start
self._popen = Popen(self)
File "C:\Python33\lib\multiprocessing\forking.py", line 248, in __init__
dump(process_obj, to_child, HIGHEST_PROTOCOL)
File "C:\Python33\lib\multiprocessing\forking.py", line 166, in dump
ForkingPickler(file, protocol).dump(obj)
File "C:\Python33\lib\multiprocessing\synchronize.py", line 70, in __getstate__
return (Popen.duplicate_for_child(sl.handle), sl.kind, sl.maxvalue)
File "C:\Python33\lib\multiprocessing\forking.py", line 258, in duplicate_for_child
return duplicate(handle, Popen._tls.process_handle)
File "C:\Python33\lib\multiprocessing\forking.py", line 201, in duplicate
0, inheritable, _winapi.DUPLICATE_SAME_ACCESS
PermissionError: [WinError 5] Access is denied
Full code (xCopyPython.py) :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# based on Carnival http://ask.python.kr/users/6970/carnival/
import os, sys, csv, re
from multiprocessing import Process, Lock
class Server:
def __init__(self, addr, path):
self.addr = addr
self.path = path
def multi_distribute_file(lo, server, dirpath, filename, subdir):
lo.acquire()
pathname = os.path.join(dirpath, filename)
print("Read from {}".format(pathname))
with open(pathname, 'rb') as inFile:
buffer = inFile.read()
l = re.findall(r"[\w']+",subdir)
m = re.findall(r"[\w']+",dirpath)
cnt_l = len(l)
cnt_m = len(m)
remotepath = "//%s/%s" % (server.addr, server.path)
if(cnt_m > cnt_l):
for j in range(cnt_m - cnt_l):
remotepath += "/%s" % (m[cnt_l + j])
remotepath += "/%s" % (filename)
print ("Write to {}".format(remotepath))
with open(remotepath, 'wb') as outFile:
outFile.write(buffer)
lo.release()
def make_dir(server_list, subdir, dirpath):
for server in server_list:
l = re.findall(r"[\w']+",subdir)
m = re.findall(r"[\w']+",dirpath)
cnt_l = len(l)
cnt_m = len(m)
path = "//%s/%s" % (server.addr, server.path)
if(cnt_m > cnt_l):
for j in range(cnt_m - cnt_l):
path += "/%s" % (m[cnt_l + j])
d = os.path.dirname(path)
if not os.path.exists(d):
os.makedirs(d)
print ("Make dir {}".format(d))
else:
print ("dir {} already exists.".format(d))
if not os.path.exists(path):
os.makedirs(path)
print ("Make dir {}".format(path))
else:
print ("dir {} already exists.".format(path))
def dist_files(server_list, subdir):
for dirpath, dirnames, filenames in os.walk(subdir):
make_dir(server_list, subdir, dirpath)
for filename in filenames:
for server in server_list:
lock = Lock()
Process(target=multi_distribute_file,args=(lock, server, dirpath, filename, subdir)).start()
def get_server_list(filename):
mydictionary = []
csvFile = csv.reader(open(filename, "r"))
for row in csvFile:
mydictionary.append(Server(row[0], row[1]))
print("{}, {}".format(row[0], row[1]))
return mydictionary
if __name__ == '__main__':
server_list = get_server_list('client_list.csv')
dist_files(server_list, 'C:\\Users\\Public\\Test')
client.csv :
192.168.10.100, Test
192.168.10.101, Test
192.168.10.102, Test
I'm going to modify multi_distribute_file method to open/read file.
origin :
def multi_distribute_file(lo, server, dirpath, filename, subdir):
lo.acquire()
pathname = os.path.join(dirpath, filename)
print("Read from {}".format(pathname))
with open(pathname, 'rb') as inFile:
buffer = inFile.read()
l = re.findall(r"[\w']+",subdir)
m = re.findall(r"[\w']+",dirpath)
cnt_l = len(l)
cnt_m = len(m)
remotepath = "//%s/%s" % (server.addr, server.path)
if(cnt_m > cnt_l):
for j in range(cnt_m - cnt_l):
remotepath += "/%s" % (m[cnt_l + j])
remotepath += "/%s" % (filename)
print ("Write to {}".format(remotepath))
with open(remotepath, 'wb') as outFile:
outFile.write(buffer)
lo.release()
modify : buffer arg is added.
def multi_distribute_file(server, dirpath, filename, subdir, buffer):
#lo.acquire()
#pathname = os.path.join(dirpath, filename)
#print("Read from {}".format(pathname))
#with open(pathname, 'rb') as inFile:
# buffer = inFile.read()
l = re.findall(r"[\w']+",subdir)
m = re.findall(r"[\w']+",dirpath)
cnt_l = len(l)
cnt_m = len(m)
remotepath = "//%s/%s" % (server.addr, server.path)
if(cnt_m > cnt_l):
for j in range(cnt_m - cnt_l):
remotepath += "/%s" % (m[cnt_l + j])
remotepath += "/%s" % (filename)
print ("Write to {}".format(remotepath))
with open(remotepath, 'wb') as outFile:
outFile.write(buffer)
#lo.release()