将json数据从jquery传递到python flask的问题

时间:2019-04-15 16:24:36

标签: java python jquery json flask

我正在尝试使用jquery将json数据传递到flask。您可以看到以下代码:

app.py

from flask import Flask, request, jsonify, render_template
from flask_mysqldb import MySQL
import time
import datetime
import json

app = Flask(__name__,template_folder='/home/tobias/Documents')
app.config['MYSQL_HOST'] = 'xxxx'
app.config['MYSQL_USER'] = 'xxxx'
app.config['MYSQL_PASSWORD'] = 'xxxx'
app.config['MYSQL_DB'] = 'xxxx'
mysql = MySQL(app)

#datahora1=time.gmtime(time.time())
#tempo=datetime.datetime.strptime(str(datahora1[2])+"/"+str(datahora1[1])+"/"+str(datahora1[0])+" 00:00:00", '%d/%m/%Y %H:%M:%S')

@app.route('/')
def index():
    return render_template('index3.html')


@app.route('/process', methods=['GET','POST'])
def process():
   local=request.get_json()
   datastore = json.loads(local)
   tempo=datastore["datahora"]
   print("local")
 #  tempo=request.form["datahora"]
#   datahora1=time.gmtime(time.time())
#   tempo=datetime.datetime.strptime(str(datahora1[2])+"/"+str(datahora1[1])+"/"+str(datahora1[0])+" 00:00:00", '%d/%m/%Y %H:%M:%S')
   cur = mysql.connection.cursor()
   cur.execute("SELECT datahora,lat,lon,wdir,wspd,gst,\
                wvht,dpd,apd,mwd,pres,ptdy,atmp,wtmp FROM ndbc WHERE datahora>='%s'\
                ORDER BY datahora DESC" % (tempo))

   row_headers=[x[0] for x in cur.description]
   rv = cur.fetchall()
   json_data=[]

   for result in rv:
       result1=[result[0].strftime('%d/%m/%Y %H:%M:%S'),result[1],result[2],result[3],result[4],result[5],result[6],result[7],result[8],result[9],result[10],result[11],result[12],result[13]]
       json_data.append(dict(zip(row_headers,result1)))

   cur.close()

   return json.dumps(json_data)

if __name__ == '__main__':
   app.run(debug=True)

index3.html

<!DOCTYPE html>

    <html>
        <script
            src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">            
        </script>

        <input type="checkbox" id="WAVESCHECK" value="WAVESCHECK" CHECKED> WAVESCHECK

        <input type="checkbox" id="NDBC" value="NDBC" CHECKED> NDBC

        <br />

        <input type="button" name="Check_All" value="MARCAR TODOS"
        onClick="CheckAll(document)">

        <input type="button" name="Un_CheckAll" value="DESMARCAR TODOS"
        onClick="UnCheckAll(document)">

        Início <input type="date" id="theDate"> 

        <input type="button" name="vermapa" value="VER"
        onClick="buscarbanco(document)">

        <input id="demo" value="VER"></p>        

        <SCRIPT LANGUAGE="JavaScript">
            <!--    
            <!-- Begin

            var server="http://localhost:5000";

            var date = new Date();

            var day = date.getDate();
            var month = date.getMonth() + 1;
            var year = date.getFullYear();

            if (month < 10) month = "0" + month;
            if (day < 10) day = "0" + day;

            var today = year + "-" + month + "-" + day;
            document.getElementById("theDate").value = today;

            function CheckAll(document) {
                document.getElementById("WAVESCHECK").checked=true;
                document.getElementById("NDBC").checked=true;
            }
            function UnCheckAll(document){
                document.getElementById("WAVESCHECK").checked=false;
                document.getElementById("NDBC").checked=false;
            }

        </script>


        <SCRIPT LANGUAGE="JavaScript">
            <!--    
            <!-- Begin

            $( function(){
                $( "#vermapa").click(function(){
                    if ($('#NDBC').prop('checked'))
                    {
                        var appdir='/process';
                        var teste = ($('#theDate').val());
//                        myObj = {"estacao": "ndbc", "tempo": teste};
                        //jsonify to send to the server
                        $.ajax({
                            type: "POST",
                            url: appdir,
                            contentType: "application/json; charset=utf-8",
                            data: {
                                local : "ndbc",
                                datahora : $('#theDate').val()
                            },
                            dataType: 'json'
                            }).done(function(data){
                                console.log(data);

                            });
                    };
                });    
            });
        </script>

app.py从jquery接收json数据,如下所示:

                            data: {
                                local : "ndbc",
                                datahora : $('#theDate').val()
                            }

因此,我运行app.py并打开Web浏览器。当我点击“ VER”按钮时,我在app.py代码中遇到了以下错误:

    File "/home/tobias/.local/lib/python3.6/site-packages/flask/app.py", line 2309, in __call__

    return self.wsgi_app(environ, start_response)

    File "/home/tobias/.local/lib/python3.6/site-packages/flask/app.py", line 2295, in wsgi_app

    response = self.handle_exception(e)

    File "/home/tobias/.local/lib/python3.6/site-packages/flask/app.py", line 1741, in handle_exception

    reraise(exc_type, exc_value, tb)

    File "/home/tobias/.local/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise

    raise value

    File "/home/tobias/.local/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app

    response = self.full_dispatch_request()

    File "/home/tobias/.local/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request

    rv = self.handle_user_exception(e)

    File "/home/tobias/.local/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception

    reraise(exc_type, exc_value, tb)

    File "/home/tobias/.local/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise

    raise value

    File "/home/tobias/.local/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request

    rv = self.dispatch_request()

    File "/home/tobias/.local/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request

    return self.view_functions[rule.endpoint](**req.view_args)

    File "/home/tobias/Documents/app.py", line 30, in process

    datastore = json.loads(local)

    File "/usr/lib/python3.6/json/__init__.py", line 348, in loads

    'not {!r}'.format(s.__class__.__name__))

    TypeError: the JSON object must be str, bytes or bytearray, not 'NoneType'

当我将json数据传递给python时,我认为我做错了。有人可以帮助我尝试找到代码中的错误吗?

0 个答案:

没有答案