Beispiel #1
0
class MySuperContextManager:
    def __init__(self):
        self.db = DBSession()

    def __enter__(self):
        return self.db

    def __exit__(self, exc_type, exc_value, traceback):
        self.db.close()
Beispiel #2
0
    def __init__(self,
                 *,
                 port: str,
                 baudrate: int,
                 path: str = 'db',
                 bs: int = 32,
                 to: int = 5,
                 http: int = 8080):

        super().__init__()
        pid = os.getpid()
        logger.info('*** NMEA Recorder startup (%d)' % pid)

        self.process: Dict[str, int] = {}
        self.process['main'] = pid

        self.ppp: Dict[str, Patrol] = {}
        self.ppp['main'] = Patrol(pid=pid)

        self.ready: bool = True
        self.g = GPS()
        self.ws = WebsocketServer(debug=True)

        self.qp = Queue()

        self.dbsession = DBSession(path=pathlib.Path(path),
                                   buffersize=bs,
                                   timeout=to)
        self.dbsession.start()
        self.process[self.dbsession.name] = self.dbsession.pid
        self.ppp[self.dbsession.name] = Patrol(pid=self.dbsession.pid)

        self.receiver = Receiver(port=port, baudrate=baudrate, qp=self.qp)
        self.receiver.start()
        self.process[self.receiver.name] = self.receiver.pid
        self.ppp[self.receiver.name] = Patrol(pid=self.receiver.pid)

        self.mc = fromUDP(quePoint=self.qp, mcip='239.192.0.1', mcport=60001)
        self.mc.start()
        self.process[self.mc.name] = self.mc.pid
        self.ppp[self.mc.name] = Patrol(pid=self.mc.pid)

        self.main = Thread(target=self.collector, name='MainLoop', daemon=True)
        self.main.start()

        self.p = Thread(target=self.patrol, name='Patrol', daemon=True)
        self.p.start()
        for k, v in self.ppp.items():
            v.start()

        self.add_route('/ws', self.ws.wsserver, websocket=True)
        self.add_route('/', self.top)
        self.add_route('/main.js', self.mainJS)
        self.add_route('/classes.js', self.classes)

        self.add_event_handler('shutdown', self.cleanup)  # notice!
        self.run(address='0.0.0.0', port=http)
Beispiel #3
0
async def get_db():
    db = DBSession()
    try:
        '''
        不要尝试在yield后面抛出HTTPException,不会起作用
        yield之后的退出,是在异常处理器之后被执行的
        '''
        yield db
    finally:
        db.close()
Beispiel #4
0
 def create(order_id):
     result = pdidx.insert().values(source='Website', orderid=order_id).execute()
     DBSession.flush()
     regid = License.generate()
     pdserial = result.inserted_primary_key[0]
     anlicenses.insert().values(
             pdserial=pdserial,
             regid=regid,
             sequence=1,
             created=datetime.now(),
             lastchange=datetime.now(),
             source='Website',
             orderid=order_id,
         ).execute()
     return pdserial
Beispiel #5
0
def payment_view(request):
    echeck = False
    if 'token' in request.params: # paypal return
        token = request.params['token']
        order = DBSession.query(Order).filter(Order.paypal_token==token).one()
        paypal = _get_paypal(request.registry.settings)
        try:
            result = paypal.get_express_checkout_details(token=token)
            payerid = result['PAYERID']
            result = paypal.do_express_checkout_payment(token=token, payerid=payerid,
                PAYMENTACTION='SALE',
                PAYMENTREQUEST_0_PAYMENTACTION='SALE',
                PAYMENTREQUEST_0_AMT=str(order.total)
                )
            status = result['PAYMENTINFO_0_PAYMENTSTATUS']
            if  status == 'Completed':
                order.confirm()
            elif status == 'Pending' and result['PAYMENTINFO_0_PAYMENTTYPE'] == 'echeck':
                order.paypal_transaction = result['PAYMENTINFO_0_TRANSACTIONID']
                echeck = True
            else:
                log.warn(str(result))
                return render_to_response('templates/error.pt',
                    {'message': 'PayPal returns: ' + str(result), 'url': request.application_url})
        except PayPalAPIResponseError, e:
            return render_to_response('templates/error.pt',
                {'message': str(e), 'url': request.application_url})
Beispiel #6
0
    def __init__(self, configfile, trace=False, app=None):
        # read the settings
        self.config = parse_config(configfile)
        self.masterlang = self.config["main"]["masterlang"]

        # for trace and app, read the values from the config file
        # override if they were turned on via the init parameters
        trace = self.config["main"]["trace"] | trace
        self.target_app = self.config["main"]["target_app"]
        if app != None: self.target_app = app
        host = self.config["main"]["dbhost"]
        dbname = self.config["main"]["dbname"]

        DBSession.__init__(self, host, dbname, trace)

        self.trace_msg("Master language = %s" % self.masterlang)
        self.trace_msg("Host = %s" % host)
        self.trace_msg("DB = %s" % dbname)
        self.trace_msg("Trace = %s" % str(trace))

        LionDBModuleMixIn.__init__(self)
Beispiel #7
0
 def __init__(self, configfile, trace=False, app=None):
     # read the settings
     self.config = parse_config(configfile)
     self.masterlang = self.config["main"]["masterlang"]
     
     # for trace and app, read the values from the config file
     # override if they were turned on via the init parameters
     trace = self.config["main"]["trace"] | trace
     self.target_app = self.config["main"]["target_app"]
     if app != None: self.target_app = app
     host = self.config["main"]["dbhost"]
     dbname = self.config["main"]["dbname"]
     
     DBSession.__init__(self, host, dbname, trace)
     
     self.trace_msg("Master language = %s" % self.masterlang)
     self.trace_msg("Host = %s" % host)
     self.trace_msg("DB = %s" % dbname)
     self.trace_msg("Trace = %s" % str(trace))
     
     LionDBModuleMixIn.__init__(self)
Beispiel #8
0
    def __init__(self):
        super().__init__()

        logger.info('### startup')
        self.running = True

        self.lack: Dict[str, Stock] = {}
        self.holdSecs = (60 * 2)
        self.locker = Lock()

        self.collector = Collector()
        self.collector.start()

        self.dbsession = DBSession(path='NMEA', buffersize=1000)
        self.dbsession.start()

        self.ws = WebsocketServer(debug=True)
        self.add_route('/ws', self.ws.wsserver, websocket=True)

        self.counter = 0
        self.ticker = Event()
        signal.signal(signal.SIGALRM, self.clocker)
        signal.setitimer(signal.ITIMER_REAL, 1, 1)

        self.cycle = Thread(target=self.routineWorker, daemon=True)
        self.cycle.start()

        self.mainLoop = Thread(target=self.loop, daemon=True)
        self.mainLoop.start()

        # logger.debug('$$$ collector = %d' % self.collector.pid)
        # logger.debug('$$$ dbsession = %d' % self.dbsession.pid)

        self.run(address='0.0.0.0', port=8080)

        self.running = False
        # self.collector.join()
        self.dbsession.join()
        logger.info('shutdown')
Beispiel #9
0
def notify_view(request):
    paypal = _get_paypal(request.registry.settings)
    response = urllib2.urlopen(paypal.config.PAYPAL_URL_BASE,
                    'cmd=_notify-validate&' + urllib.urlencode(request.params)).read()
    if response == 'VERIFIED':
        transaction = request.params['txn_id']
        try:
            order = DBSession.query(Order).filter(Order.paypal_transaction==transaction).one()
        except:
            log.warn('Wrong transaction: $s', str(request))
        else:
            if request.params['payment_status'] == 'Completed':
                order.confirm()
                row = anlicenses.select().where(anlicenses.c.pdserial==order.pdserial
                                                                ).execute().fetchone()
                params = {'order': order, 'regid': row['regid'],
                          'new': row['sequence'] == 1, 'echeck': False}
                _send_mail(request, params)
            else:
                log.warn('Useless IPN: %s' % str(request))
    else:
        log.warn('Invalid IPN request %s', str(request))
    return Response(body='', content_type='text/plain')
Beispiel #10
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from dbsession import DBSession

dbSession = DBSession()
Beispiel #11
0
 def confirm_order(order_id):
     order = DBSession.query(Order).filter(Order.order_id==order_id).one()
     order.confirm()
     return order
from searcher.cmb_searcher import CMBPriceSearcher
from searcher.boc_searcher import BOCPriceSearcher
from searcher.travelex_searcher import TravelexPriceSearcher
from models import CurrencyRate
from dbsession import DBSession, Base

session = DBSession.dbSession()

# #travelex get data
# travelexSearcher=TravelexPriceSearcher()
# travelexData=travelexSearcher.getAllHistoryData()
# session.add_all(travelexData)
# session.commit()

#boc get data
bocSearch = BOCPriceSearcher()
bocData = bocSearch.getAllHistoryData()
session.add_all(bocData)
session.commit()

# #cmb get data
# cmbSearcher=CMBPriceSearcher()
# cmbData=cmbSearcher.getAllHistoryData()
# session.add_all(cmbData)
# session.commit()
Beispiel #13
0
 def __init__(self):
     self.db = DBSession()
Beispiel #14
0
def order_view(request):
    if request.POST:
        v = request.POST
        order = Order()
        order.first_name = v['first_name']
        order.last_name = v['last_name']
        order.email = v['email']
        if v['lic'] == 'upgrade':
            row = anlicenses.select().where(anlicenses.c.regid==v['license']).execute().fetchone()
            order.pdserial = row['pdserial']
        order.total = 0
        order.payment = v['method']
        order.status = 'pending'
        order.created = datetime.now()
        DBSession.add(order)
        DBSession.flush()

        if v['bundle'] != '0':
            bundle = Items()
            bundle.order_id = order.order_id
            bundle.sku = v['bundle']
            DBSession.add(bundle)
            DBSession.flush()
            order.total = bundle.product.price
        for sku in v.getall('module'):
            module = Items()
            module.order_id = order.order_id
            module.sku = sku
            DBSession.add(module)
            DBSession.flush()
            order.total = order.total + module.product.price
        if v['method'] == 'paypal': # Paypal processing
            paypal = _get_paypal(request.registry.settings)
            #order = DBSession.query(Order).filter(Order.order_id==v['order']).one()
            description = ', '.join(i.product.name for i in order.items)
            result = paypal.set_express_checkout(
                PAYMENTREQUEST_0_AMT=str(order.total),
                PAYMENTREQUEST_0_ITEMAMT=str(order.total),
                PAYMENTREQUEST_0_DESC='Total: $' + str(order.total) + ' ' + description,
                PAYMENTREQUEST_0_PAYMENTACTION='SALE',
                RETURNURL=request.application_url + '/payment',
                CANCELURL=request.application_url + '/cancel',
            )
            if result.success:
                token = result['TOKEN']
                order.paypal_token = token
                return HTTPFound(location=paypal.generate_express_checkout_redirect_url(token))

        if v['method'] == 'card':
            settings = request.registry.settings
            if settings['braintree.environment'] == 'Production':
                env = braintree.Environment.Production
            else:
                env = braintree.Environment.Sandbox
            braintree.Configuration.configure(env,
                merchant_id=settings['braintree.merchant_id'],
                public_key=settings['braintree.public_key'],
                private_key=settings['braintree.private_key'])
            tr_data = braintree.Transaction.tr_data_for_sale(
                {"transaction": {"type": "sale",
                                 "order_id": str(order.order_id),
                                 "amount": str(order.total),
                                 "options": {"submit_for_settlement": True}}},
                request.application_url + '/payment')
            braintree_url = braintree.TransparentRedirect.url()
            return render_to_response('templates/payment.pt',
                {'order': order, 'v': v, 'tr_data':tr_data, 'braintree_url': braintree_url},
                request=request)
    try:
        bundles = DBSession.query(Product).filter(Product.bundle).order_by(Product.display_order).all()
        modules = DBSession.query(Product).filter(~Product.bundle).order_by(Product.display_order).all()
    except DBAPIError:
        return Response(conn_err_msg, content_type='text/plain', status_int=500)
    return {'bundles': bundles, 'modules': modules}
Beispiel #15
0
class Main(responder.API):
    def __init__(self):
        super().__init__()

        logger.info('### startup')
        self.running = True

        self.lack: Dict[str, Stock] = {}
        self.holdSecs = (60 * 2)
        self.locker = Lock()

        self.collector = Collector()
        self.collector.start()

        self.dbsession = DBSession(path='NMEA', buffersize=1000)
        self.dbsession.start()

        self.ws = WebsocketServer(debug=True)
        self.add_route('/ws', self.ws.wsserver, websocket=True)

        self.counter = 0
        self.ticker = Event()
        signal.signal(signal.SIGALRM, self.clocker)
        signal.setitimer(signal.ITIMER_REAL, 1, 1)

        self.cycle = Thread(target=self.routineWorker, daemon=True)
        self.cycle.start()

        self.mainLoop = Thread(target=self.loop, daemon=True)
        self.mainLoop.start()

        # logger.debug('$$$ collector = %d' % self.collector.pid)
        # logger.debug('$$$ dbsession = %d' % self.dbsession.pid)

        self.run(address='0.0.0.0', port=8080)

        self.running = False
        # self.collector.join()
        self.dbsession.join()
        logger.info('shutdown')

    def healthChecker(self, *, pid: int, name:str):
        p = psutil.Process(pid)
        cpuP = p.cpu_percent(interval=1)
        cpuN = p.cpu_num()
        logger.debug('=== %s: %d - %.1f' % (name, cpuN, cpuP))

    def clocker(self, number, frame):
        self.ticker.set()
        self.counter += 1

    def loop(self):
        while self.running:
            try:
                stock: Stock = self.collector.outputQueue.get()
            except (KeyboardInterrupt,) as e:
                logger.warning(e)
            else:
                for nmea in stock.nmea:
                    self.ws.broadcast(message=nmea.raw.decode())
                    self.dbsession.qp.put(nmea.raw)
                    name = nmea.item[0][1:]
                    with self.locker:
                        # if name not in self.lack:
                        #     logger.success('+++ append %s' % name)
                        self.lack[name] = nmea

    def cleaner(self):
        now = dt.now()
        with self.locker:
            expired: List[str] = []
            for k, v in self.lack.items():
                if (now - v.at).total_seconds() >= self.holdSecs:
                    expired.append(k)
            if len(expired):
                # logger.debug('--- %s was expired' % expired)
                for name in expired:
                    del self.lack[name]

    def routineWorker(self):
        lastEntries: int = 0
        while self.running:
            self.ticker.clear()
            self.ticker.wait()
            thisEntries: int = len(self.lack)
            if thisEntries != lastEntries:
                logger.debug('Holding %d NMEA' % thisEntries)
            lastEntries = thisEntries

            if self.counter % 5 == 0:
                self.cleaner()
                # self.healthChecker(name='main', pid=os.getpid())
                self.healthChecker(name=self.collector.name, pid=self.collector.pid)
Beispiel #16
0
class Main(responder.API):
    def __init__(self,
                 *,
                 port: str,
                 baudrate: int,
                 path: str = 'db',
                 bs: int = 32,
                 to: int = 5,
                 http: int = 8080):

        super().__init__()
        pid = os.getpid()
        logger.info('*** NMEA Recorder startup (%d)' % pid)

        self.process: Dict[str, int] = {}
        self.process['main'] = pid

        self.ppp: Dict[str, Patrol] = {}
        self.ppp['main'] = Patrol(pid=pid)

        self.ready: bool = True
        self.g = GPS()
        self.ws = WebsocketServer(debug=True)

        self.qp = Queue()

        self.dbsession = DBSession(path=pathlib.Path(path),
                                   buffersize=bs,
                                   timeout=to)
        self.dbsession.start()
        self.process[self.dbsession.name] = self.dbsession.pid
        self.ppp[self.dbsession.name] = Patrol(pid=self.dbsession.pid)

        self.receiver = Receiver(port=port, baudrate=baudrate, qp=self.qp)
        self.receiver.start()
        self.process[self.receiver.name] = self.receiver.pid
        self.ppp[self.receiver.name] = Patrol(pid=self.receiver.pid)

        self.mc = fromUDP(quePoint=self.qp, mcip='239.192.0.1', mcport=60001)
        self.mc.start()
        self.process[self.mc.name] = self.mc.pid
        self.ppp[self.mc.name] = Patrol(pid=self.mc.pid)

        self.main = Thread(target=self.collector, name='MainLoop', daemon=True)
        self.main.start()

        self.p = Thread(target=self.patrol, name='Patrol', daemon=True)
        self.p.start()
        for k, v in self.ppp.items():
            v.start()

        self.add_route('/ws', self.ws.wsserver, websocket=True)
        self.add_route('/', self.top)
        self.add_route('/main.js', self.mainJS)
        self.add_route('/classes.js', self.classes)

        self.add_event_handler('shutdown', self.cleanup)  # notice!
        self.run(address='0.0.0.0', port=http)

    async def cleanup(self):
        self.dbsession.join()
        self.receiver.join()
        self.mc.join()
        logger.debug('... OK! shutdown')

    def top(self, req: responder.Request, resp: responder.Response):
        resp.content = self.template('index.html')

    def classes(self, req: responder.Request, resp: responder.Response):
        resp.content = self.template('classes.js')

    def mainJS(self, req: responder.Request, resp: responder.Response):
        resp.content = self.template('main.js')

    def collector(self):
        loop: bool = True
        try:
            while loop:
                try:
                    raw: bytes = self.receiver.qp.get()
                except (KeyboardInterrupt, ) as e:
                    break
                else:
                    self.dbsession.qp.put(raw)

                    part = raw.split(b'*')
                    if len(part) > 1:
                        main = part[0][1:]
                        csum = int(part[1][:2], 16)
                        calc = reduce(xor, main, 0)
                        if calc != csum:
                            logger.error('!!! bad checksum')
                        else:
                            item = main.split(b',')
                            symbol = item[0]
                            prefix = symbol[0:2]
                            suffix = symbol[2:5]
                            if prefix == b'GP':
                                if suffix == b'RMC':
                                    location = self.g.get(item=item)
                                    ooo = {
                                        'type': 'location',
                                        'info': asdict(location)
                                    }
                                    self.ws.broadcast(message=json.dumps(ooo))
                                    if location.valid:
                                        print(location)

        except KeyboardInterrupt as e:
            loop = False

    def patrol(self):
        loop: bool = True
        try:
            while loop:
                time.sleep(5)
                stats = {'type': 'stats', 'info': {}}
                # logger.info('--------------------------------------------------------------------')
                for k, v in self.ppp.items():
                    stats['info'][k] = asdict(v.stats)

                # logger.info(stats)
                self.ws.broadcast(message='%s' % json.dumps(stats, indent=2))
        except KeyboardInterrupt as e:
            loop = False
Beispiel #17
0
def cancel_view(request):
    token = request.params['token']
    order = DBSession.query(Order).filter(Order.paypal_token==token).one()
    order.status = 'canceled'
    message = 'Order canceled'
    return {'message': message, 'url': request.application_url}