一尘不染

如何通过两种方式将Javascript连接到共享JSON格式数据的Python?

json

我正在尝试找出如何使用JSON格式为要检索的数据在Python服务器和Javascript客户端之间创建本地连接。特别是,我需要在HTML客户端进行一些查询,将这些查询以JSON格式发送到服务器,然后在Python服务器端运行它们以在SQLite数据库上搜索数据。从数据库获取结果后,也将这些结果也以JSON格式发送回客户端。

现在,我可以在Python上运行查询并在JSON上进行编码,如下所示:

import sqlite3 as dbapi
import json

connection = dbapi.connect("C:/folder/database.db")
mycursor = connection.cursor()
mycursor.execute("select * from people")
results = []
for information in mycursor.fetchall():
        results += information

onFormat = json.dumps(results)
print(onFormat)

我知道这段代码的作用类似(实际上它可以运行),因为它在服务器上调用了服务,该服务以JSON格式返回数据(但此示例中的服务器不是Python):

<html>
    <head>
        <style>img{ height: 100px; float: left; }</style>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
    </head>
    <body>
        <div id="images"></div>
    <script>
      $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
      {
        tags: "mount rainier",
        tagmode: "any",
        format: "json"
      },
      function(data) {
        $.each(data.items, function(i,item){
          $("<img/>").attr("src", item.media.m).appendTo("#images");
          if ( i == 3 ) return false;
        });
      });</script>

    </body>
</html>

我需要知道如何(本地)运行python程序,使其成为可用的正在运行的Web服务,以及应该如何使用Javascript从python服务器检索数据。

我在互联网上到处都在寻找这个答案,但是我在任何地方都找不到这个答案,因为他们给出的唯一答案是关于如何在Python或Javascript中编码JSON而不是两者都连接。希望有人可以帮助我!


阅读 183

收藏
2020-07-27

共1个答案

一尘不染

我终于找到了比Flask更简单的方法。这是一个名为Bottle的Python框架。您只需从官方网站下载该库并将其所有文件放在您的工作目录中,即可导入该库。您也可以使用随附的安装程序python程序进行安装,以避免随身携带源代码。然后,为了制作您的Web服务服务器,您可以像这样进行编码:

from bottle import hook, response, route, run, static_file, request
import json
import socket
import sqlite3

#These lines are needed for avoiding the "Access-Control-Allow-Origin" errors
@hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'

#Note that the text on the route decorator is the name of the resource
# and the name of the function which answers the request could have any name
@route('/examplePage')
def exPage():
    return "<h1>This is an example of web page</h1><hr/><h2>Hope you enjoy it!</h2>"

#If you want to return a JSON you can use a common dict of Python, 
# the conversion to JSON is automatically done by the framework
@route('/sampleJSON', method='GET')
def mySample():
    return { "first": "This is the first", "second": "the second one here", "third": "and finally the third one!" }

#If you have to send parameters, the right sintax is as calling the resoure
# with a kind of path, with the parameters separed with slash ( / ) and they 
# MUST to be written inside the lesser/greater than signs  ( <parameter_name> ) 
@route('/dataQuery/<name>/<age>')
def myQuery(name,age):
    connection= sqlite3.connect("C:/folder/data.db")
    mycursor = connection.cursor()
    mycursor.execute("select * from client where name = ? and age= ?",(name, age))
    results = mycursor.fetchall()
    theQuery = []
    for tuple in results:
        theQuery.append({"name":tuple[0],"age":tuple[1]})
    return json.dumps(theQuery)

#If you want to send images in jpg format you can use this below
@route('/images/<filename:re:.*\.jpg>')
def send_image(filename):
    return static_file(filename, root="C:/folder/images", mimetype="image/jpg")

#To send a favicon to a webpage use this below
@route('/favicon.ico')
def favicon():
    return static_file('windowIcon.ico', root="C:/folder/images", mimetype="image/ico")

#And the MOST important line to set this program as a web service provider is this
run(host=socket.gethostname(), port=8000)

最后,您可以通过以下方式在Javascript客户端上调用Bottlepy应用程序的REST Web服务:

var addr = "192.168.1.100"
var port = "8000"

function makeQuery(name, age){
    jQuery.get("http://"+addr+":"+port+"/dataQuery/"+ name+ "/" + age, function(result){
        myRes = jQuery.parseJSON(result);
        toStore= "<table border='2' bordercolor='#397056'><tr><td><strong>name</strong></td><td><strong>age</strong></td></tr>";
        $.each(myRes, function(i, element){
            toStore= toStore+ "<tr><td>"+element.name+"</td><td>" + element.age+ "</td></td></tr>";
        })
        toStore= toStore+ "</table>"
        $('#theDataDiv').text('');
        $('<br/>').appendTo('#theDataDiv');
        $(toStore).appendTo('#theDataDiv');
        $('<br/>').appendTo('#theDataDiv');
    })
}

我希望它对其他人有用

2020-07-27