Can you query the Sqlite3 data in JavaScript?
Actually yes .... sqlite has been compiled for javascript and is called sql.js
. Can be downloaded here link
Small use example:
var sql = window.SQL
var db = new sql.Database(banco);
var res = db.exec("SELECT * FROM hello");
console.log(res);
Here is a more complete example link
Even if you have a .py file serving this data, what is the best way to do this?
Although it is possible as I showed above, it is quite unusual to use javascript to read sqlite. The most common is to create a client / server application - the client is the browser and accesses a network address, where the server, written in python, is running and serving requests. To use this method you must choose a web framework , that is, a library of functions to facilitate the creation of a web service. There are many: django
, sanic
, flask
, cherrypy
... Each one with its advantages and disadvantages, some more complete, others more flexible ...
To end I leave a super simple example using flask
and sqlalchemy
; The purpose of the example is to show something working, so you can save it in a teste_web.py
script and run it, it will work directly.
from sqlalchemy import create_engine, Column, String, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from flask import Flask, request
e = create_engine('sqlite:///arquivo.db', echo=True)
Session = sessionmaker(bind=e)
Base = declarative_base(bind=e)
class Usuario(Base):
__tablename__ = 'usuarios'
id = Column(Integer, primary_key=True)
nome = Column(String(200))
Base.metadata.create_all()
app = Flask(__name__)
@app.route("/", methods=["GET", "POST"])
def indice():
s = Session()
result = '<html>' # monta variavel com html a retornar
if request.method == "POST":
usuario = Usuario(nome=request.form["nome"])
s.add(usuario)
s.commit()
result += '<p>Usuario incluido com sucesso!</p>'
result += '<table><tr><th>ID</td><th>Nome</th></tr>' #cabecalho
for usuario in s.query(Usuario):
result += '<tr><td>{0.id}</td><td>{0.nome}</td></tr>'.format(usuario)
result += '</table><form method="POST">Incluir novo usuario:'
result += '<input name="nome" /><input type="submit"></form><html>'
return result
if __name__ == '__main__':
app.run()
This simplified example will create the database in sqlite with a table named usuarios
and then waiting for its access at address http://localhost:5000
. When you access this address with your browser, you can view the contents of the table and include new users:
Remember that this is just a simple example - When developing your application, you need to take more into account; One of the points to change is that we are creating HTML manually, the correct one would be to use a template language to facilitate the generation of html (like jinja2
);
I hope I have helped and given you a push in the right direction.