烧瓶-psycopg2.InterfaceError:连接已关闭

时间:2018-06-30 11:41:18

标签: python postgresql flask

当前是flask开发中的新手,我想将数据发布到postgres数据库中,当我发布第一个值时,它们可以成功插入,但是当重试时,则引发如下异常:

 File "D:\Ride my app\Tuvuge3\app\rides\managerides.py", line 24, in insert_data_rides
    cur = con.cursor()
psycopg2.InterfaceError: connection already closed

我阅读了几篇与我的问题类似的文章,并在其中实施了解决方案,但似乎无法正常工作,对于此错误,我该怎么办。

下面是我的代码块:

def insert_data_rides():
        parser = reqparse.RequestParser()
        parser.add_argument('name', type=str, required=True)
        parser.add_argument('details', type=str, required=True)
        parser.add_argument('price', type=str, required=True)
        #parser.add_argument('driver', type=str,required=True)
        parser.add_argument('token', location='headers')
        args = parser.parse_args()

        offer_name = args['name']
        offer_details = args['details']
        price = args['price']
        cur = con.cursor()
        cur.execute("INSERT INTO rides (name,details,price,driver)  VALUES('"+ offer_name +"','"+offer_details+"','"+price+"','Huza')")
        con.commit()
        return make_response(jsonify({
                        'message': 'Ride offer created successfully.',
                        'status': 'success'},
                    ), 201)


class GetRides(Resource):

    def post(self):

        try:
            # get data passed from the URL into the database.
            #open db connection.
            return insert_data_rides()

        except psycopg2.DatabaseError as e:
            if con:
                 con.rollback()
                 print(e)
                 insert_data_rides()

            sys.exit(1)
        except psycopg2.InterfaceError as Ie:
              print(Ie)
              return insert_data_rides()


        finally:
            if con:
                con.close()

0 个答案:

没有答案