How to connect Javascript to Python sharing data with JSON format in both ways?

前端 未结 3 1501
没有蜡笔的小新
没有蜡笔的小新 2020-12-07 21:13

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

3条回答
  •  渐次进展
    2020-12-07 21:56

    Here's a "hello world" example of a flask web-application that can serve static html and javascript files, search database using parameter from a javascript request, and return results to javascript as 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
    

    The database setup code is from Using SQLite 3 with Flask.

    static/page.html and static/json-jquery.js files are from Ajax/jQuery.getJSON Simple Example, where the javascript code is modified slightly to pass a different url and nitems parameter:

    $(document).ready(function(){
        $('#getdata-button').live('click', function(){
            $.getJSON('/json-data', {'nitems': 3}, function(data) {
                $('#showdata').html("

    item1="+data.item1+" item2="+data.item2+" item3="+data.item3+"

    "); }); }); });

提交回复
热议问题