如何将Javascript连接到Python以两种方式共享JSON格式的数据? [英] How to connect Javascript to Python sharing data with JSON format in both ways?

查看:145
本文介绍了如何将Javascript连接到Python以两种方式共享JSON格式的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to find out how to create a local connection between a Python server and a Javascript client using the JSON format for the data to be retrieved. Particularly, I need to make some queries on the HTML client side, send these queries to the server on JSON format and run them on the Python server side to search for data on a SQLite Database. And after getting the results from the database, send those results back to the client in JSON format too.

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

By now, I just can run the query on Python and code it on JSON like this:

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):

I know this code does something alike (in fact it runs), because it calls a service on a server which returns data in JSON format (but the server in this example is NOT 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服务器检索数据。

What I need is to know how should I run (locally) the python program to be an available running web-service and how should be the Javascript to retrieve the data from the python server.

我一直在网上寻找这个,但我没有找到任何答案,因为他们给出的唯一答案是如何在Python内部或Javascript内部编写JSON代码但没有连接两者。希望有人可以帮助我!!!

I've looking for this on internet everywhere but I didn't find this answer anywhere because the only answers they give are on how to code JSON inside Python or inside Javascript but not connecting both. Hope somebody can help me on this!!!

推荐答案

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

I found finally an easier way than Flask. It's a Python framework called Bottle You only need to download the library from the official web site and put all its files in your working directory in order to import the library. You can also install it using the setup python program included to avoid carrying with the sourcecode everywhere. Then, for making your Web Service Server you can code it like this:

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服务以这种方式的客户:

Finally, you can call the REST web service of your Bottlepy app on a Javascript client in this way:

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');
    })
}

我希望它对其他人有用

这篇关于如何将Javascript连接到Python以两种方式共享JSON格式的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆