Exemple #1
0
def gen(request):
    if request.user.is_staff:
        if not request.POST:
            form = CardForm()
            return render(request, "card/generate.html", locals())
        else:
            form = CardForm(request.POST)
            if form.is_valid():
                card = Card()
                card.name = form.cleaned_data["name"]
                card.value = form.cleaned_data["value"]
                card.long_desc = form.cleaned_data["long_desc"]
                card.active = form.cleaned_data["active"]
                card.issuer = request.user
                card.save()
                record = History(action=1, user=request.user, card=card)
                record.save()
            return render(
                request, "submit.html", {
                    "success": True,
                    "title": "一張卡片就此誕生!",
                    "content": "生成了一張卡片 %s 含有 %d 點" % (card.name, card.value),
                    "next_page": reverse('generate card'),
                })
    else:
        raise PermissionDenied
Exemple #2
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('home'))

    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user.password == form.password.data:
            login_user(user)
            flash(f'berhasil login', 'success')
            return redirect(url_for('home'))
        else:
            flash('Login gagal', 'danger')

    if current_user.is_authenticated:
        aksi = "login"
        Addlog = History(aksi=aksi,
                         user_id=current_user.username,
                         user_ip=request.remote_addr)
        db.session.add(Addlog)
        db.session.commit()
    else:
        aksi = "login"
        username = "******"
        Addlog = History(aksi=aksi,
                         user_id=username,
                         user_ip=request.remote_addr)
        db.session.add(Addlog)
        db.session.commit()
    return render_template('login.html', title='Login', form=form)
Exemple #3
0
def gen(request):
    if request.user.is_staff:
        if not request.POST:
            form = CardForm()
            return render(request, "card/generate.html", locals())
        else:
            form = CardForm(request.POST)
            if form.is_valid():
                card = Card()
                card.name = form.cleaned_data["name"]
                card.value = form.cleaned_data["value"]
                card.long_desc = form.cleaned_data["long_desc"]
                card.active = form.cleaned_data["active"]
                card.issuer = request.user
                card.save()
                record = History(action=1, user=request.user, card=card)
                record.save()
            return render(
                request, "submit.html", {
                    "success": True,
                    "title": "一張卡片就此誕生!",
                    "content": "生成了一張卡片 %s 含有 %d 點" % (card.name, card.value),
                    "next_page": reverse('generate card'),
                })
    else:
        raise PermissionDenied
Exemple #4
0
def gen(request):
    if request.user.has_perm('app.add_card'):
        # only teamleader can use
        if not request.POST:
            form = CardForm()
            return render(request, "card/generate.html", locals())
        else:
            form = CardForm(request.POST)
            if form.is_valid():
                with transaction.atomic():
                    card = Card()
                    card.name = form.cleaned_data["name"]
                    card.value = form.cleaned_data["value"]
                    card.long_desc = form.cleaned_data["long_desc"]
                    card.active = form.cleaned_data["active"]
                    card.issuer = request.user
                    card.save()
                    record = History(action=1, user=request.user, card=card)
                    record.save()
                return render(
                    request, "submit.html", {
                        "success": True,
                        "title": "一張卡片就此誕生!",
                        "content": "生成了一張卡片 %s 含有 %d 點" % (card.name, card.value),
                        "next_page": reverse('view card', args=[card.cid]),
                    })
            else:
                return render(request, "submit.html", {
                    "success": False,
                    "title": "產生卡片失敗",
                    "content": "要不要去戳戳系統管理員呢?"
                    "(如果是POST奇怪的資料,可能會收到彈力繩喔ˊ_>ˋ)"
                })
    else:
        raise PermissionDenied
Exemple #5
0
def domain_management(domain_name):
    """Route to manage domain attributes."""
    if request.method == 'GET':
        domain = Domain.query.filter(Domain.name == domain_name).first()
        if not domain:
            return redirect(url_for('error', code=404))
        users = User.query.all()

        # get list of user ids to initilize selection data
        d = Domain(name=domain_name)
        domain_user_ids = d.get_user()

        return render_template('domain_management.html', domain=domain, users=users, domain_user_ids=domain_user_ids)

    if request.method == 'POST':
        # username in right column
        new_user_list = request.form.getlist('domain_multi_user[]')

        # get list of user ids to compare
        d = Domain(name=domain_name)
        domain_user_ids = d.get_user()

        # grant/revoke user privielges
        d.grant_privielges(new_user_list)

        history = History(msg='Change domain %s access control' % domain_name,
                          detail=str({'user_has_access': new_user_list}), created_by=current_user.username)
        history.add()

        return redirect(url_for('domain_management', domain_name=domain_name))

    return None
Exemple #6
0
def domain_add():
    """Route to add a Domain."""
    # pylint: disable=R0914,R0912,
    # here here here
    if request.method == 'POST':
        try:
            domain_name = request.form.getlist('domain_name')[0]
            domain_type = request.form.getlist('radio_type')[0]
            soa_edit_api = request.form.getlist('radio_type_soa_edit_api')[0]

            if ' ' in domain_name or not domain_name or not domain_type:
                return render_template('errors/400.html', msg="Please correct your input"), 400

            if domain_type == 'slave':
                if request.form.getlist('domain_master_address'):
                    domain_master_string = request.form.getlist('domain_master_address')[0]
                    domain_master_string = domain_master_string.replace(' ', '')
                    domain_master_ips = domain_master_string.split(',')
            else:
                domain_master_ips = []
            d = Domain()
            result = d.add(domain_name=domain_name, domain_type=domain_type, soa_edit_api=soa_edit_api,
                           domain_master_ips=domain_master_ips)

            # The soa record will show a.misconfigured.powerdns.server
            rec = Record()
            recs = rec.get_record_data('pop')
            soacontent = None
            nsrecords = None
            nscontent = None
            for item in recs['records']:
                if item['name'] == 'pop' and item['type'] == 'SOA':
                    soacontent = item['content']
                if item['type'] == 'NS':
                    nsrecords = item['records']
                    nscontent = item['content']

            if soacontent:
                soarec = Record(name=domain_name, type='SOA', ttl=3600)
                soarec.update(domain_name, soacontent, username=current_user.username)
            if nsrecords and nscontent:
                for nsrec in nsrecords:
                    nsrec_ = Record(name=domain_name, type='NS', ttl=3600)
                    nsrec_.update(domain_name, nsrec['content'], username=current_user.username)
            # end update the record using pop as a base
            if result['status'] == 'ok':
                history = History(msg='Add domain %s' % domain_name,
                                  detail=str({'domain_type': domain_type, 'domain_master_ips': domain_master_ips}),
                                  created_by=current_user.username)
                history.add()
                return redirect(url_for('dashboard'))
            else:
                return render_template('errors/400.html', msg=result['msg']), 400
        except Exception:
            return redirect(url_for('error', code=500))
    return render_template('domain_add.html')
Exemple #7
0
 def setUp(self):
     self.history = [History(date=datetime.datetime(2018, 5, 4), open=125.21, high=126.84, low=124.71,
                                  close=125.53, volume=5400810, ticker_id=1),
                          History(date=datetime.datetime(2018, 5, 7), open=126.59, high=128.4, low=124.44,
                                  close=124.94, volume=6999937, ticker_id=1),
                          History(date=datetime.datetime(2018, 5, 8), open=124.93, high=126.75, low=123.63,
                                  close=126.57, volume=8882661, ticker_id=1),
                          History(date=datetime.datetime(2018, 5, 9), open=128.42, high=130.42, low=128.085,
                                  close=128.72, volume=11395850, ticker_id=1)
                          ]
Exemple #8
0
def reset(uid, sid, e_msg):
    """
    Checks in all licences on error.
    :param uid: User ID
    :param sid: Server ID
    :param e_msg: Error message
    """
    Product.reset(sid)
    History.reset(sid)
    Updates.end(uid, 'ERROR', e_msg)
Exemple #9
0
def domain_delete(domain_name):
    """Route to delete a domain."""
    d = Domain()
    result = d.delete(domain_name)

    if result['status'] == 'error':
        return redirect(url_for('error', code=500))

    history = History(msg='Delete domain %s' % domain_name, created_by=current_user.username)
    history.add()

    return redirect(url_for('dashboard'))
Exemple #10
0
def check_year(server_id):
    """
    lmutil.exe does not provide a year with license data, this is a work-around to account for that. Checks in
    all licences if there is a difference between current year and the year of any checked out licenses.
    :param server_id: Id of server
    """
    checked_out = History.time_in_none(server_id)
    for r in checked_out:
        if datetime.now().year != r.time_out.year:
            Product.reset(server_id)
            History.reset(server_id)
            break
Exemple #11
0
def edit(request, id=None):
    if request.user.has_perm('app.change_card'):
        try:
            card = Card.objects.get(cid=id)
        except ObjectDoesNotExist:
            return CardNotFound(request)

        if not request.POST:
            form = CardForm({
                "name": card.name,
                "value": card.value,
                "long_desc": card.long_desc,
                "active": card.active,
                "retrieved": card.retrieved
            })
            return render(request, "card/edit.html", locals())

        else:
            form = CardForm(request.POST)
            if form.is_valid():
                action = 2
                if card.active is not form.cleaned_data["active"]:
                    if form.cleaned_data["active"]:
                        action = 4
                    else:
                        action = 3
                with transaction.atomic():
                    card.name = form.cleaned_data["name"]
                    card.value = form.cleaned_data["value"]
                    card.long_desc = form.cleaned_data["long_desc"]
                    card.active = form.cleaned_data["active"]
                    card.save()
                    record = History(action=action,
                                     user=request.user,
                                     card=card)
                    record.save()
                return render(
                    request, "submit.html", {
                        "success": True,
                        "title": "成功編輯",
                        "content": "成功編輯卡片 %s" % card.name,
                        "next_page": reverse('view card', args=[card.cid]),
                    })
            else:
                # invalid value in form
                return render(
                    request, "submit.html", {
                        "success": True,
                        "title": "編輯失敗",
                        "next_page": reverse('edit card', id),
                    })
    else:
        raise PermissionDenied
Exemple #12
0
def addToHistory(track, user):
    history = History()
    history.track = track
    history.save()
    if UserHistory.objects.filter(user=user).count() == 0:
        userHistory = UserHistory(user=user)
        userHistory.save()
        userHistory.histories.add(history)
    # Adding to existing history
    else:
        userHistory = UserHistory.objects.get(user=user)
        userHistory.save()
        userHistory.histories.add(history)
Exemple #13
0
def get(request, id=None):
    if not request.user.is_authenticated():
        # Anonymous User
        return render(request,
                      "submit.html", {
                          "success": False,
                          "content": "你可能需要先掃描一下識別證上的 QR_Code 來登入系統",
                          "title": "未登入!"
                      },
                      status=403)
    elif request.user.has_perm('app.get_card'):
        # player
        try:
            card = Card.objects.get(cid=id)
        except ObjectDoesNotExist:
            return CardNotFound(request)

        if not card.retrieved and card.active:
            # Add points
            with transaction.atomic():
                player = request.user.player
                player.captured_card.add(card)
                player.save()
                card.retrieved = True
                card.save()
                record = History(action=10, user=request.user, card=card)
                record.save()
            abscardvalue = abs(card.value)
            return render(request, "card/get.html", locals())
        elif not card.active:
            return render(
                request, "submit.html", {
                    "success": False,
                    "title": "卡片已被失效",
                    "content": "這張卡片已經被使註銷囉,何不換張卡片呢?",
                })
        else:
            return render(
                request, "submit.html", {
                    "success": False,
                    "title": "卡片已被捕獲",
                    "content": "這張卡片已經被使用過囉,何不換張卡片呢?",
                })
    else:
        # user without permission of capturing a card
        # worker and teamleader
        return render(request, "submit.html", {
            "success": False,
            "title": "工人是不能領卡的",
            "content": "工人是不能領卡的,下去領五百。",
        })
Exemple #14
0
def get(request, id=None):
    if not request.user.is_authenticated():
        # Anonymous User
        return render(
            request, "submit.html", {
                "success": False,
                "content": "你可能需要先掃描一下識別證上的 QR_Code 來登入系統",
                "title": "未登入!"}, status=403)
    elif request.user.has_perm('app.get_card'):
        # player
        try:
            card = Card.objects.get(cid=id)
        except ObjectDoesNotExist:
            return CardNotFound(request)

        if not card.retrieved and card.active:
            # Add points
            with transaction.atomic():
                player = request.user.player
                player.captured_card.add(card)
                player.save()
                card.retrieved = True
                card.save()
                record = History(action=10, user=request.user, card=card)
                record.save()
            abscardvalue = abs(card.value)
            return render(
                request, "card/get.html", locals())
        elif not card.active:
            return render(
                request, "submit.html", {
                    "success": False,
                    "title": "卡片已被失效",
                    "content": "這張卡片已經被使註銷囉,何不換張卡片呢?",
                })
        else:
            return render(
                request, "submit.html", {
                    "success": False,
                    "title": "卡片已被捕獲",
                    "content": "這張卡片已經被使用過囉,何不換張卡片呢?",
                })
    else:
        # user without permission of capturing a card
        # worker and teamleader
        return render(
            request, "submit.html", {
                "success": False,
                "title": "工人是不能領卡的",
                "content": "工人是不能領卡的,下去領五百。",
            })
Exemple #15
0
def api_login_delete_zone(domain_name):
    pdns_api_url = Setting().get('pdns_api_url')
    pdns_api_key = Setting().get('pdns_api_key')
    pdns_version = Setting().get('pdns_version')
    api_uri_with_prefix = utils.pdns_api_extended_uri(pdns_version)
    api_full_uri = api_uri_with_prefix + '/servers/localhost/zones'
    api_full_uri += '/' + domain_name
    headers = {}
    headers['X-API-Key'] = pdns_api_key

    domain = Domain.query.filter(Domain.name == domain_name)

    if not domain:
        abort(404)

    if g.user.role.name not in ['Administrator', 'Operator']:
        user_domains_obj_list = g.user.get_domains()
        user_domains_list = [item.name for item in user_domains_obj_list]

        if domain_name not in user_domains_list:
            raise DomainAccessForbidden()

    msg_str = "Sending request to powerdns API {0}"
    logging.debug(msg_str.format(domain_name))

    try:
        resp = utils.fetch_remote(
            urljoin(pdns_api_url, api_full_uri),
            method='DELETE',
            headers=headers,
            accept='application/json; q=1'
        )

        if resp.status_code == 204:
            logging.debug("Request to powerdns API successful")

            history = History(
                msg='Delete domain {0}'.format(domain_name),
                detail='',
                created_by=g.user.username
            )
            history.add()

            domain = Domain()
            domain.update()
    except Exception as e:
        logging.error('Error: {0}'.format(e))
        abort(500)

    return resp.content, resp.status_code, resp.headers.items()
Exemple #16
0
def edit(request, id=None):
    if request.user.has_perm('app.change_card'):
        try:
            card = Card.objects.get(cid=id)
        except ObjectDoesNotExist:
            return CardNotFound(request)

        if not request.POST:
            form = CardForm(
                {"name": card.name,
                 "value": card.value,
                 "long_desc": card.long_desc,
                 "active": card.active,
                 "retrieved": card.retrieved})
            return render(request, "card/edit.html", locals())

        else:
            form = CardForm(request.POST)
            if form.is_valid():
                action = 2
                if card.active is not form.cleaned_data["active"]:
                    if form.cleaned_data["active"]:
                        action = 4
                    else:
                        action = 3
                with transaction.atomic():
                    card.name = form.cleaned_data["name"]
                    card.value = form.cleaned_data["value"]
                    card.long_desc = form.cleaned_data["long_desc"]
                    card.active = form.cleaned_data["active"]
                    card.save()
                    record = History(action=action, user=request.user, card=card)
                    record.save()
                return render(
                    request, "submit.html", {
                        "success": True,
                        "title": "成功編輯",
                        "content": "成功編輯卡片 %s" % card.name,
                        "next_page": reverse('view card', args=[card.cid]),
                    })
            else:
                # invalid value in form
                return render(
                    request, "submit.html", {
                        "success": True,
                        "title": "編輯失敗",
                        "next_page": reverse('edit card', id),
                    })
    else:
        raise PermissionDenied
Exemple #17
0
def feed(request, id=None):
    if request.user.has_perm('app.feed_card'):
        try:
            card = Card.objects.get(cid=id)
        except ObjectDoesNotExist:
            return CardNotFound(request)

        if card.retrieved:
            return render(
                request, "submit.html", {
                    "success": False,
                    "title": "卡片已被捕獲",
                    "content": "這張卡片已經被使用過囉,何不換張卡片呢?",
                })
        else:
            if request.method == 'GET':
                form = FeedForm()
                return render(request, "card/feed.html", locals())
            else:
                form = FeedForm(request.POST)
                if form.is_valid():
                    with transaction.atomic():
                        player = form.cleaned_data["player"]
                        card.retrieved = True
                        card.active = True
                        card.capturer = player
                        card.save()
                        record_reciever = History(action=0xfeed,
                                                  user=player.user,
                                                  card=card,
                                                  comment="從 %s 收到一張卡片" %
                                                  request.user.get_full_name())
                        record_reciever.save()
                        record_sender = History(action=0xfeed,
                                                user=request.user,
                                                card=card,
                                                comment="給了 %s (%s)" %
                                                (player.user.get_full_name(),
                                                 player.user.username))
                        record_sender.save()
                    return render(
                        request, "submit.html", {
                            "success":
                            True,
                            "title":
                            "成功發送卡片",
                            "content":
                            "成功將卡片送給 %s 了!" % player.user.get_full_name(),
                        })
                else:
                    return render(
                        request, "submit.html", {
                            "success": False,
                            "title": "發送卡片失敗",
                            "content": "要不要去戳戳系統管理員呢?"
                        })
    else:
        raise PermissionDenied
Exemple #18
0
def issuing_bays():
    # Initialized form for bays issuing
    form = HistoryForm()
    if request.method == 'POST' and form.validate_on_submit():
        sap = SapNumber.query.filter_by(
            sap_number=request.form.get("sap_number")).all()
        for el in sap:
            sap_id = el.id
        History.create(sap_number=sap_id,
                       dpn=request.form.get("dpn"),
                       serial_number=request.form.get("serial_number"),
                       status=StatusEnum.ok)
        flash("Бухта видана успішно!", 'success')
        #sweetify.success(request, 'You did it', text='Good job! Бухта видана успішно!', persistent='Hell yeah')
        return redirect(url_for('main.issuing_bays'))
    return render_template('history.html', form=form)
Exemple #19
0
def calculation(first_cur, how_m, second_cur, user_id):
    """
    Method for working with transferred data for currency calculation
    :param first_cur:  # first abbreviation
    :param second_cur: # second abbreviation
    :param how_m: # transfer amount
    :param user_id: # Id of user
    :return: # get the answer
    """

    first = Money.query.filter_by(abbreviation=first_cur).first()
    second_money = Money.query.filter_by(abbreviation=second_cur).first()

    # Based on if the first currency BYN
    if first_cur.upper() == 'BYN':
        total = round(how_m / second_money.price * second_money.cur_scale, 2)

    # Based on if the second currency BYN
    elif second_cur.upper() == 'BYN':
        total = round(first.price / first.cur_scale * how_m, 2)

    else:
        total = round(
            first.price / first.cur_scale * how_m /
            (second_money.price / second_money.cur_scale), 2)

    history = History(first_currency=first_cur.upper(),
                      how_much=how_m,
                      second_currency=second_cur.upper(),
                      total=total,
                      user_id=user_id)
    db.session.add(history)
    db.session.commit()

    return total
Exemple #20
0
    def process_page(self, url):
        response = requests.get(url, headers=self.headers)

        if response.status_code != 200:
            print('Bad response')
            return

        soup = bs(response.content, "html.parser")
        data_container = soup.find("div", {"id": "historicalContainer"})
        data_table = data_container.find("table").find("tbody")
        rows = data_table.find_all("tr")[1:]

        for row in rows:
            cells = row.find_all("td")
            date = self.convert_to_datetime(cells[0].text.strip())
            open = self.convert_to_float(cells[1].text)
            high = self.convert_to_float(cells[2].text)
            low = self.convert_to_float(cells[3].text)
            close = self.convert_to_float(cells[4].text)
            volume = self.convert_to_int(cells[5].text)

            history_obj = History(date=date,
                                  open=open,
                                  high=high,
                                  low=low,
                                  close=close,
                                  volume=volume,
                                  ticker_id=self.ticker_id)
            save_to_db(history_obj)
Exemple #21
0
 def post(self, request):
     shape = None
     try:
         data = json.loads(
             request.body.decode('utf-8')).get('data').split(',')[1]
     except:
         raise BadRequest('bad_json')
     data_decoded = base64.b64decode(data)
     image = Image.open(ios.BytesIO(data_decoded))
     ar = numpy.array(image)
     dets = DETECTOR(ar, 1)
     for k, d in enumerate(dets):
         shape = SP(ar, d)
     if shape:
         desc = FACEREC.compute_face_descriptor(ar, shape)
         persons = Person.objects.all()
         for p in persons:
             if p.descriptor:
                 p_desc = np.fromstring(p.descriptor, sep='\n')
                 a = distance.euclidean(desc, p_desc)
                 if a < 0.5:
                     History(person=p, time=datetime.now()).save()
                     return {
                         'person': p.name,
                     }
     return {'status': False}
Exemple #22
0
def send():
    form = SubmitBookForm()

    if form.validate_on_submit():
        title = Books(title=form.title.data,
                      author=form.author.data,
                      pages=form.pages.data,
                      cost=form.cost.data,
                      description=form.description.data,
                      status=True,
                      sender=current_user)
        db.session.add(title)
        db.session.commit()

        title2 = History(title=form.title.data,
                         author=form.author.data,
                         pages=form.pages.data,
                         cost=form.cost.data,
                         type=True,
                         exchanger=current_user)
        db.session.add(title2)
        db.session.commit()

        flash("Your book was accepted, drop the book off at Aula 1p")
        return redirect(url_for('send'))
    return render_template('send.html',
                           title='Submit your old book',
                           form=form)
Exemple #23
0
def logout():
    aksi = "/logout"
    Addlog = History(aksi=aksi,
                     user_id=current_user.username,
                     user_ip=request.remote_addr)
    db.session.add(Addlog)
    db.session.commit()
    logout_user()
    return redirect(url_for('home'))
def store_db(symbol, rows):
    """
    store data in database
    """

    datetime_format = '%b %d %Y'

    # clear data of this coin in database
    pass

    store_rows = []
    for row in rows:
        clean_data(row)

        date = datetime.datetime.strptime(row[0], datetime_format)
        open = float(row[1]) if row[1] else None
        high = float(row[2]) if row[2] else None
        low = float(row[3]) if row[3] else None
        close = float(row[4]) if row[4] else None
        volume = float(row[5]) if row[5] else None
        market_cap = float(row[6]) if row[6] else None
        average = float(row[7]) if row[7] else None
        print('%s %s' % (date, symbol))
        store_rows.append({
            'date': date,
            'symbol': symbol,
            'open': open,
            'high': high,
            'low': low,
            'close': close,
            'volume': volume,
            'market_cap': market_cap,
            'average': average
        })
    if store_rows:
        History.insert_many(store_rows)
        # currency = Currency.find_one({"symbol", symbol})
        mdb.db.currencies.update(
            {"symbol": symbol},
            {"$set": {
                "historyUpdateDate": datetime.datetime.now()
            }})
    else:
        return
Exemple #25
0
def create_history(song):
    app.logger.info('Creating history')

    # create history
    history = History(song)
    db.session.add(history)

    db.session.commit()

    return history
Exemple #26
0
def upload_file():
    # check if the post request has the file part
    form = UploadForm()
    if form.validate_on_submit():
        file = request.files['photo']
        ext = file.filename.rsplit('.', 1)[1]
        timestr = time.strftime("%Y%m%d-%H%M%S")
        today = dater.date.today()
        todaystr = today.isoformat()
        nam = timestr + "." + ext
        filename = images.save(file, folder=todaystr, name=nam)
        file_url = images.url(filename)
        print(file_url)

        # Save to database
        upload = History(photo=filename,
                         patient=form.patient.data,
                         photo_url=file_url,
                         user_email=current_user.email)
        db.session.add(upload)
        db.session.commit()

        # Decoding and pre-processing base64 image
        img = load(file)

        # Creating payload for TensorFlow serving request
        data = json.dumps({
            "signature_name": "serving_default",
            "instances": img.tolist()
        })
        print('Data: {} ... {}'.format(data[:50], data[len(data) - 52:]))

        # Making POST request
        # headers = {"content-type": "application/json"}
        # json_response = requests.post(
        #     'http://localhost:8501/v1/models/pneu_model:predict', data=data, headers=headers)

        # Decoding results from TensorFlow Serving server
        # predictions = json.loads(json_response.text)['predictions']
        # print(predictions)

        # Returning JSON response to the frontend
        # return jsonify(inception_v3.decode_predictions(np.array(pred['predictions']))[0])
        flash(img.shape)
        # return redirect(url_for("dashboard", extracted_text=img.shape, img_src=names))
        return redirect(url_for("dashboard"))
    if current_user.photo == None:
        return render_template('dashboard.html', form=form)
    file_url = photos.url(current_user.photo)
    image_count = History.query.filter().order_by(
        History.timestamp.desc()).count()
    return render_template("dashboard.html",
                           form=form,
                           file_url=file_url,
                           image_count=image_count)
Exemple #27
0
def api_login_create_zone():
    pdns_api_url = Setting().get('pdns_api_url')
    pdns_api_key = Setting().get('pdns_api_key')
    pdns_version = Setting().get('pdns_version')
    api_uri_with_prefix = utils.pdns_api_extended_uri(pdns_version)
    api_full_uri = api_uri_with_prefix + '/servers/localhost/zones'
    headers = {}
    headers['X-API-Key'] = pdns_api_key

    msg_str = "Sending request to powerdns API {0}"
    msg = msg_str.format(request.get_json(force=True))
    logging.debug(msg)

    resp = utils.fetch_remote(
        urljoin(pdns_api_url, api_full_uri),
        method='POST',
        data=request.get_json(force=True),
        headers=headers,
        accept='application/json; q=1'
    )

    if resp.status_code == 201:
        logging.debug("Request to powerdns API successful")
        data = request.get_json(force=True)

        history = History(
            msg='Add domain {0}'.format(data['name'].rstrip('.')),
            detail=json.dumps(data),
            created_by=g.user.username
        )
        history.add()

        if g.user.role.name not in ['Administrator', 'Operator']:
            logging.debug("User is ordinary user, assigning created domain")
            domain = Domain(name=data['name'].rstrip('.'))
            domain.update()
            domain.grant_privileges([g.user.username])

        domain = Domain()
        domain.update()

    return resp.content, resp.status_code, resp.headers.items()
Exemple #28
0
def order():
    flag, total_amount, time_taken = 0, 0, 0
    t = time_correction()
    if request.method == 'POST':
        dishes = Quantity.query.filter_by(customer=current_user).all()
        for dish in dishes:
            if dish.quantity != 0:
                if flag == 0:
                    flash("Your order is:")
                    recent_order = RecentOrders(
                        customer=current_user,
                        timestamp=(datetime.now() - timedelta(minutes=330)))
                    history = History(customer=current_user,
                                      timestamp=(datetime.now() -
                                                 timedelta(minutes=330)),
                                      recent_order=recent_order)
                    db.session.add(recent_order)
                    db.session.add(history)
                    flag = 1
                time_taken += int(dish.dish.timetaken) * int(dish.quantity)
                total_amount += int(dish.dish.amount) * int(dish.quantity)
                order = Orders(history=history,
                               quantity=dish.quantity,
                               dish=dish.dish)
                db.session.add(order)
                flash("{} {} Rs.{}".format(dish.quantity, dish.dish.dishname,
                                           dish.quantity * dish.dish.amount))
                flash("Total amount is Rs.{}".format(total_amount))
                dish.quantity = 0

        if flag == 0:
            flash("Please select a dish.")
        else:
            user_email = current_user.email
            Thread(target=notification,
                   args=(app, t + time_taken, user_email)).start()

            recent_order.timestamp += timedelta(minutes=(t + time_taken))
            history.total_amount = total_amount
            app.config['WAIT_TIME'] += time_taken
            db.session.commit()
    return redirect(url_for('index'))
Exemple #29
0
def feed(request, id=None):
    if not request.user.is_staff:
        raise PermissionDenied
    else:
        try:
            user = User.objects.get(username=id)
        except ObjectDoesNotExist:
            return render(
                request, "submit.html", {
                    "content": "你是誰?",
                    "title": "錯誤!"}, status=404)

        if not is_player(user):
            return render(
                request, "submit.html", {
                    "content": "工作人員的世界你是看不到的!",
                    "title": "錯誤!"}, status=404)
        else:
            if not request.POST:
                form = FeedForm()
                return render(request, "player/feed.html", locals())
            else:
                form = FeedForm(request.POST)
                if form.is_valid():
                    player = user.player
                    card = form.cleaned_data["card"]
                    player.captured_card.add(card)
                    player.save()
                    card.retrieved = True
                    card.save()
                    record = History(action=0xfeed, user=request.user, card=card,
                                     comment="給" + user.get_full_name() + " (" + user.username + ")")
                    record.save()
                    card.save()

                    return render(
                        request, "submit.html", {
                            "title": "成功發送",
                            "content": "你送給 %s 一張卡片" % player.user.get_full_name(),
                        })
                else:
                    return render(request, "player/feed.html", locals())
Exemple #30
0
def get(request, id=None):
    if not is_player(request.user):
        return render(request,
                      "submit.html", {
                          "success": False,
                          "content": "你可能需要先掃描一下識別證上的 QR_Code 來登入系統",
                          "title": "未登入!"
                      },
                      status=404)
    else:
        try:
            card = Card.objects.get(cid=id)
        except ObjectDoesNotExist:
            return CardNotFound(request)

        if is_player(request.user):
            if not card.retrieved or card.active:
                # Add points
                player = request.user.player
                player.captured_card.add(card)
                player.save()
                card.retrieved = True
                card.save()
                record = History(action=10, user=request.user, card=card)
                record.save()
            else:
                return render(
                    request, "submit.html", {
                        "success": False,
                        "title": "卡片已被捕獲",
                        "content": "這張卡片已經被使用過囉,何不換張卡片呢?",
                    })

            return render(
                request, "submit.html", {
                    "success": True,
                    "title": "恭喜獲得 %d 點" % card.value,
                    "content": "從 %s 中得到了 %d 點" % (card.name, card.value),
                    "next_page": reverse('home')
                })
        else:
            raise PermissionDenied
Exemple #31
0
def home():
    user = User.query.all()
    post = Post.query.order_by(desc(Post.id))

    if current_user.is_authenticated:
        aksi = "home"
        Addlog = History(aksi=aksi,
                         user_id=current_user.username,
                         user_ip=request.remote_addr)
        db.session.add(Addlog)
        db.session.commit()
    else:
        aksi = "home"
        username = "******"
        Addlog = History(aksi=aksi,
                         user_id=username,
                         user_ip=request.remote_addr)
        db.session.add(Addlog)
        db.session.commit()
    return render_template('home.html', user=user, posts=post)
Exemple #32
0
def post(title):
    page = request.args.get('page', 1, type=int)
    post = Post.query.filter_by(title=title).first()
    id = post.id
    pagination = Comment.query.filter_by(post_id=id).order_by(Comment.comment_time).paginate(page, per_page=current_app.config['FLASK_PER_PAGE'], error_out=True)
    comments = pagination.items

    # 评论 and 回复
    form = CommentForm()
    if form.validate_on_submit():
        platform = request.user_agent.platform
        browser = request.user_agent.browser
        if len(form.parent_id.data) == 0:
            comment = Comment(post_id=id, user_name=form.user_name.data, email=form.email.data, website=form.website.data,
                            comment=form.comment.data, platform=platform, browser=browser, comment_time=datetime.now())
        else:
            comment_parent = Comment.query.filter_by(id=int(form.parent_id.data)).first()
            if comment_parent is not None:
                regx_user = regx_user_name(comment_parent.user_name,form.comment.data)
                if regx_user is not None:
                    comment = Comment(post_id=id, user_name=form.user_name.data, email=form.email.data, website=form.website.data,
                            comment=form.comment.data, platform=platform, browser=browser, comment_time=datetime.now(),parent=comment_parent)
                    msg = "回复成功!"
                    send_email(comment_parent.email,'评论回复','mail/comment',comment=comment,post=post)

        db.session.add(comment)
        try:
            db.session.commit()
            flash("评论成功!")
        except Exception as e:
            db.session.rollback()
            print(e)
            flash("数据库提交失败!")
        flash(msg)
        return redirect(url_for('main.post', title=title))
    
    post = Post.query.filter_by(id=id).first()
    postview = PostView.query.filter_by(post_id=id, visit_date=time.strftime(
        '%Y-%m-%d', time.localtime(time.time()))).first()
    if postview is None:
        postview = PostView(post_id=id, views=1, visit_date=time.strftime(
            '%Y-%m-%d', time.localtime(time.time())))
    else:
        postview.views += 1
    history = History(ip=request.remote_addr, post_id=id, platform=request.user_agent.platform,
                      browser=request.user_agent.browser, visit_time=datetime.now())
    db.session.add(history)
    db.session.add(postview)
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print(e)
    return render_template('post.html', current_user=current_user, post=post, comments=comments, form=form, pagination=pagination, title=title)
Exemple #33
0
def post(title):
    page = request.args.get('page', 1, type=int)
    post = Post.query.filter_by(title=title).first()
    id = post.id
    pagination = Comment.query.filter_by(post_id=id).order_by(
        Comment.comment_time.desc()).paginate(
            page,
            per_page=current_app.config['FLASK_PER_PAGE'],
            error_out=True)
    comments = pagination.items
    form = CommentForm()
    if form.validate_on_submit():
        platform = request.user_agent.platform
        browser = request.user_agent.browser
        comment = Comment(post_id=id,
                          user_name=form.user_name.data,
                          email=form.email.data,
                          website=form.website.data,
                          comment=form.comment.data,
                          platform=platform,
                          browser=browser,
                          comment_time=datetime.now())
        db.session.add(comment)
        db.session.commit()
        flash("评论成功!")
        return redirect(url_for('main.post', title=title))
    post = Post.query.filter_by(id=id).first()
    postview = PostView.query.filter_by(
        post_id=id,
        visit_date=time.strftime('%Y-%m-%d',
                                 time.localtime(time.time()))).first()
    if postview is None:
        postview = PostView(post_id=id,
                            views=1,
                            visit_date=time.strftime(
                                '%Y-%m-%d', time.localtime(time.time())))
    else:
        postview.views += 1
    history = History(ip=request.remote_addr,
                      post_id=id,
                      platform=request.user_agent.platform,
                      browser=request.user_agent.browser,
                      visit_time=datetime.now())
    db.session.add(history)
    db.session.add(postview)
    db.session.commit()
    return render_template('post.html',
                           current_user=current_user,
                           post=post,
                           comments=comments,
                           form=form,
                           pagination=pagination,
                           title=title)
 def create(self, request, *args, **kwargs):
     account = request.data["params"]["account"]
     newsID = request.data["params"]["newsID"]
     try:
         newRecord = History(
             account=account,
             newsID=newsID,
         )
         newRecord.save()
         return JsonResponse({
             "status": 0,
             "mes": "success",
             "data": {
                 "id": newRecord.id
             }
         })
     except:
         return JsonResponse({
             "status": 1,
             "mes": "fail",
         })
Exemple #35
0
def get(request, id=None):
    if not is_player(request.user):
        return render(
            request, "submit.html", {
                "success": False,
                "content": "你可能需要先掃描一下識別證上的 QR_Code 來登入系統",
                "title": "未登入!"}, status=404)
    else:
        try:
            card = Card.objects.get(cid=id)
        except ObjectDoesNotExist:
            return CardNotFound(request)

        if is_player(request.user):
            if not card.retrieved or card.active:
                # Add points
                player = request.user.player
                player.captured_card.add(card)
                player.save()
                card.retrieved = True
                card.save()
                record = History(action=10, user=request.user, card=card)
                record.save()
            else:
                return render(
                    request, "submit.html", {
                        "success": False,
                        "title": "卡片已被捕獲",
                        "content": "這張卡片已經被使用過囉,何不換張卡片呢?",
                        })

            return render(
                request, "submit.html", {
                    "success": True,
                    "title": "恭喜獲得 %d 點" % card.value,
                    "content": "從 %s 中得到了 %d 點" % (card.name, card.value),
                    "next_page": reverse('home')
                })
        else:
            raise PermissionDenied
Exemple #36
0
def get(request, id=None):
    if user_permission(request.user) == 0:
        # Anonymous User
        return render(
            request, "submit.html", {
                "success": False,
                "content": "你可能需要先掃描一下識別證上的 QR_Code 來登入系統",
                "title": "未登入!"}, status=404)
    elif user_permission(request.user) == 1:
        # player   
        try:
            card = Card.objects.get(cid=id)
        except ObjectDoesNotExist:
            return CardNotFound(request)

        if not card.retrieved and card.active:
            # Add points
            with transaction.atomic():
                player = request.user.player
                player.captured_card.add(card)
                player.save()
                card.retrieved = True
                card.save()
                record = History(action=10, user=request.user, card=card)
                record.save()
            abscardvalue = abs(card.value)
            return render(
                request, "card/get.html", locals())
        else:
            return render(
                request, "submit.html", {
                    "success": False,
                    "title": "卡片已被捕獲",
                    "content": "這張卡片已經被使用過囉,何不換張卡片呢?",
                })
    elif user_permission(request.user) > 1:
        # worker and teamleader
        return redirect('view card', card.cid)
    else:
        raise PermissionDenied
Exemple #37
0
def lite(request, tt=None):
    denomination = [32, 64, 128, 256, -128, -32, -64]
    if user_permission(request.user) < 2:
        raise PermissionDenied
    if tt is not None:
        try:
            tt = int(tt)
        except:
            return render(
                request, "submit.html", {
                    "success": False,
                    "title": "發送卡片失敗",
                    "content": "我幫你綁好繩子了,"
                    "你要自己跳還是我推你跳呢?(本繩載重20g)"})
        if tt not in range(0, len(denomination)):
            return render(
                request, "submit.html", {
                    "success": False,
                    "title": "發送卡片失敗",
                    "content": "要不要去戳戳系統管理員呢?"
                    "(如果是POST奇怪的資料,可能會收到彈力繩喔ˊ_>ˋ)"
                })
        with transaction.atomic():
            card = Card()
            present = request.user.first_name
            if present == "":
                present = '祝福'
            card.name = "來自 %s 的%s" % (request.user.last_name, present)
            card.value = denomination[tt]
            card.active = True
            card.retrieved = False
            card.issuer = request.user
            card.save()
            record = History(action=1, user=request.user, card=card)
            record.save()
        return redirect('view card', card.cid)
    else:
        return render(request, 'staff/lite.html',locals())
Exemple #38
0
def feed(request, id=None):
    if request.user.has_perm('app.feed_card'):
        try:
            card = Card.objects.get(cid=id)
        except ObjectDoesNotExist:
            return CardNotFound(request)

        if card.retrieved:
            return render(
                request, "submit.html", {
                    "success": False,
                    "title": "卡片已被捕獲",
                    "content": "這張卡片已經被使用過囉,何不換張卡片呢?",
                })
        else:
            if request.method == 'GET':
                form = FeedForm()
                return render(request, "card/feed.html", locals())
            else:
                form = FeedForm(request.POST)
                if form.is_valid():
                    with transaction.atomic():
                        player = form.cleaned_data["player"]
                        card.retrieved = True
                        card.active = True
                        card.capturer = player
                        card.save()
                        record_reciever = History(
                            action=0xfeed, user=player.user, card=card,
                            comment="從 %s 收到一張卡片" % request.user.get_full_name())
                        record_reciever.save()
                        record_sender = History(
                            action=0xfeed, user=request.user, card=card,
                            comment="給了 %s (%s)" % (player.user.get_full_name(), player.user.username))
                        record_sender.save()
                    return render(
                        request, "submit.html", {
                            "success": True,
                            "title": "成功發送卡片",
                            "content": "成功將卡片送給 %s 了!" % player.user.get_full_name(),
                        })
                else:
                    return render(
                        request, "submit.html", {
                            "success": False,
                            "title": "發送卡片失敗",
                            "content": "要不要去戳戳系統管理員呢?"
                        })
    else:
        raise PermissionDenied
Exemple #39
0
def gift(request):
    if user_permission(request.user) < 3:
        raise PermissionDenied
    if request.method == 'GET':
        return render(request, 'staff/gift.html', {"form": FastSendForm()})
    else:
        form = FastSendForm(request.POST)
        if form.is_valid():
            player = form.cleaned_data['player']
            card = Card()
            # hard code
            present = request.user.first_name
            if present == "":
                present = '祝福'
            with transaction.atomic():
                card.name = "來自 %s 的%s" % (request.user.last_name, present)
                card.value = form.cleaned_data['point']
                card.comment = form.cleaned_data['message']
                card.active = True
                card.retrieved = True
                card.issuer = request.user
                card.capturer = player
                card.save()
                record_reciever = History(
                    action=0xfeed, user=player.user, card=card,
                    comment="從 %s 收到一張卡片" % request.user.get_full_name())
                record_reciever.save()
                record_sender = History(
                    action=0xfeed, user=request.user, card=card,
                    comment="給了 %s (%s)" % (player.user.get_full_name(), player.user.username))
                record_sender.save()
            return render(
                request, "submit.html", {
                    "success": True,
                    "title": "成功發送卡片",
                    "content": "成功將卡片送給 %s 了!" % player.user.get_full_name(),
                })
        else:
            return render(
                request, "submit.html", {
                    "success": False,
                    "title": "發送卡片失敗",
                    "content": "要不要去戳戳系統管理員呢?"
                    "(如果是POST奇怪的資料,可能會收到彈力繩喔ˊ_>ˋ)"
                })
Exemple #40
0
def feed(request, id=None):
    if request.user.has_perm('app.feed_card'):
        try:
            user = User.objects.get(username=id)
        except ObjectDoesNotExist:
            return render(
                request, "submit.html", {
                    "content": "你是找誰?",
                    "title": "錯誤!"}, status=404)

        else:
            if not request.POST:
                form = FeedForm()
                return render(request, "player/feed.html", locals())
            else:
                form = FeedForm(request.POST)
                if form.is_valid():
                    with transaction.atomic():
                        player = user.player
                        card = form.cleaned_data["card"]
                        card.capturer = player
                        card.retrieved = True
                        card.save()
                        record_sender = History(
                            action=0xfeed, user=request.user, card=card,
                            comment="給了 %s (%s)" % (player.user.get_full_name(), player.user.username))
                        record_sender.save()
                        record_reciever = History(
                            action=0xfeed, user=player.user, card=card,
                            comment="從 %s 收到一張卡片" % request.user.get_full_name())
                        record_reciever.save()

                    return render(
                        request, "submit.html", {
                            "title": "成功發送",
                            "content": "你送給 %s 一張卡片" % player.user.get_full_name(),
                        })
                else:
                    return render(request, "player/feed.html", locals())
    else:
        return render(
            request, "submit.html", {
                "content": "工作人員的世界你是看不到的!",
                "title": "錯誤!"}, status=403)
Exemple #41
0
def gift(request):
    if request.method == 'GET':
        return render(request, 'staff/gift.html', {"form": FastSendForm()})
    else:
        form = FastSendForm(request.POST)
        if form.is_valid():
            player = form.cleaned_data['player']
            card = Card()
            card.name = "來自 %s 的祝福" % request.user.get_full_name()
            card.value = form.cleaned_data['point']
            card.comment = form.cleaned_data['message']
            card.active = True
            card.retrieved = True
            card.issuer = request.user
            card.capturer = player
            card.save()
            record_reciever = History(
                action=0xfeed, user=player.user, card=card,
                comment="從 %s 收到一張卡片" % request.user.get_full_name())
            record_reciever.save()
            record_sender = History(
                action=0xfeed, user=request.user, card=card,
                comment="給了 %s (%s)" % (player.user.get_full_name(), player.user.username))
            record_sender.save()
            return render(
                request, "submit.html", {
                    "success": True,
                    "title": "成功發送卡片",
                    "content": "成功將卡片送給 %s 了!" % player.user.get_full_name(),
                })
        else:
            return render(
                request, "submit.html", {
                    "success": False,
                    "title": "發送卡片失敗",
                    "content": "要不要去戳戳系統管理員呢?"
                })