Experimenting in Interactive Mode

You can get to by simply starting your terminal and entering python3 to run the code.
Steps:

  1. Rename your app from flask-example.py to flask_example.py (replace the dashes with underscores, so that we can import it with Python)
  2. Go to your terminal and enter Python interactive mode by entering python3
  3. Import the app by running import flask_example (notice that there is no .py at the end when we are imprting!)
  4. If you get the deprecating warning, modify the app to set app.config[‘SQLALCHEMY_TRACH_MODIFICATIONS’] = False
  5. Try importing again - you should now get a successful import with no errors or warnings.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://username@localhost:5432/example'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
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()

请添加图片描述


How to debug?
使用这个函数:

# Ability to customozie a principle string (useful for debugging)
def __repr__(self):
	return f'<{
      
      self.id}, {
      
      self.name}>'

这个代码:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://username@localhost:5432/example'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
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)

    def __repr__(self):
        return f'<Person ID: {
      
      self.id}, name: {
      
      self.name}>'

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()

请添加图片描述

猜你喜欢

转载自blog.csdn.net/BSCHN123/article/details/121307017