python – Erro AttributeError: ‘Aluno’ object has no attribute ‘lista_estudante’

Nesse código preciso criar uma lista com os dados do DB que são lidos no Python pela classe Aluno

Trecho do código que necessita imprimir a lista que foi inserida no DB com um INSERT

class Aluno(object):

    def update_aluno(self, nome_aluno, id_curso, data_nascimento_aluno, email_aluno, telefone_aluno):
    """ atualiza informações do aluno baseado no id_aluno """
    sql = """ UPDATE Aluno
                SET nome_aluno = %s
                SET id_curso = %s
                SET data_nascimento_aluno = %s
                SET email_aluno = %s
                SET telefone_aluno = %s
                WHERE id_curso = %s"""
    conn = None
    updated_rows = 0
    
    try:
        # read database configuration
        params = config(filename="/database.ini")
        # connect to the PostgreSQL database
        conn = psycopg2.connect(**params)
        # create a new cursor
        cur = conn.cursor()
        # execute the UPDATE  statement
        cur.execute(sql, (nome_aluno, id_curso, data_nascimento_aluno, email_aluno, telefone_aluno))
        # get the number of updated rows
        updated_rows = cur.rowcount
        # Commit the changes to the database
        conn.commit()
        # Close communication with the PostgreSQL database
        cur.close()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()

    return updated_rows

Trecho do código que executa e solicita informações ao usuário:

  elif lista_selecionada == 2:
    print("Confira a lista de alunos da Escola: n")
    estudante = Aluno()
    estudante.lista_estudante()

    id_estudante = int(input("Digite a matrícula do aluno que deseja atualizar: n"))
    nome_aluno = input("Digite o novo nome do aluno: n")
    is_curso = input("Digite o curso 3 para Fundamental e 4 para Fundamental 2: n")
    data_nascimento_aluno = input("Digite a nova data de nascimento do aluno: n")
    email_aluno = input("Digite o novo e-mail do aluno: n")
    telefone_aluno = input("Digite o novo telefone do aluno: n")
    
    estudante.update_aluno(matricula_aluno = id_estudante, id_curso=is_curso, nome_aluno=nome_aluno, data_nascimento_aluno = data_nascimento_aluno, email_aluno = email_aluno, telefone_aluno=telefone_aluno)

Entendi que preciso fazer um referência a estudante.lista_estudante() na classe, só que não tenho ideia de como, podem me ajudar?

javascript – Django: AttributeError at /update_item/ ‘WSGIRequest’ object has no attribute ‘data’

The following error is given to me when i access my localhost:8000/update_item/: “AttributeError at /update_item/ ‘WSGIRequest’ object has no attribute ‘data'”

views.py

def updateItem(request):
    data = json.loads(request.data)
    productId = data('productId')
    action = data('action')
    print('Action:', action)
    print('productId:', productId)

    customer = request.user.customer
    product = Product.objects.get(id=productId)
    order, created = Order.objects.get_or_create(customer=customer, complete=False)
    orderItem, created = OrderItem.objects.get_or_create(order = order, product = product)

carrito.js:

function updateUserOrder(productId, action){
    console.log('Usuario logeado y enviando data...')

    var url = '/update_item/'

    fetch (url, {
        method: 'POST',
        headers:{
            'Content-Type':'application/json',
            'X-CSRFToken': csrftoken,
        },
        body:JSON.stringify({'productId' :productId, 'action' :action})
    })

    .then((response) =>{
        return response.json()
    })

    .then((data) =>{
        console.log('data:', data)
        location.reload()
    })

}

The error is in the following line:

data = json.loads(request.data)

if i change that line to the following:

data = json.loads(request.body)

It gives me another error: “JSONDecodeError at /update_item/
Expecting value: line 1 column 1 (char 0)”

python – AttributeError: ‘str’ object has no attribute ‘num_points’

Estou tentando criar um coletor de dados de um experimento que eu estou fazendo. Até o momento eu tenho o seguinte código:

em um arquivo experiments.py tem a classe:

import csv

class Experimento:
        
       def __init__(self, material: str, num_points: int, time: float=20.0, expType: str='varredura'):
            
            if expType not in ('varredura','ponto fixo'):
                raise ValueError('Tipo de experimento inválido. Selecione entre Varredura ou Ponto Fixo. n NOTA: não utilize letras maiúsculas!')
            
            self.num_points = num_points
            self.time = time
            self.material = material
            self.expType = expType

E a subclasse:

class Ponto_Fixo(Experimento):
    
    def __init__(self, material: str, num_points: int, x: int, z: int, time: float=20.0):
        Experimento.__init__(material, num_points, time, 'ponto fixo')
        self.x = x
        self.z = z
        self.expID = material + ' x' + str(self.x) + ' z' + str(self.z) + ' pt=' + str(num_points)
        
        header = ('data','material','ponto','x','z','contagem','tempo(s)')
        
        csv_title = '%s.csv' %(self.expID)
        with open('resultados'+ csv_title,'w') as file:
            writer = csv.writer(file)
            writer.writerow(header)

No main.py, eu executo esse código assim:

import experiments

if __name__ == "__main__":
    material = 'agua+CaCO3'
    expType = 'ponto fixo'
    tempo = 20.0
    num_points = 6
    x = 2
    z = 2

def new_experiment(material, num_points, tempo, x, z, expType):
        
    if expType == 'ponto fixo':
        
        experiments.Ponto_Fixo(material, num_points, x, z, tempo)
        
novo_exp = new_experiment(material, num_points, tempo, x, z, expType)

Porém, ao fazer essa execução eu obtenho o erro do título

  File "C:AdamDoutoradoLaboratorioTARGprogramsdata collectionmain.py", line 46, in <module>
    novo_exp = new_experiment(material, num_points, tempo, x, z, expType)

  File "C:AdamDoutoradoLaboratorioTARGprogramsdata collectionmain.py", line 37, in new_experiment
    experiments.Ponto_Fixo(material, num_points, x, z, tempo)

  File "C:AdamDoutoradoLaboratorioTARGprogramsdata collectionexperiments.py", line 113, in __init__
    Experimento.__init__(material, num_points, time, 'ponto fixo')

  File "C:AdamDoutoradoLaboratorioTARGprogramsdata collectionexperiments.py", line 37, in __init__
    self.num_points = num_points

AttributeError: 'str' object has no attribute 'num_points'

A linha que o programa acusa o erro é essa (que está dentro da classe Experimento):

self.num_points = num_points

Além disso, a linha que troca a tipagem da variável num_point de int para str está depois dessa linha do erro. Logo, não estou conseguindo enxergar onde e porque está ocorrendo a troca do tipo de int para str no num_point.

Alguém consegue dar uma luz?
Obrigado

AttributeError: ‘pygame.Surface’ object has no attribute ‘move’ [closed]

import pygame

def main():
    pygame.init()
    tela = pygame.display.set_mode((700,700))
    pygame.display.set_caption("Pacman")
    cor_branca = (255,255,255)
    cor_vermelha = (255,0,0)
    superficie1 = pygame.Surface((200,30))
    superficie2 = pygame.Surface((30,200))
    superficie3 = pygame.Surface((200,30))
    superficie4 = pygame.Surface((200,30))
    pacman = pygame.Surface((30,30))
    superficie1.fill(cor_branca)
    superficie2.fill(cor_branca)
    superficie3.fill(cor_branca)
    superficie4.fill(cor_branca)
    pacman.fill(cor_vermelha)




    sair = False


    while sair == False:
        tela.blit(superficie1, (20,20))
        tela.blit(superficie2, (100,100))
        tela.blit(superficie3, (200,200))
        tela.blit(superficie4, (300,300))
        tela.blit(pacman, (400,400))
        pygame.display.update()


        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    pacman.move(-10,0)
                if event.key == pygame.K_RIGHT:
                    pacman.move(10,0)
                if event.key == pygame.K_DOWN:
                    pacman.move(0,10)
                if event.key == pygame.K_UP:
                    pacman.move(0,-10)



main()

python – AttributeError: module ‘PyQt5’ has no attribute ‘uic’

hope you are having a nice day.
I am making small PyQt window widget, before adapting it on my main window widget

this is my code,

import sys
from PyQt5 import QtWidgets, uic

class Ui(QtWidgets.QMainWindow):
    def __init__(self):
        super(Ui, self).__init__() # Call the inherited classes __init__ method
        uic.loadUi('untitled.ui', self) # Load the .ui file
        self.show()

app = QtWidgets.QApplication(sys.argv)
window = Ui()
app.exec_()

copied from tutorial site. However, it gives me this error message,

Traceback (most recent call last):
  File "path/student.py", line 18, in <module>
    window = Ui()
  File "path/student.py", line 14, in __init__
    qt.uic.loadUi('untitled.ui', self) # Load the .ui file
AttributeError: module 'PyQt5' has no attribute 'uic'

I am wondering why this is not working I tried to uninstall and install PyQt5. And weirdly, my main form, which use the same library, works the same. I checked the interpreter but both code works with the same interpreter.

python 3.x – How to fix AttributeError: module ‘tensorflow’ has no attribute ‘Session’ in Handwriting OCR

there are a lot of questions about this, but I didn’t find the solution. I want to make Handwriting OCR from this site handwriting-ocr

When I import the library, I found this error

AttributeError                            Traceback (most recent call last)
<ipython-input-22-1c5011de3819> in <module>
      8 sys.path.append('../src/')
      9 from ocr.normalization import word_normalization, letter_normalization
---> 10 from ocr import page, words, characters
     11 from ocr.helpers import implt, resize
     12 from ocr.tfhelpers import Model

D:Masterhandwriting-ocr-masterhandwriting-ocr-mastersrcocrcharacters.py in <module>
     14 location = os.path.dirname(os.path.abspath(__file__))
     15 CNN_model = Model(
---> 16     os.path.join(location, '../../models/gap-clas/CNN-CG'))
     17 CNN_slider = (60, 30)
     18 RNN_model = Model(

D:Masterhandwriting-ocr-masterhandwriting-ocr-mastersrcocrtfhelpers.py in __init__(self, loc, operation, input_name)
     18         self.input = input_name + ":0"
     19         self.graph = tf.Graph()
---> 20         self.sess = tf.Session(graph=self.graph)
     21         with self.graph.as_default():
     22             saver = tf.train.import_meta_graph(loc + '.meta', clear_devices=True)

AttributeError: module 'tensorflow' has no attribute 'Session

Because I use tensorflow 2.1.0 so I try to change Into this library

import tensorflow.compat.v1 as tf

And try this

hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))

It’s successful. The output is b'Hello, TensorFlow!'.
If use import tensorflow as tf I change tf.Session() into this tf.compat.v1.Session() successful but if I implement it in ocr.py it still doesn’t work and returns the same error no session

I have try re-install tensorflow too.

I use jupyter notebook , python 3.6, and opencv 3.3.1
Thanks for the help guys.

python – AttributeError: module ‘openstack.proxy’ has no attribute ‘Proxy’

I’m runing an Ussuri install on openSUSE 15.2. According the official install guide, the Keystone, Glance, and Placemente has run withou any bigger issues. But, when i try run any command with nova-manage, i have that message:

AttributeError: module 'openstack.proxy' has no attribute 'Proxy'

That message occurs at every comand with “nova-manage”. Especially, i’m executing the step:

Populate the nova-api database:

from the official guide, the command is:

su -s /bin/sh -c "nova-manage api_db sync" nova

Every log has that error, even the journalctl -xe if try to start the service without populate database.

The others services runs fine.

The full log is:

Traceback (most recent call last):
  File "/usr/bin/nova-manage", line 6, in <module>
    from nova.cmd.manage import main
  File "/usr/lib/python3.6/site-packages/nova/cmd/manage.py", line 48, in <module>
    from nova.cmd import common as cmd_common
  File "/usr/lib/python3.6/site-packages/nova/cmd/common.py", line 32, in <module>
    from nova import utils
  File "/usr/lib/python3.6/site-packages/nova/utils.py", line 35, in <module>
    from openstack import connection
  File "/usr/lib/python3.6/site-packages/openstack/__init__.py", line 22, in <module>
    import openstack.connection
  File "/usr/lib/python3.6/site-packages/openstack/connection.py", line 213, in <module>
    class Connection(six.with_metaclass(_meta.ConnectionMeta)):
  File "/usr/lib/python3.6/site-packages/six.py", line 856, in __new__
    return meta(name, resolved_bases, d)
  File "/usr/lib/python3.6/site-packages/openstack/_meta.py", line 47, in __new__
    service_filter_class = _find_service_filter_class(service_type)
  File "/usr/lib/python3.6/site-packages/openstack/_meta.py", line 113, in _find_service_filter_class
    service_filter_module = importlib.import_module(import_name)
  File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name(level:), package, level)
  File "/usr/lib/python3.6/site-packages/openstack/baremetal_introspection/baremetal_introspection_service.py", line 14, in <module>
    from openstack.baremetal_introspection.v1 import _proxy
  File "/usr/lib/python3.6/site-packages/openstack/baremetal_introspection/v1/_proxy.py", line 23, in <module>
    class Proxy(proxy.Proxy):
AttributeError: module 'openstack.proxy' has no attribute 'Proxy'

django – please help me i am getting error error AttributeError: /usr/lib/libgdal.so.1: undefined symbol: OGR_F_GetFieldAsInteger64

I am trying to deploy the Django project on the cloud and get error error AttributeError: /usr/lib/libgdal.so.1: undefined symbol: OGR_F_GetFieldAsInteger64 anyone gives the GDAL dockerfile for
google cloud Django my docker file. if anyone has any suggestion or they require any more file I send please help I am working from last 20 days on this error no one help, please help me

FROM gcr.io/google-appengine/python

RUN apt-get update && apt-get install -y 
  binutils 
  gdal-bin 
  python-gdal

# Create a virtualenv for dependencies. This isolates these packages from
# system-level packages.
RUN virtualenv /env -p python3.7

# Setting these environment variables are the same as running
# source /env/bin/activate.
ENV VIRTUAL_ENV /env
ENV PATH /env/bin:$PATH

# Copy the application's requirements.txt and run pip to install all
# dependencies into the virtualenv.
ADD  requirements.txt /app/requirements.txt
RUN pip install -r /app/requirements.txt
# Add the application source code.
ADD . /app

# Run a WSGI server to serve the application. gunicorn must be declared as
# a dependency in requirements.txt.
entrypoint gunicorn -b :$PORT tiwari.tiwari.wsgi

Anaconda spyder (3.7.6) AttributeError: the & # 39; tkinter & # 39; module does not have a & tk & # 39; attribute

my ide spyder has the following error when running tkinter programs

Import it without error, but when running the program alone it doesn't work

this is my code

import tkinter as tk
tk = tk.Tk()
tk.label(tk, text="hola")
tk.mainloop()

python folium [AttributeError: module ‘folium’ has no attribute ‘Map’]

I have reasonable usage experience with python, but I only know what is needed on the linux system. I am looking to learn image processing for precision farming and I discovered folium in python. I encounter the following error:

AttributeError: module 'folium' has no attribute 'Map'

I have already done a lot of research, and there were few people with the same problem, and their answers did not help me.
I am using linux mint, i have already updated linux, pip, tried with python 3.6, 3.7, up to 2, none of it worked. already installed by pip and pip3:

pip install folium

It installs normally, but the error is the same. I also tried anaconda, env and the system I prefer, all returning the same error. finally i repeated it all by cloning and installing from the git repository and nothing. I don't know what I did wrong or if it's a system issue. If anyone else has had this experience, could you help me?
Learning just by getting your hands dirty isn't it? Here is the code I got from the lib documentation itself:

import folium
mapa = folium.Map(location=(-15.77972, -47.92972))

Thank you!