如何将Javascript连接到Python并以JSON格式共享数据?

问题描述 投票:0回答:4

我试图找出如何使用 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,但没有连接两者。希望有人可以帮助我!

javascript python json web-services sqlite
4个回答
12
投票

这是一个 Flask Web 应用程序的“hello world”示例,它可以提供静态 html 和 javascript 文件,使用 javascript 请求中的参数搜索数据库,并将结果作为 json 返回给 javascript:

import sqlite3 from flask import Flask, jsonify, g, redirect, request, url_for app = Flask(__name__) @app.before_request def before_request(): g.db = sqlite3.connect('database.db') @app.teardown_request def teardown_request(exception): if hasattr(g, 'db'): g.db.close() @app.route('/') def index(): return redirect(url_for('static', filename='page.html')) @app.route('/json-data/') def json_data(): # get number of items from the javascript request nitems = request.args.get('nitems', 2) # query database cursor = g.db.execute('select * from items limit ?', (nitems,)) # return json return jsonify(dict(('item%d' % i, item) for i, item in enumerate(cursor.fetchall(), start=1))) if __name__ == '__main__': app.run(debug=True, host='localhost', port=5001) # http://localhost:5001/ else: application = app # for a WSGI server e.g., # twistd -n web --wsgi=hello_world.application --port tcp:5001:interface=localhost

数据库设置代码来自

Using SQLite 3 with Flask

static/page.html

static/json-jquery.js
文件来自
Ajax/jQuery.getJSON简单示例,其中稍微修改了javascript代码以传递不同的url和nitems
参数:

$(document).ready(function(){ $('#getdata-button').live('click', function(){ $.getJSON('/json-data', {'nitems': 3}, function(data) { $('#showdata').html("<p>item1="+data.item1+" item2="+data.item2+" item3="+data.item3+"</p>"); }); }); });
    

8
投票
你的问题相当于“我如何将这个Python变成一个网络服务”。

最轻量级的方法可能是

web.py

flask
。检查一下。 

如果它变得越来越大,请考虑使用

django

tastypie
 - 这是制作基于 json 的 api 的简单方法。

更新:显然,还有一个名为

Pico 的 python-javascript RPC 框架,Felix Kling 是该框架的贡献者。简介说:

从字面上添加一行代码(导入 pico)到您的 Python 模块中 将其转换为可通过 Javascript 访问的 Web 服务 (和 Python)Pico 客户端库。


4
投票
我终于找到了比 Flask 更简单的方法。这是一个名为

Bottle 的 Python 框架,您只需从官方网站下载该库并将其所有文件放在您的工作目录中即可导入该库。您还可以使用附带的 setup 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'); }) }

我希望它对其他人有用


0
投票
检查这个:

https://github.com/yzITI/srpc!我专门设计了一个轻量级脚本来使这种通信尽可能简单。

它基于HTTP,设计目标是使这种通信无缝。

© www.soinside.com 2019 - 2024. All rights reserved.