-1

I am pretty new in the field and I appreciate your help

I have the following JavaScript code that uses JSON (That's all in HTML template)

What I want to achieve is to write "patterns" (regular expressions) to a text file saved locally on my machine using JSON format. The action should happen when the user clicks on button with an id="commitButton"

Please advise :) ... I am using Python 2.7

This DOES NOT WORK Error: I am getting an error in the web browser (G Chrome):

VM901:1 POST http://127.0.0.1:5000/main 500 (INTERNAL SERVER ERROR)
(anonymous) @ VM901:1
send @ jquery.min.js:4
ajax @ jquery.min.js:4
r.(anonymous function) @ jquery.min.js:4
(anonymous) @ main:118
dispatch @ jquery.min.js:3
q.handle @ jquery.min.js:3

Below is JavaScript code that uses JSON (That's all in HTML template)

<script>

var allPatt = [];
{% for line in f %}
allPatt.push({pattern:"{{line}}", currentStatus:"Current", prevStatus: "Current"})
{%endfor%}

$(function(){
  $('#commitButton').click(function(){
    $.post('/main', { commit_patterns : JSON.stringify(allPatt) })
    .done(function(data){
      console.info(data);
    })
  });
});
</script>

In Python I have the below code:

from flask import Flask,  request, render_template, jsonify
from pollerag.config import Config
import os, json
lines = []
app = Flask(__name__)

@app.route('/main', methods=["POST"])
def commitPattern():
    data = json.loads(request.form['commit_patterns'])
    for p in data:
        if (p.currentStatus == "New" or p.currentStatus == "Current"):
            with open('C:\\poller-admin-gui\\filter_configs\\field_pattern_filter.txt', 'w') as outfile:  
                json.dump(p, outfile)


if __name__ == '__main__':
    app.run(debug = True)
Omar
  • 63
  • 2
  • 12

1 Answers1

0

I am getting this error in the browser: VM558:1 POST 127.0.0.1:5000/main 500 (INTERNAL SERVER ERROR)

Internal server errors means there's a bug in your Python code that causes your server to fail. You should write some tests for your server code before trying to access it from JavaScript.

The flask console should output the error that happened. My guess would be here:

data = json.loads(request.form['commit_patterns'])
for p in data:
    if (p.currentStatus == "New" or p.currentStatus == "Current"):

depending on how the JSON looks like, data is most likely a list of dict objects. Dictionaries should be indexed in python:

data = json.loads(request.form['commit_patterns'])
for p in data:
    if (p["currentStatus"] == "New" or p["currentStatus"] == "Current"):

this is most likely the reason, but there are more options. You're not validating the data in any way, so if the user sends data that has a different shape than you expect, your Python code can throw exceptions from other places causing more HTTP 500 errors.

Kos
  • 70,399
  • 25
  • 169
  • 233