Hướng dẫn mysqldb exceptions operationalerror (2006 flask) - lỗi hoạt động ngoại lệ mysqldb (bình 2006)
Tôi có một ứng dụng với Python, Flask và Flask_MysQLDB. Khi tôi thực hiện truy vấn đầu tiên, mọi thứ đều hoạt động tốt, nhưng truy vấn thứ hai luôn gây ra lỗi (2006, máy chủ đã biến mất). Tất cả mọi thứ tôi tìm thấy trên web đều nói rằng lỗi này là một vấn đề về thời gian chờ, dường như không phải là trường hợp của tôi bởi vì: 1 - Tôi chạy truy vấn thứ hai chỉ vài giây sau khi chạy lần đầu tiên 2 - Cấu hình thời gian chờ của tôi được đặt thành 8 giờ Tôi không biết đây có thể là gì, đây là mã mà tôi đang chạy:
Đây là mã cho tệp Usuarios:
Tôi có điều này chạy trên nginx + gunicorn, đây là nhật ký:
Nếu tôi chạy nó với nhiều công nhân hơn, tôi có thể chạy thêm một vài (tùy thuộc vào số lượng công nhân) truy vấn, điều gì có thể gây ra điều này? Tôi đã cập nhật bình luận Stackoverflow và thảo luận với OP. Tôi đã thực hiện một số cuộc điều tra và phát hiện ra rằng tôi cũng phải thay đổi sqlalchemy_pool_recycle để ít hơn mysql interactive_timeout. Trên máy chủ Godaddy, Interactive_Timeout đã được đặt thành 60, vì vậy tôi đặt SQLALCHEMY_POOL_RECYCLE thành 50. Tôi nghĩ rằng cả mẫu tôi đã sử dụng và thời gian chờ này là cần thiết để làm cho vấn đề biến mất, nhưng tại thời điểm này tôi không tích cực. Tuy nhiên, tôi khá chắc chắn rằng khi sqlalchemy_pool_recycle lớn hơn interactive_timeout, tôi vẫn bị lỗi hoạt động. Sau đây là 30 ví dụ mã của mysqldb.operationalerror (). Bạn có thể bỏ phiếu cho những người bạn thích hoặc bỏ phiếu cho những người bạn không thích và đi đến dự án gốc hoặc tệp nguồn bằng cách theo các liên kết trên mỗi ví dụ. Bạn cũng có thể muốn kiểm tra tất cả các chức năng/lớp có sẵn của mô -đun MySQLDB hoặc thử chức năng tìm kiếm.30 code examples of MySQLdb.OperationalError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module MySQLdb, or try the search function .Ví dụ 1 def execute_with_reconnect(self, sql: str, args: Optional[List[ValidSqlArgumentDescription]] = None, fetch_rows: Optional[bool] = False) -> Tuple[int, List[ValidSqlArgumentDescription]]: result = None # Attempt to execute the query and reconnect 3 times, then give up for _ in range(3): try: p = perf.start() n = self.cursor.execute(sql, args) perf.check(p, 'slow_query', (f'```{sql}```', f'```{args}```'), 'mysql') if fetch_rows: rows = self.cursor.fetchall() result = (n, rows) else: result = (n, []) break except OperationalError as e: if 'MySQL server has gone away' in str(e): print('MySQL server has gone away: trying to reconnect') self.connect() else: # raise any other exception raise e else: # all attempts failed raise DatabaseException('Failed to execute `{sql}` with `{args}`. MySQL has gone away and it was not possible to reconnect in 3 attemps'.format(sql=sql, args=args)) return result Ví dụ #2 def setup_audit_plugin(instance): """ Install the audit log plugin. Similarly to semisync, we may or may not use it, but we need to make sure that it's available. Audit plugin is available on 5.5 and above, which are all the versions we support. Args: instance - A hostaddr object """ return # this is intentional; we may re-enable the audit log at some # later date, but for now, we just exit. conn = connect_mysql(instance) cursor = conn.cursor() try: cursor.execute("INSTALL PLUGIN audit_log SONAME 'audit_log.so'") except MySQLdb.OperationalError as detail: (error_code, msg) = detail.args # plugin already loaded, nothing to do. if error_code != MYSQL_ERROR_FUNCTION_EXISTS: raise conn.close() Ví dụ #3 def query(self, sql, use_dict=True, retry=0): if retry < 0: retry = 0 retry = int(retry) # the first attempt does not count as 'retry' for i in range(retry + 1): try: with self() as conn: return conn_query(conn, sql, use_dict=use_dict) except MySQLdb.OperationalError as e: if len(e.args) > 0 and e[0] in retriable_err: logger.info( repr(e) + " conn_query error {sql}".format(sql=sql)) continue else: raise else: raise Ví dụ #4 def _purge_bitmaps_to(lsn): _say("Purging bitmap files to LSN: %s" % lsn) if not db_connect(): _error("Failed to connect to server, unable to purge bitmaps.") _exit_code(XB_EXIT_BITMAP_PURGE_FAIL) return False try: cur = xb_mysqldb.cursor(MySQLdb.cursors.DictCursor) cur.execute("PURGE CHANGED_PAGE_BITMAPS BEFORE %s" % lsn) except MySQLdb.OperationalError, e: _error("Got MySQL error %d, \"%s\" at execute" % (e.args[0], e.args[1])) _error("Failed to purge bitmaps!") _exit_code(XB_EXIT_BITMAP_PURGE_FAIL) return False Ví dụ #5 def job_runner(f): """Accepts any callable function and runs it Catches any exceptions and logs to Rollbar """ result = None try: ensure_mysql_connection_usable() result = f() except MySQLdb.OperationalError as e: extra_data = { 'caught_exception' : True, 'attempt_reconnect' : True, } rollbar.report_exc_info(extra_data=extra_data) attempt_mysql_reconnect() except: rollbar.report_exc_info() finally: close_connection() return result Ví dụ #6 def addAddress( self ): """Add address record to database""" if self.entries[ "LAST_NAME" ].get() != "" and \ self.entries[ "FIRST_NAME"].get() != "": # create INSERT query command query = """INSERT INTO addresses ( FIRST_NAME, LAST_NAME, ADDRESS, CITY, STATE_PROVINCE, POSTAL_CODE, COUNTRY, EMAIL_ADDRESS, HOME_PHONE, FAX_NUMBER ) VALUES (""" + \ "'%s', " * 10 % \ ( self.entries[ "FIRST_NAME" ].get(), self.entries[ "LAST_NAME" ].get(), self.entries[ "ADDRESS" ].get(), self.entries[ "CITY" ].get(), self.entries[ "STATE_PROVINCE" ].get(), self.entries[ "POSTAL_CODE" ].get(), self.entries[ "COUNTRY" ].get(), self.entries[ "EMAIL_ADDRESS" ].get(), self.entries[ "HOME_PHONE" ].get(), self.entries[ "FAX_NUMBER" ].get() ) query = query[ :-2 ] + ")" # open connection, retrieve cursor and execute query try: connection = MySQLdb.connect( db = "AddressBook" ) cursor = connection.cursor() cursor.execute( query ) except MySQLdb.OperationalError, message: errorMessage = "Error %d:\n%s" % \ ( message[ 0 ], message[ 1 ] ) showerror( "Error", errorMessage ) else: cursor.close() connection.close() self.clearContents() Ví dụ #7 def findAddress( self ): """Query database for address record and display results""" if self.entries[ "LAST_NAME" ].get() != "": # create SELECT query query = "SELECT * FROM addresses " + \ "WHERE LAST_NAME = '" + \ self.entries[ "LAST_NAME" ].get() + "'" # open connection, retrieve cursor and execute query try: connection = MySQLdb.connect( db = "AddressBook" ) cursor = connection.cursor() cursor.execute( query ) except MySQLdb.OperationalError, message: errorMessage = "Error %d:\n%s" % \ ( message[ 0 ], message[ 1 ] ) showerror( "Error", errorMessage ) self.clearContents() else: # process results results = cursor.fetchall() fields = cursor.description if not results: # no results for this person showinfo( "Not found", "Nonexistent record" ) else: # display person's info. in GUI self.clearContents() # display results for i in range( len( fields ) ): if fields[ i ][ 0 ] == "ID": self.IDEntry.set( str( results[ 0 ][ i ] ) ) else: self.entries[ fields[ i ][ 0 ] ].insert( INSERT, str( results[ 0 ][ i ] ) ) cursor.close() connection.close() Ví dụ #8 0Ví dụ #9 1Ví dụ #10 2Ví dụ #11 3Ví dụ #12 4Ví dụ #13 5Ví dụ #14 6Ví dụ #15 7Ví dụ #16 8Ví dụ #17 9Ví dụ #18 0Ví dụ #19 1Ví dụ #20 2Ví dụ #21 3Ví dụ #22 4Ví dụ #23 8Ví dụ #24 9Ví dụ #25 6Ví dụ #26 7Ví dụ #27 9Ví dụ #28 def execute_with_reconnect(self, sql: str, args: Optional[List[ValidSqlArgumentDescription]] = None, fetch_rows: Optional[bool] = False) -> Tuple[int, List[ValidSqlArgumentDescription]]: result = None # Attempt to execute the query and reconnect 3 times, then give up for _ in range(3): try: p = perf.start() n = self.cursor.execute(sql, args) perf.check(p, 'slow_query', (f'```{sql}```', f'```{args}```'), 'mysql') if fetch_rows: rows = self.cursor.fetchall() result = (n, rows) else: result = (n, []) break except OperationalError as e: if 'MySQL server has gone away' in str(e): print('MySQL server has gone away: trying to reconnect') self.connect() else: # raise any other exception raise e else: # all attempts failed raise DatabaseException('Failed to execute `{sql}` with `{args}`. MySQL has gone away and it was not possible to reconnect in 3 attemps'.format(sql=sql, args=args)) return result0 Ví dụ #29 6Ví dụ #30 7 |