コード例 #1
0
 def test_extra_operations(self):
     expressions = [
         "5 + 3 * 8 *",
         "5 + 3 * 8 * * *",
         "5 + 3 * * * 8",
         " / 5 + 3 * 8",
     ]
     for exp in expressions:
         with self.assertRaises(RuntimeError) as cm:
             rpn.evaluate(exp)
         self.assertIn('mismatched operators', str(cm.exception))
コード例 #2
0
ファイル: server.py プロジェクト: MahoVik/calculator-flask
def calculate():
    d = request.get_json(force=True)
    if not isinstance(d, dict):
        # Throw an error
        # "The given data is not a dict!"
        resp = app.response_class(
            response=json.dumps({
                'status': 400,
                'message': "The given data is not a dict!"
            }),
            status=400,
        )
        return resp

    if 'expression' not in d:
        # Throw an error
        # "The key 'expression' required'
        resp = app.response_class(
            response=json.dumps({
                'status': 400,
                'message': "The key 'expression' required"
            }),
            status=400,
        )
        return resp

    expression = d.get('expression')
    if not isinstance(expression, str):
        resp = app.response_class(
            response=json.dumps({
                'status': 400,
                'message': "The given data is not a string!"
            }),
            status=400,
        )
        return resp
    try:
        res = rpn.evaluate(expression)
    except Exception as e:
        resp = app.response_class(
            response=json.dumps({
                'status': 400,
                'message': str(e)
            }),
            status=400,
        )
        return resp

    return json.dumps({"result": res})
コード例 #3
0
ファイル: server.py プロジェクト: MahoVik/calculator-flask
def calc_form():
    error = None
    res = None
    if request.method == 'POST':
        d = request.form
        mathexpression = d.get('expression')
        if not isinstance(mathexpression, str):
            error = "The given data is not a string!"
        elif len(mathexpression) == 0:
            error = "The given data is empty!"
        try:
            res = rpn.evaluate(mathexpression)
        except Exception as e:
            error = str(e)

    # следущий код выполняется при методе запроса GET
    # или при признании полномочий недействительными

    return flask.render_template('index.html', error=error, res=res)
コード例 #4
0
 def test_extra_closed_brackets(self):
     expressions = ["(1 + (5 + 3))) * 8", "(2 + 10))", "2 + 5)"]
     for exp in expressions:
         with self.assertRaises(RuntimeError) as cm:
             rpn.evaluate(exp)
         self.assertIn('mismatched brackets', str(cm.exception))