Python-MySQL就在这两者之间

2024-10-01 07:42:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个将数据插入DB表的端点。下面是我的代码:-你知道吗

@app.route('/user',methods=['POST'])
def user():
    data = request.form
    loginfo= {
               'user_id' : data['user_id'],
               'dob' : data['dob'],
               'gender' : data['gender'],
               'imei1' : data['imei1'],
               'epoch' : data['epoch'],
              }

    if CONNECTION is None:
        return '{"status":503,"error":"MySQL not connected. Service Unavailable."}'

    try:
        create_user_profile(loginfo)
    except Exception,e:
        return '{"status":500,"error":' + str(e) + '}'        

    return '{"status":200}'

在我的访问日志中,我得到以下日志。你知道吗

[pid: 17877|app: 0|req: 1/1] 127.0.0.1 () {36 vars in 494 bytes} [Thu May 21 05:49:22 2015] POST /user => generated 14 bytes in 11 msecs (HTTP/1.0 200) 2 headers in 79 bytes (1 switches on core 0)

尽管它返回200(因为我应用了try except),但它仍然不会将记录插入表中。无论我在哪里通过uwsgi --reload /var/run/uwsgi.pid重新加载uwsgi,它都可以正常工作。我假设在重新加载uwsgi时会断开MySQL连接,重新建立连接,然后重新启动,因此工作正常。你知道吗

如何调试它??这个错误出现过多次。我一直在重新装。你知道吗

PS:因为我已经应用了try,所以我无法查看错误。它被部署在生产上。我现在已经把打印出来的报表写好了。下次会告诉你们的。你知道吗

在我的另一个项目中,同样的错误也会发生,但它返回500,因为我没有应用try。你知道吗

更新

下面是我的代码。请注意,为了方便起见,有些变量被删掉了。如果您发现任何语法错误,请忽略它们。其余的逻辑保持不变。你知道吗

def data_exist(self,data_exist_query):
    with self.connection:
        cur = self.connection.cursor()
        cur.execute(data_exist_query)
        rows = cur.fetchall()
        if len(rows) >= 1 :
            return True
        else :
            return False


def create_table_index_query(self,tc_query,in_query=None,ix_query=None,show_index_query=None):
    with self.connection:
        cur = self.connection.cursor()
        cur.execute(tc_query)
        cur.execute(in_query)
        self.connection.commit()

        if ix_query:
            cur = self.connection.cursor()
            cur.execute(show_index_query)
            rows = cur.fetchall()
            if len(rows) < 3 :
                print 'Creating Index'
                cur.execute(ix_query)
                self.connection.commit()


def create_user_profile(self, dct):
    rows = (str(dct['user_id']),str(datetime.strptime(dct['dob'],'%d-%m-%Y')), str(dct["gender"]), str(dct["imei1"]),str(dct['epoch']))
    found = False
    data_exist_query = "SELECT * from USER_PROFILE WHERE imei1 = '%s'" % (dct['imei1'],)
    try:
        found = self.data_exist(data_exist_query)
    except:
        pass

    if not found:
        in_query = "INSERT INTO USER_PROFILE (user_id,dob, gender, imei1,epoch) "\
               "VALUES ('%s','%s','%s','%s','%s') " % rows

        self.create_table_index_query(tc_query,in_query)

Tags: inselfdatareturnifconnectionqueryrows