Python Back-end for Front-end

Asked

Viewed 3,268 times

0

I made a simple application that registers some data in a sqlite3 database, all this part of the Back-end is done in Python with.py files running in the same terminal, for my use already serves me excellently. Now I want to view the data on a web page even to study HTML CCS and JS. Is there any way to query Sqlite3 data in Javascript? to fill in the data on the web page, even if you have a.py file serving that data, how best to do this?

  • Creating a web server that uses scripts or accesses sqlite3 and provides pro JS data via HTTP requests.

1 answer

0


You can consult Sqlite3 data in Javascript?

In fact yes.... sqlite has been compiled for javascript and is called sql.js. Can be downloaded here https://github.com/kripken/sql.js

Small example of use:

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 http://kripken.github.io/sql.js/GUI/


even if you have a.py file serving that data, what’s the best way to do it?

Although it is possible as shown above, it is rather unusual 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 framework web, ie a library of functions to facilitate the creation of a web service. There are many: django, sanic, flask, cherrypy... Each with its advantages and disadvantages, some more complete, others more flexible...

To finish I leave a super simple example using flask and sqlalchemy; The goal of the example is to show something working, so you can save it in a script teste_web.py 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 called usuarios and then will be waiting for your access at the address http://localhost:5000. By accessing this address with your browser, you can see the contents of the table and include new users:

web

Remember that this is just a simple example - When developing your application, you need to take more than that into account; One of the points to change is that we are creating HTML manually, the correct would be to use a template language to facilitate html generation (as for example jinja2);

I hope I helped and gave you a push in the right direction.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.