Inserting Records and Using Debug Mode

如何在python里调取database里的数据,将数据显示在webpage呢?

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://username@localhost:5432/example'
db = SQLAlchemy(app)

# The Person class inherit from db.Model, we wound up linking and connecting to SQLAlchemy's mappings between classes and tables.
class Person(db.Model):
    # By defult, SQLAlchemy will pick the name of the table for you and set it equal to the lowercase version of your class.
    # But if you want to control the name of the table, you can do this way
    __tablename__ = 'persons'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(), nullable=False)

db.create_all()

@app.route('/')
def index():
    # Get the first record of the Persons
    person = Person.query.first()
    return 'Hello ' + person.name

if __name__ == '__main__':
    app.run()

前提是,得运行自己的数据库,不然就会报错


FLASK_DEBUG=true

will set debug mode on NO, which will automatically restart the server whenever we make changes to our application.

We can set this in-line with our flask run command,

$ FLASK_DEBUG=true flask run

or export it ahead of time in our terminal session on a separate line before we run the server.

$ export FLASK_DEBUG=true
$ flask run

Guess you like

Origin blog.csdn.net/BSCHN123/article/details/121260518