我有一个python脚本应该从postgres数据库“获取”信息
create_table.py
from flask import request
from flask_restful import Resource
import psycopg2
class single_user_Request(Resource):
def get(self, username):
connection = psycopg2.connect("dbname = 'tracker' "
"user = 'postgres' "
"password='rasengan1408' "
"host = 'localhost' "
"port='5432'")
cursor = connection.cursor()
query = "SELECT * FROM users WHERE username=%s"
result = cursor.execute(query, (username,))
row = result.fetchone()
connection.close()
if row:
return {'req_id':row[0], 'username':row[1], 'equipment_name': row[2], 'requesttype':row[3], 'description': row[4], 'status':row[5]}
return {'message':'request not found'}, 404
初始化的.py
from flask import Flask
from flask_restful import Api
from app.api.v1.requests import single_user_Request
def create_app():
app = Flask(__name__)
app.secret_key = 'GciOiJIUzI1NiJ9.eyJleHAiOj'
api = Api(app)
api.add_resource(single_user_Request, '/api/v1/userrequests/<string:username>')
return app
run.py
from app.api import create_app
app = create_app()
app.run(debug=True)
运行脚本后
AttributeError: 'NoneType' object has no attribute 'fetchone'
如果数据库有数据,我很难理解为什么fetchone会成为非类型对象
答案 0 :(得分:0)
cursor.execute
不会返回任何内容,
你需要像这样改变你的代码
query = "SELECT * FROM users WHERE username=%s"
cursor.execute(query, (username,))
row = cursor.fetchone()