see examples that define the model directly at the start of the program, such as _ _ init__.py, server.py.
my idea is to define the model in the corresponding .py file and create it directly when needed. I don"t know how to organize the project file and call it.
initialization file:
-sharpapp/__init__.py
import os
from flask import Flask
def create_app(test_config=None):
-sharp create and configure the app
app = Flask(__name__, instance_relative_config=True)
if test_config is None:
-sharp load the instance config, if it exists, when not testing
app.config.from_pyfile("config.py", silent=True)
else:
-sharp load the test config if passed in
app.config.from_mapping(test_config)
-sharp instance
try:
os.makedirs(app.instance_path)
except OSError:
pass
-sharp
@app.route("/hello")
def hello():
return "Hello, World!"
-sharp
from app.models import db
db.init_app(app)
print("")
db.create_all()
return app
Model file:
-sharpapp/models.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
addresses = db.relationship("Address", backref="person", lazy=True)
class Address(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(120), nullable=False)
person_id = db.Column(db.Integer, db.ForeignKey("person.id"),
nullable=False)
it is normal to start the application, but no database tables are generated.
(Flask-Practice) ydx@ydx-PC:$ flask run
* Serving Flask app "app" (lazy loading)
* Environment: development
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with inotify reloader
* Debugger is active!
* Debugger PIN: 338-486-377
Why did you output create Database twice?
an error occurred when accessing the application:
RuntimeError: application not registered on db instance and no application bound to current context
< hr >
refer to Link description the solution is as follows:
modify the initialization file to inform the flask module of the current application using the context.
-sharp
from app.models import db
db.init_app(app)
with app.app_context():
print("")
db.create_all()