Common folder/file structure in Flask app [closed] - python
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 months ago.
The community reviewed whether to reopen this question 3 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I have just created a flask application and so far I have a router for my "Hello world!" template.
I would like to add a little (a lot) more functionality, but I wonder how I should structure the app directory.
What's the most common way of structuring a Flask app?
For instance, should I create a routes.py for all my routes?
Where does the SQLAlchemy stuff go?
Should models be in models.py?
You should check out the Larger Applications page in the Patterns section of the Flask docs: http://flask.pocoo.org/docs/patterns/packages/. It seems to be the model that most people follow when their application calls for a package instead of a module.
I believe views.py is what you are calling routes.py. After that, models would go in models.py, forms would go in forms.py, etc.
An example of a FlaskApp directory:
/yourapp
/run.py
/config.py
/app
/__init__.py
/views.py
/models.py
/static/
/main.css
/templates/
/base.html
/requirements.txt
/yourappenv
run.py - contains the actual python code that will import the app and start the development server.
config.py - stores configurations for your app.
__init__.py - initializes your application creating a Flask app instance.
views.py - this is where routes are defined.
models.py - this is where you define models for your application.
static - contains static files i.e. CSS, Javascript, images
templates - this is where you store your html templates i.e. index.html, layout.html
requirements.txt - this is where you store your package dependancies, you can use pip
yourappenv - your virtual environment for development
I would say if you split the application use divisional rather than functional structure.
I advocate this because you are more likely to work on 1 of these divisional components at any one time.
This type of structure lends itself well on marketplace or SaaS apps where different user groups use a different type of views. API only flask app I might use functional splitting.
Here are examples from Flask Blueprints. Blueprints are essentially documented advice how to split Flask application for more manageable pieces. More on this at : http://exploreflask.com/en/latest/blueprints.html
Here is an example of divisional splitting. See how each feature is grouped together.
yourapp/
__init__.py
admin/
__init__.py
views.py
static/
templates/
home/
__init__.py
views.py
static/
templates/
control_panel/
__init__.py
views.py
static/
templates/
models.py
Here is the functional example >
yourapp/
__init__.py
static/
templates/
home/
control_panel/
admin/
views/
__init__.py
home.py
control_panel.py
admin.py
models.py
I think flask is micro framework and now you must decide how create files and folders.
i use this way :
flask folders and files structure -> https://gist.github.com/4545740
this is near Django structure
i suggest you see some project to give you what you want
danjac / newsmeme — Bitbucket -> https://bitbucket.org/danjac/newsmeme/overview
sean-/flask-skeleton · GitHub -> https://github.com/sean-/flask-skeleton
Anyone looking for a simple beginner-friendly structure for the flask project may find this helpful:
|__movies
|__run.py
|__app
├── templates
│ └── index.html
│ └── signup.html
└── __init__.py
└── routes.py
Here 'movies' is the name given for the main application. It contains 'run.py' and a folder called 'app'.
'app' folder contains all necessary flask files such as 'templates' folder, '__init __.py', and 'routes.py'.
Contents of:
run.py:
from app import app
__init.py__:
from flask import Flask
app = Flask(__name__)
from app import routes
app.run(debug=True)
routes.py:
from app import app
#app.route('/')
#app.route('/index')
def index():
return "Hello, World!"
Beauty of flask lies in its flexibility. You can build django like project-structure easily. Django popularized abstraction of features in apps and making them reusable but it can be a overkill for many projects.
But with flask you can go either way. Write reusable apps or write simple apps. Check these cookiecutter skeletons -
minimal skeleton
myproject
├── config.py
├── instance
│ └── config.py
├── myproject
│ ├── commands.py
│ ├── controllers.py
│ ├── extensions.py
│ ├── forms.py
│ ├── __init__.py
│ ├── models.py
│ ├── routes.py
│ └── ui
│ ├── static
│ │ ├── css
│ │ │ └── styles.css
│ │ └── js
│ │ └── custom.js
│ └── templates
│ └── index.html
├── README.md
├── requirements.txt
└── wsgi.py
django like skeleton
myproject
├── config.py
├── development.py
├── instance
│ └── config.py
├── myproject
│ ├── auth
│ │ ├── controllers.py
│ │ ├── forms.py
│ │ ├── __init__.py
│ │ ├── models.py
│ │ └── routes.py
│ ├── helpers
│ │ ├── controllers.py
│ │ ├── __init__.py
│ │ └── models.py
│ ├── __init__.py
│ └── ui
│ └── templates
│ ├── 404.html
│ ├── 500.html
│ └── base.html
├── README.md
├── requirements.txt
├── tests
│ ├── auth
│ │ ├── __init__.py
│ │ └── test_controllers.py
│ └── __init__.py
└── wsgi.py
This is an excellent article on this.
You could get inspired by the cookiecutter templates here to jumpstart your app development
https://github.com/imwilsonxu/fbone
https://github.com/cookiecutter-flask/cookiecutter-flask
Here is the basic file structure for flask I use regularly.
yourapp/
static/
js
css
img
templates/
home.html
index.html
app.py
static folder contains all the static files of the website.
The templates folder contains all the HTML pages.
and app.py contains your python views.
I decided to nest the source code folder under src/.
my_flask_app (project folder)
├── app.py
├── setup.py
├── src/
│ ├── my_flask_app/ (source code folder)
│ │ ├── config.py
│ │ ├── errors.py
│ │ ├── forms.py
│ │ ├── __init__.py
│ │ ├── models.py
│ │ ├── routes.py
│ │ ├── static/
│ │ └── templates/
│ └── my_flask_app.egg-info/
|
└── tests/ (test folder)
Because of this, I added package_dir={'': 'src'} in setup.py.
good idea is to goole for sceletons/template projects on github
for example you can look at this
https://github.com/xen/flask-project-template
https://github.com/upperlinecode/flaskproject
https://github.com/alisezer/flask-template
In flask we can maintain the mvc structure like as separate all thinks
for example
1 Templets folder contains all html files
2 Static folder contains all css and boostrap related files
3 User defined db folder for db connection and crud operations
4 User defined Model folder for accessing/ binding the data from Templets/front- end to db/back-end connectivity
and after the main activity file
for reference flask file structure link as follow
https://flask.palletsprojects.com/en/1.1.x/tutorial/layout/
For larger projects here's what my directory structure looks like
app_name(root folder)
│ .env
│ .gitignore
│ .gitattributes
│ README.MD
│ pyproject.toml
│
└── app(source code)
│ │ __init__.py
│ │ __main__.py
│ │ db.py
│ │ auth.py
│ │ forms.py
│ │ utils.py
│ │ config.py
│ │
│ └─── routes
│ __init__.py
│ views.py
│ api.py
│ auth.py
│
└─ resources
│ |─── static
│ │ css
│ │ js
│ │ images
│ │
│ └─── templates
│ base
| components
│
└─ tests
└─ venv
└─ docs
Related
Python project structure many main.py endpoints
I currently have the following project structure in python: | project ├── module_1 │ ├── __init__.py │ ├── class_1.py ├── module_2 │ ├── __init__.py │ ├── class_2.py ├── main_1.py ├── main_2.py ├── .. ├── main_n.py ├── set_up.py Because of the vast amount of main files we use to run our scripts, I would like to organise these in different modules within the project (different module based on different usage of the endpoint). I have tried something like below: | project ├── module_1 │ ├── __init__.py │ ├── class_1.py ├── module_2 │ ├── __init__.py │ ├── class_2.py ├── endpoints_1 │ ├── __init__.py │ ├── main_1.py │ ├── set_up.py ├── endpoints_2 │ ├── __init__.py │ ├── main_2.py │ ├── set_up.py The problem that arises however is that I would have to make a different 'set_up.py' file for each of the endpoint modules. In this set_up file I would add the project path to the sys.paths so that all imports work as expected. So to conclude I have the following two questions: Is there any way I can have this project structure without having to mess to much with the sys paths and having a custom 'set_up.py' for each module which contains endpoints? Should I, to begin with, even use this kind of project structure or should I just keep the original structure and not bundle the endpoints in a module ?
Python ModuleNotFoundError: No module named 'xxx'
Pycharm imports works correctly, but when I execute test_settings.py in the terminal, I have this error: ImportError while importing test module '/home/ed/PycharmProjects/TTime/tests/test_settings.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: tests/test_settings.py:3: in from ttime import app, db E ModuleNotFoundError: No module named 'ttime' Here is my Flask project structure. I tried to include init.py in the main folder and in the tests folder, but nothing changes. It seems like somethings is wrong with python paths. . ├── config.py ├── README.md ├── requirements.txt ├── runserver.py ├── tests │ ├── functional │ │ └── __init__.py │ ├── pytest.ini │ ├── test_settings.py │ └── unit │ ├── __init__.py │ └── test_models.py └── ttime ├── __init__.py ├── models.py ├── routes.py ├── static └── templates ├── base.html └── index.html
ImportError: No module named Mail python sendgrid
User.views.py this is the folder of Mail/views.py im having error when i started the local development server from Mail.views import sendgrid_mail content['url'] = input_values["host"] + "/EmailVerification/" + user.email + '/' + md5_key message = render_to_string('accountverification.html', content) # sendMail.delay("[GavaGives] Account created successfully", message, content['email']) sendgrid_mail('info', user.email, '[GavaGives] Account created successfully', message, 'user_offline_donation') return response("create", "success", []) Mail.views.py def sendgrid_mail(from_email, to_email, subject, content, template): sg = sendgrid.SendGridClient(config('SENDGRID_API_KEY')) mail = sendgrid.Mail() mail.add_to(to_email) mail.set_from(mail_from(from_email)) mail.set_subject(subject) mail.set_html(content) mail.add_filter('templates', 'enable', '1') mail.add_filter('templates', 'template_id', get_templates(template)) sg.send(mail) Settings.py this is the folder of the main project/settings.py im having error when i started the local development server INSTALLED_APPS = [ 'django.contrib.sessions', 'corsheaders', # CORS installation 'django_cron', # celery 'django_crontab', # Cron jobs 'celery', 'djcelery', 'Users', 'Campaign', 'Donor', 'Media', 'Admin', 'Common', 'CommonModules', 'Event', 'Cards', 'Mail' ] this my project Folder Structure base on django. any help would be much appreciated. thanks <pre> [projectname]/ ├── [admin]/ ├── campaign/ ├── card/ ├── common/ ├── commonmodules/ ├── donor/ ├── event/ ├── gavagives/ │ ├── __init__.py │ ├── cel.py │ ├── cronjobs.py │ ├── custom_commands.py │ ├── settings.py │ ├── urls.py │ ├── views.py │ ├── wsgi.py ├── logs/ ├── Mail/ │ ├── mail.py │ ├── views.py ├── node_modules/ ├── manage.py ├── README.rst ├── requirements.txt ├── .env ├── Users/ │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── cronjobs.py │ ├── models.py │ ├── urls.py │ ├── validations.py │ ├── views.py ├── venv/ │ ├── include │ ├── Lib │ ├── Scripts │ ├── tcl ├── License.txt ├── .gitignore </pre>
As per django documentation, an app must contain models to be treated as a django app. Basically here you are creating a package, so you don't need to include it in INSTALLED_APPS. To allow other apps/packages/modules in your project to use your files inside the Mail folder, you need to create an __init__.py file inside that folder. Without having a __init__.py file inside the folder, Python will no longer look for submodules inside that directory, so attempts to import the module will fail. More information can be found in python documentation regarding how to import from regular package.
you need to import mail python send grid by using pip. you enter this line in juper note book or command. pip install mail python sendgrid or pip3 install mail python sendgrid
why url cannot be generated after use blueprint
My current project looks like this: ├── __init__.py ├── pages ├── settings.py ├── static ├── templates │ ├── article.html │ ├── base.html │ ├── index.html │ └── posts.html ├── view │ ├── article.py │ ├── home.py │ ├── index.py │ └── postwall.py I breaked views.py(no longer in the project) into files and those files cannot generate url dynamically anymore. What i had in article.py is: from flask import Blueprint, render_template from app import articles article = Blueprint('article',__name__) #article.route('/article/<path:path>/') def page(path): article = articles.get_or_404(path) return render_template('article.html',page=article) Meanwhile, posts.html which offers the link button to articles doesn't work anymore: More -> What is the problem?Did I miss something in the blueprint file?
solved. change More -> to More -> forgot to add blueprint name
What's the best practice when extending an application's template?
I've recently started studying Django(ver 1.9), and have a question about templates inheritance. Suppose I have a Django project named mysite and an app named myapp. And I created base template named base.html and another one named child.html, which inherits base.html. So directory structure is like this: (project root) ├── mysite │ ├── settings.py │ ├── urls.py │ └── ... ├── myapp │ ├── models.py │ ├── views.py │ ├── ... │ └── templates │ └── myapp │ ├── base.html │ └── child.html └── manage.py In this situation, I can inherit base.html like this. <!-- on top of `child.html` --> {% extends "myapp/base.html" %} What I'm wondering is, I'm hard-coding the application name. Are there any other ways of writing that avoid hard-coding the app name? Or, it's OK and I don't need to worry about? I came up with some workarounds. 1) Place base.html directly under templates directory ├── myapp │ ├── models.py │ ├── views.py │ ├── ... │ └── templates │ ├── base.html # Here! │ └── myapp │ └── child.html --> I think it causes file name crashing between applications. 2) Place base.html under project templates directory -->In this case I don't want to share base.html between applications. (base.html here is only for myapp, not other applications)
Both your base template and your child template are specific to your app, so both should live in the same myapp/ subdirectory. It's entirely acceptable to hard-code the dependency on myapp/base.html.
How about |── myapp │ ├── models.py │ ├── views.py │ ├── ... │ └── templates │ ├── base.html # Here! │ └── child.html │ then use <!-- on top of `child.html` --> {% extends "base.html" %} Then dynamically changing your Template directory at the beginning of each views.py file. from django.conf import settings settings.TEMPLATE_DIRS =(os.path.join(settings.BASE_DIR,'myapp/templates').replace('\\','/'),) You will have to do the same for every one of your apps.