コード例 #1
0
def update_email_password():
    logger.info("Entering update_email_password..")
    add_email_form = AddEmailForm()
    change_email_password_form = ChangeEmailPasswordForm()
    existing_addresses = get_existing_addresses_by_user_id(
        current_user.user_id)

    # -- Update Email Password submission START
    if change_email_password_form.is_submitted():
        logger.info("Address: %s",
                    change_email_password_form.email_address.data)
        email_addr = change_email_password_form.email_address.data
        email_address = get_email_address_by_address(email_addr)

        logger.info("Entering password change")
        if email_address is not None and email_address.get_active_status():
            if change_email_password_form.new_password.data:
                if test_mailbox_conn(email_addr\
                , change_email_password_form.new_password.data):
                    flash('Password successfully updated!', 'success')
                    email_address.set_email_password(\
                    change_email_password_form.new_password.data)
                    db.session.commit()
                else:
                    flash('Unable to connect to mailbox with new password!',
                          'error')
            else:
                logger.info("Password entered is empty.")
                flash('Password cannot be empty!.', 'error')
        else:
            logger.warn("Email address is inactive or None.")
            flash('Email address is inactive or does not exist', 'error')
        # -- Update Email Password submission END --

    return redirect(url_for('dash_email'))
コード例 #2
0
ファイル: label.py プロジェクト: rsanting/PlanarAlly
async def delete(sid, data):
    sid_data = state.sid_map[sid]
    user = sid_data["user"]
    room = sid_data["room"]
    location = sid_data["location"]

    label = Label.get_or_none(uuid=data)

    if label is None:
        logger.warn(f"{user.name} tried to delete a non-existing label.")
        return

    if label.user != user:
        logger.warn(f"{user.name} tried to delete another user's label.")
        return

    label.delete_instance(True)

    await sio.emit(
        "Label.Delete",
        {
            "user": user.name,
            "uuid": data
        },
        skip_sid=sid,
        namespace="/planarally",
    )
コード例 #3
0
ファイル: cards.py プロジェクト: davidvon/pipa-pay-server
    def post(self):
        try:
            args = request.values
            logger.info('[ApiCardBuy] args:%s' % args)

            card_id = args.get('cardId')
            price = args.get('price')
            count = args.get('count')
            openid = args.get('openId')
            order = create_order(card_id, float(price), openid, count)
            if not order:
                return {'result': 250}
            res, outputs = payable(request, openid, order)
            logger.info('[ApiCardBuy] data:%s' % str(outputs))

            if res == 0:
                outputs['orderId'] = order.order_id
                logger.info('[ApiCardBuy] create temp order success:%s' %
                            order.order_id)
                return {'result': 0, 'content': outputs}

            logger.warn('[ApiCardBuy] order:%s pre-pay failed:%d' %
                        (order.order_id, res))
            return {'result': res, 'msg': outputs}
        except Exception as e:
            logger.error('[ApiCardBuy] except:%s' % e.message)
            return {'result': 254, 'msg': e.message}
コード例 #4
0
ファイル: label.py プロジェクト: rsanting/PlanarAlly
async def add(sid, data):
    sid_data = state.sid_map[sid]
    user = sid_data["user"]
    room = sid_data["room"]
    location = sid_data["location"]

    label = Label.get_or_none(uuid=data)

    if label is not None:
        logger.warn(
            f"{user.name} tried to add a label with an id that already exists."
        )
        return

    if data["user"] != user.name:
        logger.warn(f"{user.name} tried to add a label for someone else.")
        return

    data["user"] = User.by_name(data["user"])
    label = Label.create(**data)

    for psid in state.get_sids(skip_sid=sid, room=room):
        if state.get_user(psid) == user or label.visible:
            await sio.emit("Label.Add",
                           label.as_dict(),
                           room=psid,
                           namespace="/planarally")
コード例 #5
0
    def __get_genome(self):
        """
        Get Genome object from DB corresponding to a strain/genome name and a User.

        Returns:
            app.models.Genome: :class:`Genome` object in MIST JSON output file
        Warning:
            If genome does not exist in the DB for the `self.user` then a new
            genome is created
        """
        genome = self.session.query(Genome).filter_by(name=self.strain,
                                                      user=self.user).first()
        if genome is None:
            logger.warn(
                'Genome {0} does not exist for user {1}. Adding genome to database'
                .format(self.strain, self.user))

            genome = Genome(name=self.strain,
                            user=self.user,
                            time_uploaded=datetime.utcnow())
            try:
                self.session.add(genome)
                self.session.commit()
            except:
                self.session.rollback()
        return genome
コード例 #6
0
 async def publish_state(self, customer_state: CustomerState):
     logger.debug('publish_state')
     logger.debug(customer_state)
     topic = self.get_topic_for_event_type(customer_state.status)
     logger.warn(f'Publishing {customer_state} to {topic} topic')
     message = self.prepare_payload(customer_state)
     self.client.publish(topic, message)
コード例 #7
0
def delete(id):
    if not is_owned(vm_id=id, username=current_user.fullname):
        logger.warn(f"Try deleting vm id <{id}> by <{current_user.fullname}>")
        return redirect("/")
    try:
        subprocess.check_output(f'vboxmanage unregistervm {id} --delete', shell=True)
    except:
        logger.error(f"Error deleting vm id <{id}> by <{current_user.fullname}>")

    logger.info(f"Deleted vm id <{id}> by <{current_user.fullname}>")
    delete_machine(vm_id=id)
    time.sleep(4.0)
    return redirect('/')
コード例 #8
0
async def phone(request: Request, customer_id: int):
    """
    Customer calls asistance
    """
    logger.warn('THIS ENDPOINT DOES NOT SEND MQTT MESSAGE!')
    logger.warn(
        'THIS ENDPOINT DOES EVERYTHINK WHAT THIS APP WILL DO IF THE MESSAGE WOULD OCCURE'
    )
    EventsHendler.handle_event(
        CUSTOMER_BROWSING_TOPIC,
        f'{{"id": "{customer_id}", "ts": "{int(time.time())}", "dep": "Unknown"}}',
        app.state)
    return PlainTextResponse('OK')
コード例 #9
0
def admin():
    logger.info("Entering admin route")
    if current_user.get_admin_status() == True:
        logger.info("Admin user logging in, redirecting to admin portal")

        statistics = get_admin_dashboard_stats()
        monthly_stats = get_admin_monthly_overview()

        return render_template('admin/index.html', statistics = statistics \
        , monthly_stats = monthly_stats)
    else:
        logger.warn("Normal user accessing admin, redirecting to dashboard")
        return redirect(url_for('dashboard'))
コード例 #10
0
def stream_results():
    logger.warn('Connected to /gallery')

    # request results from Google
    headers = {
        'User-Agent':
            "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
    }
    # loop through objects in flask global object
    for filename, actual_name in session['file_dict'].iteritems():

        fpath = os.path.normpath(os.path.join(app.config['UPLOAD_DIR'], filename))

        r = requests.post('http://www.google.com/searchbyimage/upload',
                          headers=headers,
                          files={'encoded_image': (filename, open(fpath, 'rb')), 'image_content': ''},
                          allow_redirects=False)

        logger.warn('Requesting {}'.format(r.headers['Location']))
        r_2 = requests.get(r.headers['Location'],
                           headers=headers)

        bs = BeautifulSoup(r_2.text, 'lxml')
        logger.warn('Requesting {}'.format(bs.find('a', text='Visually similar images')['href']))
        r_3 = requests.get(bs.find('a', text='Visually similar images')['href'],
                           headers=headers)

        # result = imgsch.parse_google_query(r.text)

        print('vvvvvvvvvv')
        pprint(r_3)
        print('----')
        pprint(len(r_3.text))
        print('^^^^^^^^^^')
        result = parse_google_query(r_3.text)
        result.update({
            # 'url': google_url,
            # 'img': public_url,
            'filename': actual_name
        })

        if not r_3.ok:
            logger.warn('Google API query returned code {}'.format(r_3.code))
            continue

        logger.warn('r.ok! {}'.format(r_2.text))
        emit('result', json.dumps(result))

        # allow images to live for 5 minutes
        t = Timer(600.0, delete_file, [filename])
        t.start()
コード例 #11
0
 def parse_all_test_metadata(self):
     self.metadata_dict = self.mist_json['Results'][0]['Metadata']
     for test_name in self.metadata_dict.keys():
         mist_test = self.session.query(MistTest).filter_by(
             name=test_name).first()
         if mist_test is not None:
             mist_metadata_results = self.__parse_mist_test_metadata(
                 mist_test)
             self.session.add(mist_metadata_results)
             self.session.commit()
         else:
             logger.warn(
                 'Test {0} does not exist in the database! User: {1} | MIST JSON {2}'
                 .format(test_name, self.user.name, self.json_path))
コード例 #12
0
def add_email():
    logger.info("Entering add_email..")
    add_email_form = AddEmailForm()
    change_email_password_form = ChangeEmailPasswordForm()
    existing_addresses = get_existing_addresses_by_user_id(
        current_user.user_id)

    ## --- Add Email Form submission START ---
    if add_email_form.validate_on_submit():
        email_addr = add_email_form.email_address.data
        password = add_email_form.password.data

        # Checks if email already exist in database
        email_exist = get_email_address_by_address(email_addr)

        if email_exist == None:
            # Attempts a mailbox login via imap_tools based on submit
            # Adds the email address to the database
            logger.info("Checking mailbox connectivity..")
            # -- If you want to test adding emails to a user account
            # -- without checking connection
            # -- change the if statement to if True:
            if test_mailbox_conn(email_addr, password):
                new_email = EmailAddress()
                new_email.set_email_address(add_email_form.email_address.data)
                new_email.set_email_password(add_email_form.password.data)
                new_email.set_owner_id(current_user.user_id)
                new_email.set_created_at(datetime.now())
                new_email.set_active_status(True)
                db.session.add(new_email)
                db.session.commit()
            # If connection to mailbox fails
            else:
                flash("Unable to connect to mailbox."\
                " Maybe you've entered a wrong email/password?", 'error')
        else:
            flash("{} already exist in our database!".format(email_addr),
                  'error')
            logger.error("Email already exist")
    else:
        if not add_email_form.email_address.data:
            logger.warn('Empty email submitted')
            flash('Email Address cannot be empty!', 'error')
        if not add_email_form.password.data:
            logger.warn('Empty password submitted')
            flash('Password cannot be empty!', 'error')
    ## -- Add Email Form submission END --

    return redirect(url_for('dash_email'))
コード例 #13
0
def save_tasks():
    incomplete = Todo.query.filter_by(complete=False).all()
    complete = Todo.query.filter_by(complete=True).all()
    incomplete.extend(complete)
    url = "http://localhost:5001/api/save"
    entries = ["Id: " + str(entry.id) + " Task: " + entry.text + " Complete: " + str(entry.complete) \
        for entry in incomplete]
    response = requests.post(url=url, data=json.dumps(entries))
    if response.ok:
        logger.warn("Todo saved to file.")
        return make_response("Todo saved to file.", 200)
    else:
        logger.error(response.reason)
        return make_response("Exception occurred while saving.", 500)
    return redirect('/')
コード例 #14
0
ファイル: expedition.py プロジェクト: KanColleTool/kcsrv
def cancel():
    """Cancels a mission"""
    fleet_id = int(request.values.get("api_deck_id")) - 1

    try:
        fleet = g.admiral.fleets[fleet_id]
    except IndexError:
        logger.warn("Fleet does not exist -> {}".format(fleet_id))
        abort(404)
        return

    fleet.expedition_cancelled = True
    db.session.add(fleet)
    db.session.commit()
    return svdata(MemberHelper.expedition(fleet, cancelled=True))
コード例 #15
0
def cancel():
    """Cancels a mission"""
    fleet_id = int(request.values.get("api_deck_id")) - 1

    try:
        fleet = g.admiral.fleets[fleet_id]
    except IndexError:
        logger.warn("Fleet does not exist -> {}".format(fleet_id))
        abort(404)
        return

    fleet.expedition_cancelled = True
    db.session.add(fleet)
    db.session.commit()
    return svdata(MemberHelper.expedition(fleet, cancelled=True))
コード例 #16
0
 def parse_all_marker_results(self):
     self.test_result_dict = self.mist_json['Results'][0]['TestResults']
     for test_name in self.test_result_dict.keys():
         mist_test = self.session.query(MistTest).filter_by(
             name=test_name).first()
         if mist_test is not None:
             test_results = self.test_result_dict[test_name]
             if mist_test.type == MistTestType.allelic:
                 self.__parse_allelic_marker_results(
                     mist_test, test_results)
             else:
                 self.__parse_non_allelic_marker_results(
                     mist_test, test_results)
         else:
             logger.warn(
                 'Test {0} does not exist in the database! User: {1} | MIST JSON {2}'
                 .format(test_name, self.user.name, self.json_path))
コード例 #17
0
def add_task(task):
    try:
        print("Task Received: " + task)
        if len(task) > 10:
            raise Exception
        todo = Todo(text=task, complete=False)
        db.session.add(todo)
        db.session.commit()
        # Logging with the logger will be tracked as logging telemetry (traces)
        logger.warn("Added entry: " + todo.text)
        # Records a measure metric to be sent as telemetry (customMetrics)
        mmap.measure_int_put(request_measure, 1)
        mmap.record(tmap)
    except Exception:
        logger.exception("ERROR: Input length too long.")
        return make_response("ERROR: Input length too long.", 500)
    return make_response("Successfully added task.", 200)
コード例 #18
0
def _spawn_jobqueue() -> None:
    """
    Spawns a job queue:

    :return:
    """
    logger.info("Starting job queue!")
    future_time = datetime.utcnow() + timedelta(seconds=10)
    while True:
        if len(JOB_QUEUE) == 0:
            # logger.debug("Sleeping one second")
            sleep(1)

        if future_time <= datetime.utcnow():
            future_time = datetime.utcnow() + timedelta(seconds=15)
            _log_queues()

        for index, job in enumerate(JOB_QUEUE):
            try:
                if not job.is_runnable():
                    continue

                job.run_funcs_before_proc_completion()
                job.run_process()
                # Periodically check the queue for messages and print them.
                _async_read2(job)
                job_retval = job.process.poll()
                if job_retval != None or not job.is_pid():
                    logger.debug("Completed: %s" % str(job))
                    if job_retval != 0:
                        logger.debug("Job return value was not 0. It was %d" % int(job_retval))
                        _save_job(job, job_retval, "Failed to execute with unknown error.")
                    else:
                        _save_job(job, job_retval, "Successfully executed job.")
                    
                    job.run_funcs_after_proc_completion()
                    job.run_job_clean_up(index)
                elif job.is_zombie():
                    logger.warn("ZOMBIE process cleanup %s" % str(job))
                    _save_job(job, 600, "Job became a zombie somehow.")
                    job.run_job_clean_up(index)
                    # Clean zombie has to happen after we garbage collect the popen object
            except Exception as e:
                logger.exception(e)
                _save_job(job, 500, str(e.message))
                job.run_job_clean_up(index)
コード例 #19
0
def add():
    add_input = request.form['add_input']
    # Fail if string greater than 10 characters
    try:
        if len(add_input) > 10:
            raise Exception
        todo = Todo(text=add_input, complete=False)
        db.session.add(todo)
        db.session.commit()
        # Logging with the logger will be tracked as logging telemetry (traces)
        logger.warn("Added entry: " + todo.text)
        # Records a measure metric to be sent as telemetry (customMetrics)
        mmap.measure_int_put(request_measure, 1)
        mmap.record(tmap)
    except Exception:
        logger.exception("ERROR: Input length too long.")
        return redirect('/error')
    return redirect('/')
コード例 #20
0
ファイル: note.py プロジェクト: chisaipete/PlanarAlly
async def update_note(sid: int, data: Dict[str, Any]):
    pr: PlayerRoom = game_state.get(sid)

    note = Note.get_or_none(uuid=data["uuid"])

    if not note:
        logger.warning(
            f"{pr.player.name} tried to update non-existant note with id: '{data['uuid']}'"
        )
        return

    if note.user != pr.player:
        logger.warn(f"{pr.player.name} tried to update note not belonging to him/her.")
    else:
        with db.atomic():
            note.title = data["title"]
            note.text = data["text"]
            note.save()
コード例 #21
0
ファイル: cards.py プロジェクト: davidvon/pipa-pay-server
    def post(self):
        args = request.values
        logger.debug('[ApiCardShareInfo] in: args[%s]' % args)

        open_id = args['openId']
        card_id = args['cardId']
        card_code = args['cardCode']
        card = CustomerCard.query.filter_by(card_id=card_id,
                                            card_code=card_code).first()
        if not card:
            logger.warn(
                '[ApiCardShareInfo] openid:%s card[id:%s code:%s] not exist' %
                (open_id, card_id, card_code))
            return {'result': 254}

        share = CustomerCardShare.query.filter_by(
            share_customer_id=open_id, customer_card_id=card.id).first()
        acquire_customer = None
        if share and share.acquire_customer_id:
            acquire_customer = Customer.query.filter_by(
                openid=share.acquire_customer_id).first()
        data = {
            'result': 0,
            'data': {
                'status':
                '已领取' if share.status == 2 else '未领取',
                'cardLogo':
                share.customer_card.card.merchant.logo,
                'cardCode':
                card_code,
                'cardName':
                share.customer_card.card.title,
                'datetime':
                str(share.datetime),
                'content':
                share.content,
                'acquireUserImg':
                acquire_customer.head_image if acquire_customer else '',
                'acquireUserName':
                acquire_customer.show_name() if acquire_customer else '',
            }
        }
        logger.debug('[ApiCardShareInfo] out: return[%s]' % data)
        return data
コード例 #22
0
    def clean_process(self):
        logger.info("Started cleaning")
        if self.process and not self.process.poll():
            self.process.stdin.close()
            self.process.stdout.close()
            try:
                self.process.terminate()
            except OSError:
                logger.warn("No process to terminate")
            self.process = None

        if self.inputProcessing and self.inputProcessing.isAlive():
            self.inputProcessing = None
            # does not need to be stopped because stdin is closed

        if self.heartbeat and self.heartbeat.isAlive():
            self.heartbeat.stop = True
            self.heartbeat = None
        logger.info("Closed all threads")
コード例 #23
0
ファイル: label.py プロジェクト: rsanting/PlanarAlly
async def set_visibility(sid, data):
    sid_data = state.sid_map[sid]
    user = sid_data["user"]
    room = sid_data["room"]
    location = sid_data["location"]

    label = Label.get_or_none(uuid=data["uuid"])

    if label is None:
        logger.warn(f"{user.name} tried to change a non-existing label.")
        return

    if label.user != user:
        logger.warn(f"{user.name} tried to change another user's label.")
        return

    label.visible = data["visible"]
    label.save()

    for psid in state.get_sids(skip_sid=sid, room=room):
        if state.get_user(psid) == user:
            await sio.emit(
                "Label.Visibility.Set",
                {
                    "user": label.user.name,
                    **data
                },
                room=psid,
                namespace="/planarally",
            )
        else:
            if data["visible"]:
                await sio.emit("Label.Add",
                               label.as_dict(),
                               room=psid,
                               namespace="/planarally")
            else:
                await sio.emit("Label.Delete", {
                    'uuid': label.uuid,
                    'user': label.user.name
                },
                               room=psid,
                               namespace="/planarally")
コード例 #24
0
async def set_visibility(sid: int, data: Dict[str, Any]):
    pr: PlayerRoom = game_state.get(sid)

    label = Label.get_or_none(uuid=data["uuid"])

    if label is None:
        logger.warn(f"{pr.player.name} tried to change a non-existing label.")
        return

    if label.user != pr.player:
        logger.warn(f"{pr.player.name} tried to change another user's label.")
        return

    label.visible = data["visible"]
    label.save()

    for psid in game_state.get_sids(skip_sid=sid, room=pr.room):
        if game_state.get_user(psid) == pr.player:
            await sio.emit(
                "Label.Visibility.Set",
                {
                    "user": label.pr.player.name,
                    **data
                },
                room=psid,
                namespace=GAME_NS,
            )
        else:
            if data["visible"]:
                await sio.emit("Label.Add",
                               label.as_dict(),
                               room=psid,
                               namespace=GAME_NS)
            else:
                await sio.emit(
                    "Label.Delete",
                    {
                        "uuid": label.uuid,
                        "user": label.pr.player.name
                    },
                    room=psid,
                    namespace=GAME_NS,
                )
コード例 #25
0
def perform_systems_check() -> Response:
    """
    Kicks off a systems check job

    :return: Response object
    """
    current_kit_configuration = conn_mng.mongo_kit.find_one({"_id": KIT_ID})
    if current_kit_configuration:
        if current_kit_configuration["form"] and current_kit_configuration["form"]["root_password"]:
            cmd_to_execute = ("ansible-playbook -i /opt/rock/playbooks/inventory.yml -e ansible_ssh_pass='******' site.yml")
            spawn_job("SystemsCheck",
                    cmd_to_execute,
                    ["systems_check"],
                    log_to_console,
                    working_directory="/opt/rock-integration-testing/playbooks")
            return OK_RESPONSE

    logger.warn("Perform systems check failed because the Kit configuration was not found in the mongo database.")
    return ERROR_RESPONSE
コード例 #26
0
ファイル: cards.py プロジェクト: davidvon/pipa-pay-server
    def post(self):
        args = request.values
        logger.debug('[ApiCardBuyCommit] in: args[%s]' % args)

        order_id = args.get('orderId')
        order = get_cache_order(order_id)
        if not order:
            logger.warn('[ApiCardBuyCommit] order:%s not exist' % order_id)
            return {'result': 254}

        try:
            order.paid = True
            db.session.add(order)
            db.session.commit()
            logger.info('[ApiCardBuyCommit] order:%s create success' %
                        order_id)
            return {'result': 0}
        except Exception as e:
            logger.error('[ApiCardBuyCommit] order:%s create error:%s' %
                         (order_id, e.message))
            return {'result': 255}
コード例 #27
0
ファイル: cards.py プロジェクト: davidvon/pipa-pay-server
    def post(self):
        args = request.values
        logger.debug('[ApiCardPayCode] in: args[%s]' % args)

        card_id = args['cardId']
        card_code = args['cardCode']
        card = CustomerCard.query.filter_by(card_id=card_id,
                                            card_code=card_code).first()
        if not card:
            logger.warn('[ApiCardPayCode] card[id:%s,code:%s] not exist' %
                        (card_id, card_code))
            return {'result': 255}
        data = {
            'status': card.status,
            'merchantName': card.card.merchant.name,
            'cardName': card.card.title,
            'amount': card.amount,
            'qrcode': cache_qrcode_code(card_id, card_code)
        }
        logger.debug('[ApiCardPayCode] out: result[0] data[%s]' % data)
        return {'result': 0, 'data': data}
コード例 #28
0
def get_node_statuses() -> Response:
    try:
        with KubernetesWrapper(conn_mng) as kube_apiv1:
            api_response = kube_apiv1.list_node()
            ret_val = []
            for item in api_response.to_dict()['items']:                
                try:
                    public_ip = item["metadata"]["annotations"]["flannel.alpha.coreos.com/public-ip"]
                    item["metadata"]["public_ip"] = public_ip
                    ret_val.append(item)
                except KeyError as e:
                    item["metadata"]["public_ip"] = ''
                    ret_val.append(item)
                except Exception as e:
                    logger.warn(item)
                    logger.exception(e)
            return jsonify(ret_val)
    except Exception as e:
        logger.exception(e)

    return jsonify([])
コード例 #29
0
ファイル: note.py プロジェクト: rsanting/PlanarAlly
async def update_note(sid, data):
    sid_data = state.sid_map[sid]
    user = sid_data["user"]
    room = sid_data["room"]
    location = sid_data["location"]

    note = Note.get_or_none(uuid=data["uuid"])

    if not note:
        logger.warning(
            f"{user.name} tried to update non-existant note with id: '{data['uuid']}'"
        )
        return

    if note.user != user:
        logger.warn(f"{user.name} tried to update note not belonging to him/her.")
    else:
        with db.atomic():
            note.title = data["title"]
            note.text = data["text"]
            note.save()
コード例 #30
0
ファイル: cards.py プロジェクト: davidvon/pipa-pay-server
    def post(self):
        args = request.values
        logger.debug('[ApiCardDispatch] in: args[%s]' % args)

        order_id = args.get('order_id')
        try:
            order = Order.query.filter_by(order_id=order_id).first()
            if not order:
                logger.warn('[ApiCardDispatch] order[%s] not exist' % order_id)
                return {"result": 254}

            expire_date = datetime.date.today() + datetime.timedelta(
                365 * 3)  # TODO
            count = CustomerCard.query.filter_by(order_id=order_id).count()
            if count < order.card_count:
                for i in range(count, order.card_count):
                    card = CustomerCard(customer_id=order.customer.openid,
                                        order_id=order_id,
                                        card_id=order.card_id,
                                        amount=order.face_amount,
                                        expire_date=expire_date,
                                        status=0)
                    db.session.add(card)
                db.session.commit()

            output = {
                "result": 0,
                "data": {
                    "count": order.card_count,
                    "amount": order.face_amount
                }
            }
            logger.debug('[ApiCardDispatch] out: return [%s]' % output)
            return output
        except Exception as e:
            logger.error(traceback.print_exc())
            logger.error(
                '[ApiCardDispatch] order[%s] card dispatch exception:[%s]' %
                (order_id, e.message))
            return {'result': 255, 'data': e.message}
コード例 #31
0
ファイル: cards.py プロジェクト: davidvon/pipa-pay-server
    def post(self):
        args = request.values
        logger.debug('[ApiCardShareCheck] in: args[%s]' % args)

        card_id = args['cardId']
        open_id = args['openId']
        card_code = args['cardCode']
        if not card_code:
            logger.warn(
                '[ApiCardShareCheck] openid:%s card[id:%s] not banding' %
                (open_id, card_id))
            return {'result': 254}

        customer_card = CustomerCard.query.filter_by(
            customer_id=open_id, card_id=card_id, card_code=card_code).first()
        if not customer_card:
            logger.warn(
                '[ApiCardShareCheck] openid:%s card[id:%s code:%s] not exist' %
                (open_id, card_id, card_code))
            return {'result': 255}

        if customer_card.status >= 3:
            logger.debug('[ApiCardShareCheck] out: result[0] status[%s]' %
                         customer_card.status)
            return {'result': 0, 'status': customer_card.status}  # 转赠中或已转赠

        data = {
            'result': 0,
            'status': customer_card.status,
            'card': {
                'sign': nonce_str(12),
                'cardId': customer_card.card_id,
                'cardCode': customer_card.card_code,
                'cardName': customer_card.card.title,
                'timestamp': str(int(time.time())),
                'logo': customer_card.card.merchant.logo
            }
        }
        logger.debug('[ApiCardShareCheck] out: return[%s]' % data)
        return data
コード例 #32
0
    def __add_novel_mist_allele(self, mist_marker, allele_seq):
        """
        Add a novel allele to the database with an allele number/name of the
        number of alleles + 1.
        E.g. if there are 10 alleles in for a marker then the novel allele
        will be allele 11.

        Args:
            mist_marker (app.models.MistMarker): :class:`MistMarker` object
                to which the novel allele will be assigned.
            allele_seq (str): Novel allele nucleotide sequence.
        Returns:
            app.models.MistAllele: object of novel allele
        """

        assert isinstance(mist_marker, MistMarker)
        if not isinstance(allele_seq, str):
            logger.warn(
                'allele_seq is NOT isinstance of str for marker {marker}\n{allele_seq}'
                .format(marker=mist_marker.name, allele_seq=allele_seq))
            allele_seq = str(allele_seq)

        new_allele_num = mist_marker.alleles.count() + 1
        mist_allele = MistAllele(name=str(new_allele_num),
                                 seq=allele_seq,
                                 marker=mist_marker,
                                 test=mist_marker.test,
                                 timestamp=datetime.utcnow())
        logger.info(
            'Adding novel allele for marker {0} as allele {1} for test {2}'.
            format(mist_marker.name, new_allele_num, mist_marker.test.name))
        try:
            self.session.add(mist_allele)
            self.session.commit()
        except:
            self.session.rollback()
        mist_allele = mist_marker.alleles.filter_by(seq=allele_seq).first()
        assert isinstance(mist_allele, MistAllele)
        return mist_allele
コード例 #33
0
ファイル: expedition.py プロジェクト: KanColleTool/kcsrv
def expd_result():
    # Horrible bastard code to get the result of the expedition.
    fleet_id = int(request.values.get("api_deck_id")) - 1

    try:
        fleet = g.admiral.fleets[fleet_id]
    except IndexError:
        logger.warn("Fleet does not exist -> {}".format(fleet_id))
        abort(404)
        return

    if not fleet.expedition:
        logger.warn("Fleet not on expedition -> {}".format(fleet))
        abort(400)
        return

    # Similar to the official servers, we calculate everything in expd_result
    # instead of calculating everything in mission. Meaning nobody knows the result of the expedition until this
    # method is called and it's all calculated.

    # Check the timings.
    if fleet.expedition_completed >= time.time() and not fleet.expedition_cancelled:
        logger.warn("Expedition_Completed ({}) >= Current Time ({})".format(fleet.expedition_completed, time.time()))
        # Don't cheat.
        abort(400)
        return

    # What did the fleet look like again?
    res = fleet.expedition.constraints
    assert isinstance(res, dict)

    # Check in order.
    hq_level_min = res.get("hq_level_min", 0)
    required_ships = res.get("required_ships", {})

    # Enter the world's hackiest solution.
    def check_requirements():
        # This inline-function allows us to check the requirements then exit if needed.

        # First, check HQ level.
        if hq_level_min > g.admiral.level:
            return False
        # Next, check ships.
        else:
            min_ships_total = required_ships.get("min_ships_total", 1)
            if len(fleet.kanmusu) < min_ships_total:
                return False
            ship_types = {}
            for kanmusu in fleet.kanmusu:
                if kanmusu.ship.type_ not in ship_types:
                    ship_types[kanmusu.ship.type_] = 0
                ship_types[kanmusu.ship.type_] += 1
            # Check expedition restrictions
            types = required_ships.get("ship_types", {})
            for t, amount in types.items():
                if ship_types.get(t, 0) < amount:
                    return False
        return True

    if not fleet.expedition_cancelled:
        met_requirements = check_requirements()
    else:
        met_requirements = False

    # Update internal state.
    g.admiral.expedition_total += 1
    g.admiral.expeditions.append(fleet.expedition)
    if met_requirements:
        g.admiral.expedition_successes += 1
        g.admiral.experience += 30
        g.admiral.fix_level()

        api_exp_get = []

        # Level up the kanmusus.
        for kanmusu in fleet.kanmusu:
            # Expeditions are not a good way of levelling up
            kanmusu.experience += (kanmusu.level * 3)
            api_exp_get.append(kanmusu.level * 3)
            kanmusu.fix_level()

        # Update resources.
        g.admiral.resources.add(*fleet.expedition.resources_granted.to_list())
    else:
        g.admiral.experience += 5
        g.admiral.fix_level()

        api_exp_get = [0 for _ in fleet.kanmusu]

    # Update ship resource usage.
    for kanmusu in fleet.kanmusu:
        kanmusu.current_fuel = floor((kanmusu.current_fuel -
                                      (kanmusu.current_fuel / (fleet.expedition.resources_used.fuel / 10))))
        kanmusu.current_ammo = floor((kanmusu.current_ammo -
                                      (kanmusu.current_ammo / (fleet.expedition.resources_used.ammo / 10))))
        db.session.add(kanmusu)

    data = {
        "api_ship_id": [-1] + [kanmusu.number for kanmusu in fleet.kanmusu],
        "api_clear_result": int(met_requirements),
        "api_get_exp": 30 if met_requirements else 5 if not fleet.expedition_cancelled else 0,
        "api_member_lv": g.admiral.level,
        "api_member_exp": g.admiral.experience,
        "api_get_ship_exp": api_exp_get,
        "api_get_exp_lvup": [[kanmusu.experience, kanmusu.experience + kanmusu.get_exp_to_level()] for kanmusu in
                             fleet.kanmusu],
        "api_maparea_name": "???",
        "api_detail": "???",
        "api_quest_name": "Expedition {}".format(fleet.expedition.id),
        "api_quest_level": 1,
        "api_get_material": fleet.expedition.resources_granted.to_list() if met_requirements else -1,
        "api_useitem_flag": [
            0,
            0
        ]
    }
    fleet.expedition = None
    fleet.expedition_completed = None
    fleet.expedition_cancelled = None
    db.session.add(fleet)
    db.session.add(g.admiral)
    db.session.commit()
    sv = svdata(data)
    return sv
コード例 #34
0
ファイル: kcsrv.py プロジェクト: KanColleTool/kcsrv
#!/usr/bin/env python3
import logging

from app import app, logger

root = logging.getLogger()
root.setLevel(logging.DEBUG)

logging.getLogger("sqlalchemy.engine").setLevel(logging.INFO)


if __name__ == "__main__":
    logger.warn("This is a debugging configuration. Run with the gunicorn script to run in production.")
    app.run(host="0.0.0.0", debug=True)