11

取得するデータに 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 サービスにする方法と、Python サーバーからデータを取得するための Javascript をどのようにするかを知ることです。

私はどこでもインターネットでこれを探しましたが、この答えはどこにも見つかりませんでした。なぜなら、彼らが与える唯一の答えは、PythonまたはJavascript内でJSONをコーディングする方法であり、両方を接続しないためです。誰かがこれについて私を助けてくれることを願っています!!!

4

3 に答える 3

12

これは、静的な html ファイルと javascript ファイルを提供し、javascript リクエストのパラメーターを使用してデータベースを検索し、結果を json として javascript に返すことができるフラスコ Web アプリケーションの「hello world」の例です。

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.htmlstatic/json-jquery.jsファイルはAjax/jQuery.getJSON Simple Exampleからのもので、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>");
        });
    });
});
于 2012-07-31T21:45:26.003 に答える
8

あなたの質問は、「このpythonをWebサービスにするにはどうすればよいですか」ということになります。

おそらくそれを行う最も軽量な方法はweb.pyflaskです。それらをチェックしてください。

これが大きくなっている場合は、json ベースの API を作成する簡単な方法を検討djangoしてください。tastypie

更新: どうやら、 Picoと呼ばれる python-javascript RPC フレームワークもあり、Felix Kling が貢献しています。イントロには次のように書かれています。

Python モジュールに文字通り 1 行のコード (import pico) を追加して、Javascript (および Python) Pico クライアント ライブラリを介してアクセス可能な Web サービスに変換します。

于 2012-07-31T19:29:37.627 に答える
4

Flaskよりも簡単な方法をついに見つけました。これはBottleと呼ばれる Python フレームワークです。ライブラリをインポートするには、公式 Web サイトからライブラリをダウンロードし、そのすべてのファイルを作業ディレクトリに配置するだけです。ソースコードをどこにでも持ち歩かないように、含まれているセットアップ 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');
    })
}

他の誰かに役立つことを願っています

于 2012-08-16T14:42:32.353 に答える