Object not callable in python class in flask application - python

This is my first flask application and i tried my best to get it running. Nevertheless i stuck into one error.
I tried to create a python flask app but stuck into an error.
here is my code
flask.py
from test_displayclass import Bartender
class MyFlask:
bartender = Bartender()
def __init__(self):
#self.bartender = Bartender()
self.bartender.test()
from flask import Flask
app = Flask(__name__)
my_flask = MyFlask()
#app.route("/Test")
def Test():
return my_flask.test.APIfunction
if __name__ == "__main__":
app.run(debug=True,port=9999)
test_displayclass.py
import adafruit_ssd1306
import busio
from board import SCL, SDA
from PIL import Image, ImageDraw, ImageFont
class Display():
def __init__(self):
i2c = busio.I2C(SCL, SDA)
self.oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
self.oled.fill(0)
self.oled.show()
def drawImage(self, image):
self.oled(image)
self.oled.show()
class Bartender():
def __init__(self):
self.oled = Display()
def test(self):
image = Image.new("1", (20, 20))
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 25)
self.len = len("e")
draw.text(
(0, 40 - 2 // 2),
"e",
font=font,
fill=255,
)
Error is:
Traceback (most recent call last):
File "/home/pi/Smart-Bartender/bartender_flask_new_test.py", line 13, in <module>
my_flask = MyFlask()
File "/home/pi/Smart-Bartender/bartender_flask_new_test.py", line 8, in __init__
self.bartender.test()
File "/home/pi/Smart-Bartender/test_displayclass.py", line 61, in test
self.oled.drawImage(image)
File "/home/pi/Smart-Bartender/test_displayclass.py", line 33, in drawImage
self.oled(image)
TypeError: 'SSD1306_I2C' object is not callable
Can you advice me how to do it the correct waY?

Need of taken the function self.oled.image(image)

Related

Trying to import module

When I am trying to import a method from another class, I am getting the following error.
Traceback (most recent call last):
File "d:\Python\Report-monitoring-system\com\acc\report\main\Main.py", line 7, in <module>
from com.acc.report.report.review.Review import *
ModuleNotFoundError: No module named 'com'
Here's my code below. I want to access methods from Review class which is under com.acc.report.report.review.Review.py and from the class from where I am importing is under com.acc.report.main.Main.py
from com.acc.report.report.review.Review import *
class Main:
program = Tk()
def selectReports(self):
messagebox.showinfo("EDP", "All reports")
def showReports(self):
messagebox.showinfo("EDP", "Select reports")
def Show_Page(self):
# program = Tk()
self.program.title("My Tkinter app")
style = ttk.Style()
style.map("C.TButton",
foreground=[('pressed', 'red'), ('active', 'blue')],
background=[('pressed', '!disabled', 'black'), ('active', 'white')]
)
self.program.geometry("626x431")
reviewObj = Review()
monitor = ttk.Button(name="",text="Monitor",command=reviewObj.reviewReport,style="C.TButton")
monitor.pack(pady=100)
review = ttk.Button(name="",text="Review",command=self.selectReports,style="C.TButton")
review.pack(pady=0)
self.program.mainloop()
# Main method
if __name__ == "__main__":
objectMain = Main()
objectMain.Show_Page()

What should I do to import those modules correctly?

I want to run this code in jupyter notebook but it gives me that error :
ImportError: cannot import name 'document' from 'browser' (C:\Users\pc\anaconda3\lib\site-packages\browser_init_.py)
What should I do ?
from browser import document, window
def sketch(p):
def setup():
p.createCanvas(500, 500)
p.stroke(p.color("blue"))
p.line(10, 10, 100, 100)
def draw():
pass
p.setup = setup
p.draw = draw
myP5 = window.p5.new(sketch)

pyqrcode.create does not exist

I am trying to merge a Qr Code onto a pdf. When I split the code into two separate scripts it works fine. I am new to phython any help is appreciated. I am running this on RHEL 7.4 in Phyton 2.7
Yes I know it's old but it is a 3rd party server and I cannot upgrade it.
[user#myserver scripts]$ python pdf_test3.py
Traceback (most recent call last):
File "pdf_test3.py", line 28, in <module>
qcode = pyqrcode("http://www.weather.com","/cfg/test.png")
File "pdf_test3.py", line 8, in __init__
qrCode = self.create(url)
AttributeError: pyqrcode instance has no attribute 'create'
from fpdf import FPDF
from pyqrcode import QRCode
import png
import sys
class pyqrcode(QRCode):
def __init__(self, url,fileOutputDir):
qrCode = self.create(url)
# create qr code and save it as a svg image
qrCode.png(fileOutputDir, scale=1)
class PDF(FPDF):
def __init__(self,imageFileName):
# file name, left,top,heght,width
self.image(imageFileName, 200,1,20,20)
self.cell(30, 10, 'Title', 1, 0, 'C')
# Page footer
def footer(self):
# Position at 1.5 cm from bottom
self.set_y(-15)
# Arial italic 8
self.set_font('Arial', 'I', 8)
# Page number
self.cell(0, 10, 'Page ' + str(self.page_no()) + '/{nb}', 0, 0, 'C')
# Instantiation of inherited class
qcode = pyqrcode("http://www.weather.com","/cfg/test.png")
pdf = PDF()
pdf.alias_nb_pages()
pdf.add_page()
pdf.set_font('Times', '', 12)
for i in range(1, 5):
pdf.cell(0, 10, 'Hello World.' + str(i), 0, 1)
pdf.output('test.pdf', 'F')
Your error is saying that your own pyqrcode instance has no create function, which it does not. Also, best not to name a class with the same name as a module
You can fix that by importing the create function
from fpdf import FPDF
from pyqrcode import QRCode
from pyqrcode import create as create_qrcode
import png
import sys
class PyQRcode(QRCode):
def __init__(self, url,fileOutputDir):
qrCode = create_qrcode(url)

PySDL2 issue with SDL_Surface / LP_SDL_Surface

Im running win7 with python 3.3 and PySDL2 0.5. When creating surfaces (no matter what method) i get an LP_SDL_Surface instead of a SDL_Surface. The LP_SDL_Surface lacks any of the methods and attribute you would expect it to have. Here is the issue using example code from the documentation:
import os
os.environ["PYSDL2_DLL_PATH"] = os.path.dirname(os.path.abspath(__file__))
import sys
import ctypes
from sdl2 import *
def main():
SDL_Init(SDL_INIT_VIDEO)
window = SDL_CreateWindow(b"Hello World",
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
592, 460, SDL_WINDOW_SHOWN)
windowsurface = SDL_GetWindowSurface(window)
image = SDL_LoadBMP(b"exampleimage.bmp")
SDL_BlitSurface(image, None, windowsurface, None)
print(image.h)
SDL_UpdateWindowSurface(window)
SDL_FreeSurface(image)
running = True
event = SDL_Event()
while running:
while SDL_PollEvent(ctypes.byref(event)) != 0:
if event.type == SDL_QUIT:
running = False
break
SDL_DestroyWindow(window)
SDL_Quit()
return 0
if __name__ == "__main__":
sys.exit(main())
and the traceback is:
Traceback (most recent call last):
File "C:/.../test.py", line 35, in <module>
sys.exit(main())
File "C:/.../test.py", line 17, in main
print(image.h)
AttributeError: 'LP_SDL_Surface' object has no attribute 'h'
A google search for "LP_SDL_Surface" brings 0 (!) results.
If you work with the lower level SDL methods (e.g. sdl2.SDL_LoadBMP) you will have to deal with ctypes conversions, referencing(byref) and dereferencing of pointers (.contents, .value).
So for the specific question, as you've already commented, using print(image.contents.h) would be enough.
There are some higher level classes and methods provided by pysdl2 (sdl2.ext), however, that could do most of those conversions for you, if desired. The code below achieves the same goal without having to touch ctypes:
import os
os.environ["PYSDL2_DLL_PATH"] = os.path.dirname(os.path.abspath(__file__))
import sys
import sdl2
import sdl2.ext
def main():
sdl2.ext.init()
window = sdl2.ext.Window(
title="Hello World!", size=(592, 460), flags=sdl2.SDL_WINDOW_SHOWN,
position=(sdl2.SDL_WINDOWPOS_CENTERED, sdl2.SDL_WINDOWPOS_CENTERED))
window.show()
renderer = sdl2.ext.Renderer(window)
factory = sdl2.ext.SpriteFactory(sdl2.ext.TEXTURE, renderer=renderer)
spriterenderer = factory.create_sprite_render_system(window)
image = factory.from_image("exampleimage.bmp")
print(image.size[1]) # image.size = (w, h)
running = True
while running:
for event in sdl2.ext.get_events():
if event.type == sdl2.SDL_QUIT:
running = False
break
spriterenderer.render(image)
sdl2.ext.quit()
return 0
if __name__ == '__main__':
sys.exit(main())
It also makes use of texture rendering, using hardware acceleration, instead of surface blitting (software based).
Finally, using the higher level sdl2.ext you could also instantiate classes (instead of having to write a whole new sprite class yourself) like sdl2.ext.sprite.TextureSprite, and implement a h property:
class TextureSprite(sdl2.ext.TextureSprite):
#property
def h(self):
"""The height of the TextureSprite."""
return self.size[1]
#property
def w(self):
"""The width of the TextureSprite."""
return self.size[0]

Cocos2d: AttributeError: 'Director' object has no attribute '_window_virtual_width'

We are using the cocos2d framework to create a game. We're completely new to this framework, so we cannot get the director object to work as we are expecting. Here is our code skeleton:
from cocos.director import director
from cocos.layer import base_layers
import sys
import math
import os
import pyglet
import cocos
world_width = 1000
world_height = 1000
class NetworkMap(cocos.layer.ScrollableLayer):
def __init__(self, world_width, world_height):
self.world_width = world_width
self.world_height = world_height
super(NetworkMap, self).__init__()
bg = ColorLayer(170,170,0,255,width=500,height=500)
self.px_width = world_width
self.px_height = world_height
self.add(bg,z=0)
class TestScene(cocos.scene.Scene):
def __init__(self):
super(TestScene,self).__init__()
def on_enter():
director.push_handlers(self.on_cocos_resize)
super(TestScene, self).on_enter()
def on_cocos_resize(self, usable_width, usable_height):
self.f_refresh_marks()
def main():
scene = TestScene()
director.init(world_width, world_height, do_not_scale=True)
world_map = NetworkMap(world_width, world_height)
scroller = cocos.layer.ScrollingManager()
scroller.add(world_map)
scene.add(scroller)
director.run(scene)
So for some reason the director doesn't have all the attributes we want.
Our stack trace is:
Traceback (most recent call last):
File "map.py", line 49, in <module>
main()
File "map.py", line 39, in main
scene = TestScene()
File "map.py", line 29, in __init__
super(TestScene,self).__init__()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/scene.py", line 95, in __init__
super(Scene,self).__init__()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/cocosnode.py", line 114, in __init__
self.camera = Camera()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/camera.py", line 56, in __init__
self.restore()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/camera.py", line 76, in restore
width, height = director.get_window_size()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/director.py", line 522, in get_window_size
return ( self._window_virtual_width, self._window_virtual_height)
AttributeError: 'Director' object has no attribute '_window_virtual_width'
You need to initialise the director before you instantiate your first scene. The director is the global object that initialises your screen, sets up the Cocos2D framework, etc.
I found a few other errors:
You need to change ColorLayer to be fully qualified, e.g. cocos.layer.ColorLayer.
on_enter needs to have self as the first argument.
You need to define f_refresh_marks in your TestScene class.
Here's a working copy of the code. (Working, in the sense that it does not throw errors, not that it does any sort of scrolling.)
from cocos.director import director
from cocos.layer import base_layers
import sys
import math
import os
import pyglet
import cocos
world_width = 1000
world_height = 1000
class NetworkMap(cocos.layer.ScrollableLayer):
def __init__(self, world_width, world_height):
self.world_width = world_width
self.world_height = world_height
super(NetworkMap, self).__init__()
bg = cocos.layer.ColorLayer(170,170,0,255,width=500,height=500)
self.px_width = world_width
self.px_height = world_height
self.add(bg,z=0)
class TestScene(cocos.scene.Scene):
def __init__(self):
super(TestScene,self).__init__()
def on_enter(self):
director.push_handlers(self.on_cocos_resize)
super(TestScene, self).on_enter()
def on_cocos_resize(self, usable_width, usable_height):
self.f_refresh_marks()
def f_refresh_marks(self):
pass
def main():
director.init(world_width, world_height, do_not_scale=True)
scene = TestScene()
world_map = NetworkMap(world_width, world_height)
scroller = cocos.layer.ScrollingManager()
scroller.add(world_map)
scene.add(scroller)
director.run(scene)
if __name__ == '__main__': main()
I had the same issue (with a very similar stack trace) and it was because I was trying to create a layer before calling director.init(). Moving director.init() to earlier in the code fixed it for me.

Categories