SORU
19 ŞUBAT 2009, PERŞEMBE


pythonic bir şekilde bir şeyler kat sayısı kadar denemek var mı?

Paylaşılan bir linux host MySQL sunucusu sorgulama olan bir python komut dosyası var. Nedense, MySQL genellikle "sunucu gitti" hata: . dönüş sorguları

_mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away')

Eğer sorguyu yeniden hemen ardından çalışırsanız, genellikle başarılı olur. Bu yüzden, eğer bir sorgu yürütmek için denemek için python mantıklı bir yolu varsa bilmek isterim, ve eğer başarısız olursa, tekrar dener, sabit bir sayı. Muhtemelen tamamen vazgeçmeden önce 5 kez denemek istiyorum.

İşte ben kod türü:

conn = MySQLdb.connect(host, user, password, database)
cursor = conn.cursor()

try:
    cursor.execute(query)
    rows = cursor.fetchall()
    for row in rows:
        # do something with the data
except MySQLdb.Error, e:
    print "MySQL Error %d: %s" % (e.args[0], e.args[1])

Açıkça tümcesi dışında başka bir girişimde alarak yapabilirim, ama bu çok çirkin, ve bunu başarmak için iyi bir yolu olmalı gibi bir his var içimde.

CEVAP
19 ŞUBAT 2009, PERŞEMBE


Dana'nın cevabı üzerinde yapı, bir mimar olarak bunu yapmak isteyebilirsiniz:

def retry(howmany):
    def tryIt(func):
        def f():
            attempts = 0
            while attempts < howmany:
                try:
                    return func()
                except:
                    attempts  = 1
        return f
    return tryIt

Sonra...

@retry(5)
def the_db_func():
    # [...]

decorator modül kullanan gelişmiş versiyonu

import decorator, time

def retry(howmany, *exception_types, **kwargs):
    timeout = kwargs.get('timeout', 0.0) # seconds
    @decorator.decorator
    def tryIt(func, *fargs, **fkwargs):
        for _ in xrange(howmany):
            try: return func(*fargs, **fkwargs)
            except exception_types or Exception:
                if timeout is not None: time.sleep(timeout)
    return tryIt

Sonra...

@retry(5, MySQLdb.Error, timeout=0.5)
def the_db_func():
    # [...]

the decorator module yüklemek için:

$ easy_install decorator

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Edgar flores

    Edgar flores

    7 HAZİRAN 2006
  • Louis C.K.

    Louis C.K.

    18 HAZİRAN 2006
  • TomSka

    TomSka

    30 Mayıs 2006