S
S
Sasha Filinsky2022-04-20 14:13:02
Python
Sasha Filinsky, 2022-04-20 14:13:02

How to properly split a Python file into modules?

There is a main.py file where I connect to the database. It is necessary to write models to the database, since it is not correct to write everything in one file, I want to divide it into a module, but I don’t know how to do it correctly.

main.py code example

from flask import Flask, redirect, render_template, request, url_for, redirect
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True

db = SQLAlchemy(app)

class Users(db.Model):
    Id = db.Column(db.Integer, primary_key=True)
    Login = db.Column(db.String(255), nullable=False)

class Checks(db.Model):
    Id = db.Column(db.Integer, primary_key=True)
    PasswordHash = db.Column(db.String(255), nullable=False)


I want all models to be in the models.py file.
How to do this correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ramis, 2022-04-20
@UkaUkaa

Structure:

├── main.py
└── my_project
    ├── __init__.py
    ├── models.py
    ├── views.py

main.py
from my_project import app
app.run()

__init__.py
from flask import Flask, redirect, render_template, request, url_for, redirect
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True

db = SQLAlchemy(app)

import project.views

models.py
from my_project import db

class Users(db.Model):
    Id = db.Column(db.Integer, primary_key=True)
    Login = db.Column(db.String(255), nullable=False)

class Checks(db.Model):
    Id = db.Column(db.Integer, primary_key=True)
    PasswordHash = db.Column(db.String(255), nullable=False)

views.py
from my_project import app
from my_project .models import Users, Checks

@app.route('/')
def index():
    return 'hello habr'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question