[英]How to connect Javascript to Python sharing data with JSON format in both ways?
我正在嘗試找出如何使用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但不連接兩者。 希望有人可以幫助我!!!
這是一個燒瓶網絡應用程序的“hello world”示例,它可以提供靜態html和javascript文件,使用javascript請求中的參數搜索數據庫,並將結果返回到javascript為json:
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
數據庫設置代碼來自使用SQLite 3和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>");
});
});
});
你的問題相當於“如何將這個python變成web服務”。
可能最輕量級的方法是web.py
和flask
。 去看一下。
如果這個變得越來越大,請考慮使用tastypie
django
- 這是制作基於json的api的簡單方法。
更新:顯然,還有一個名為Pico的python-javascript RPC框架,Felix Kling是一個貢獻者。 介紹說:
直接在Python模塊中添加一行代碼(import pico),將其轉換為可通過Javascript(和Python)Pico客戶端庫進行訪問的Web服務。
我終於找到了比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');
})
}
我希望它對其他人有用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.