Пример #1
0
 def get_match(klass, keyw):
     try:
         return klass.objects.annotate(
             name=models.F('product_name')).filter(
                 product_name__contains=keyw).values('id', 'name')[:15]
     except:
         traceback.exc()
         return []
Пример #2
0
 def send(self, data):
     """
     called from the GUI to send
     message
     """
     try:
         self.msg_lock.acquire()
         self.networking.send_msg(data)
         self.msg_lock.release()
     except:
         print traceback.exc()
Пример #3
0
def thread_entry(stop_event, name, period):
    try:
        cnter = -1
        s = None
        loginfo(f'thread {name} started')
        while not stop_event.is_set():
            try:
                if s is None:
                    s = requests.Session()
                    s.headers.update(DFT_API_HDRS)
                ## ensure thread period is respected
                time.sleep(1)
                cnter = (cnter + 1) % period
                if cnter != 0: continue
                ## call appropriated function
                if   name == MAESTRO:   maestro(s)
                elif name == DIPSEEKER: dipseeker(s)
                elif name == BUYER:     buyer(s)
                elif name == SELLER:    seller(s)
                else: raise NotImplementedError
            except requests.exceptions.ConnectionError:
                logwarn('connection error')
                s = None
    except Exception:
        logerror(exc())
    finally:
        loginfo(f'thread {name} ended')
Пример #4
0
 def queryOne(self, dbname, command):
     conn = None
     cur = None
     res = None
     try:
         conn = self.getConn(dbname)
         if DB_CONFIG[dbname]['type'] == 'mssql':
             cur = conn.cursor(True)
         elif DB_CONFIG[dbname]['type'] == 'mysql':
             cur = conn.cursor(None)
         else:
             raise '非法的数据库类型', dbname
         cur.execute(command)
         res = cur.fetchone()
     except Exception, e:
         print e
         traceback.exc()
Пример #5
0
 def queryOne(self, dbname, command):
     conn = None
     cur = None
     res = None
     try:
         conn = self.getConn(dbname)
         if DB_CONFIG[dbname]['type'] == 'mssql':
             cur = conn.cursor(True)
         elif DB_CONFIG[dbname]['type'] == 'mysql':
             cur = conn.cursor(None)
         else:
             raise '非法的数据库类型', dbname
         cur.execute(command)
         res = cur.fetchone()
     except (OperationalError, InternalError):
         logger.error(u'query one error:' + command)
         self.callReConn(dbname)
         traceback.print_exc()
     except Exception, e:
         print e
         traceback.exc()
Пример #6
0
 def get_movie(self, movie_id):
     #to get movie data
     try:
         response = {}
         db = dbObj.connect_db()
         cur = db.cursor()
         cur.execute('SELECT * FROM movies WHERE movie_id = %s', movie_id)
         for row in cur:
             response['movie_id'] = row[0]
             response['movie_name'] = row[1]
             response['movie_director'] = row[2]
             response['movie_99_popularity'] = str(row[3])
             response['movie_genre'] = row[4].split(',')
             response['movie_imdb_score'] = str(row[5])
         db.close()
         return response
     except Exception as ins:
         print ins
         print traceback.exc()
         return {
             'message': 'Movie could not be fetched. Please try again later'
         }
Пример #7
0
 def _do_request(self, op, msg=None):
     if op not in ['op', 'lp']:
         return False
     if not msg: 
         msg = {}
     msg['op'] = op
     msg['sid'] = self._sid
     path = '/?data=' + urllib.quote(json.dumps(msg))
     http_request = messages.make_http_request('GET', path)
     try:
         sock = connect(self._worker_addr)
         sock.send(http_request)
         if op == 'op':
             f = lambda : self._wait_op(sock)
         else:
             self._lp_sock = sock
             f = lambda : self._wait_lp(sock)
         t = threading.Thread(target=f)
         t.setDaemon(True)
         t.start()
     except:
         traceback.exc()
         return False
     return True
Пример #8
0
def colorFade(color, fade=100):
    """Fades a color to transparency.

	Takes a java color object and a 0 to 100 fade 'percentage' (int) and applies the percentage to the alpha channel 
	then returns the new color.

	:param color: java.awt.Color
	:param fade: int, between 0 and 100 how opaque, compared to current, to make the color.

	:returns: java.awt.Color
	"""

    from traceback import format_exc as exc

    try:
        r, g, b, a = parseJavaColor(color)
        a = int(255 * fade / 100.0)
        newColor = "Color({r},{g},{b},{a})".format(r=r, g=g, b=b, a=a)
        return newColor
    except Exception:
        print(exc())
        return (color)
Пример #9
0
    run()
    # requires sign in using phone number
    client.run_until_disconnected()


if __name__ == "__main__":
    threads = []
    try:
        import queue
        my_queue = queue.Queue()
        t = threading.Thread(target=start, args=(my_queue, ))
        threads.append(t)
        t.start()
        import qrcodescanner
        t = threading.Thread(target=qrcodescanner.main, args=(my_queue, ))
        threads.append(t)
        t.start()

        #handling requests from qrcode scanner
        while (True):
            if (my_queue.empty()):
                continue
            else:
                req = str(my_queue.get())
                print("IN QUEUE" + req)
                handle_qr(req)

    except Exception:
        import traceback
        print(traceback.exc())
Пример #10
0
    def validate(self):
        valid = True
        print('start validating')

        if self.m_offer.product_name == '':
            valid = False
            self.m_errors['product_name'] = '*product name cannot be empty'

        if self.m_offer.discount == '':
            valid = False
            self.m_errors['discount'] = '*Discount cannot be empty'

        tz = timezone.get_current_timezone()
        try:
            self.m_offer.start_date = tz.localize(
                datetime.strptime(self.m_offer.start_date, "%Y/%m/%d"))
            if self.m_offer.start_date < timezone.now():
                valid = False
                self.m_errors[
                    'start_date'] = '*Start date cannot be before today'
        except:
            valid = False
            self.m_errors['start_date'] = 'Invalid date format'

        try:
            self.m_offer.expire_date = tz.localize(
                datetime.strptime(self.m_offer.expire_date, "%Y/%m/%d"))
            if self.m_offer.expire_date < timezone.now():
                valid = False
                self.m_errors[
                    'expire_date'] = '*Expire date cannot be before today'
        except:
            valid = False
            self.m_errors['expire_date'] = 'Invalid date format'

        if self.m_offer.start_date > self.m_offer.expire_date:
            valid = False
            self.m_errors[
                'start_date'] = '*Start date cannot be before expire date'

        try:
            name, pin = self.m_area.split("(")
            pin = pin.split(")")[0]
            print('area name : ' + name)
            print('area pin : ' + pin)
            area = Area.get(name, pin)
            if area != None:
                self.m_offer.fk_area = area
            else:
                valid = False
                self.m_errors['area'] = 'location not found'
        except:
            valid = False
            self.m_errors['area'] = '*Invalid area'
            print('failed to get area')
            traceback.exc()

        self.m_offer.fk_user = User.get_user(self.m_user)
        if self.m_file_id != None and self.m_file_id != '':
            upload = FileUpload.get_file(int(self.m_file_id),
                                         self.m_offer.fk_user)
            if upload != None:
                pprint(self.m_file_id)
                pprint(upload)
                self.m_offer.product_image = upload.file
            else:
                valid = False
                self.m_errors['product_image'] = 'File attachement expires'
        else:
            valid = False
            self.m_errors['product_image'] = 'No files attached'

        self.m_valid = valid
        return self.m_valid
Пример #11
0
#!/usr/bin/python
import sys,traceback

try:
	n=int(sys.argv[1])
	print n
except (ValueError,IndexError):
	traceback.exc(file=sys.stdout)
	print "value error"
except IOError:
	print "Name Error"
else:
	print "else part when no exception"
finally:
	sys.stdout.write("running finally\n");
'''except NameError:
	print "name error"
	print "-"*10
except IndexError:
	print "index error"'''





Пример #12
0
    loginfo('thread main started')
    try:
        ## set min price*qty of order, also checks connection and symbol 
        XCH = get_exchange_info()
        ## starts the threads
        threads = []
        if not args.nomaestro:   threads.append(start_thread(MAESTRO,   10))
        time.sleep(1) ## ensures maestro can create meta collection first
        if not args.nodipseeker: threads.append(start_thread(DIPSEEKER, 10))
        if not args.nobuyer:     threads.append(start_thread(BUYER,     10))
        if not args.noseller:    threads.append(start_thread(SELLER,    10))
        ## monitor all threads, in case anyone of them die, finish execution
        is_fatal_error = False
        while not is_fatal_error:
            time.sleep(1)
            for thread, stop, name, lockfp in threads:
                if not thread.is_alive():
                    logerror(f'thread {name} died')
                    is_fatal_error = True
    except KeyboardInterrupt:
        logwarn('ctrl-c pressed')
    except Exception:
        logerror(exc())
    finally:
        for thread, stop, name, lockfp in threads:
            stop.set()
            thread.join()
            unlock(lockfp)
    loginfo('thread main ended')