The `__init__.py` import multiple modules while they are not utilized within the file - django

I am reading /django/forms/__init__.py
"""
Django validation and HTML form handling.
"""
from django.core.exceptions import ValidationError # NOQA
from django.forms.boundfield import * # NOQA
from django.forms.fields import * # NOQA
from django.forms.forms import * # NOQA
from django.forms.formsets import * # NOQA
from django.forms.models import * # NOQA
from django.forms.widgets import * # NOQA
The __init__.py import multiple modules while they are not utilized within the files.
I assume they might be employed by others lived in the same dir, How Django achieve this?

The __init__.py import multiple modules
s/modules/names/ - the from somemodule import somename syntax exposes the somename name, not somemodule.
while they are not utilized within the files.
I assume they might be employed by others lived in the same dir
Actually this is a design pattern known as "facade" - the forms package hides it's inner implementation (in which submodule / subpackage is something defined) so
1/ the users can just import what they need from django.forms without having to care about the underlying modules / subpackages hierarchy,
and
2/ the mainainers can reorganize the underlying modules / subpackages hierarchy without breaking client code.
How Django achieve this?
This is nothing Django specific, it's just plain ordinary Python. Read Python's doc about modules and packages.

Related

Sphinx ignoring imports (py2.7)

Sphinx seems to be ignoring imports in autodoc'ed modules.
doc/conf.py excerpt
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
sys.setrecursionlimit(1500)
doc/code.rst
Auto Generated Documentation
============================
Utils
-----
.. automodule:: myproject.utils
:members:
myproject/utils/__init__.py
from data import *
from hashing import *
from redis import *
from cookie import *
from route import *
def method_whose_docstring_is_picked_up(string):
"""I'm being autodoc'ed. =)
"""
None of the classes or functions from X import Y are being autodoc'ed. Anything directly in the __init__.py is being picked up just not the imports. I tried explicitly importing each object but that didn't resolve anything.
Turns out this is possible with the imported-members but it will also drag in all std-lib and third-party imports as well, cluttering up your sphinx doc.
Sphinx, using automodule to find submodules

Why can you import UpdateView in "multiple ways"

Why do both of the following ways of importing UpdateView work?:
1. from django.views.generic import UpdateView
2. from django.views.generic.edit import UpdateView
I was assuming 2. was the correct way, and 1. would not work, but from testing both work.
What you see here is quite common (at least in some Python packages). If you define a .py file, that acts as a module. For example the django.views.generic.edit module maps on the django/views/generic/edit.py file [GitHub].
A directory is a Python module as well (due to the __init__.py file), but it does not contain any elements by default, hence that would mean that django.views.generic would be empty.
If we take a look at the django/views/generic/__init__.py file [GitHub], we see:
from django.views.generic.base import RedirectView, TemplateView, View
# ...
from django.views.generic.edit import (
CreateView, DeleteView, FormView, UpdateView,
)
# ...
__all__ = [
'View', 'TemplateView', 'RedirectView', 'ArchiveIndexView',
'YearArchiveView', 'MonthArchiveView', 'WeekArchiveView', 'DayArchiveView',
'TodayArchiveView', 'DateDetailView', 'DetailView', 'FormView',
'CreateView', 'UpdateView', 'DeleteView', 'ListView', 'GenericViewError',
]
# ...
This thus imports the UpdateView from the generic.py file, and re-exports the class.
You thus can reference to the class in two ways: through the module defined by the generic.py file, or through the re-export of the module of the directory, specified through the __init__.py file.
This is typically done to export a portion of the items that are defined in the files, export these under a more convenient name, or provide some extra classes at the module level (for example the __init__.py file defines the GenericViewError error).
This directory-level module thus "groups" interesting views together. For example the FormMixin is not exported at this level. The __init__.py here groups (popular) class-based views together, whereas the mixins, that are typically used to define such generic views, are still specific to a file.

Flask Blueprints sharing

I want to make an API with Flask and it also needs to have an admin panel.
I guess that Blueprints are the way to go, but I don't want to make models twice.
My structure is going to be this:
- app
- api
- admin
- models
So my question is: How can I access the models in the models folder in my api blueprint and my admin blueprint?
Thanks in advance.
if you'd in a module within the api or admin folders you can import anything from a module in the models folder using this notation
from ..models.module_name import model1, model2, etc
for small projects i usually keep all the models in a single models.py file like:
[app]
[blueprint_1]
__init__.py
views.py
[blueprint_2]
[static]
[templates]
__init__.py
models.py
then from within any of your blueprint files just:
from ..models import model1, model2, etc
About the import, If your directory include __init__.py then it is a python package so . use for current dir. For example:
auth/
__init__.py
forms.py
views.py
#views.py
from forms import Form name
from . import auth_blueprint # imports from __init__.py
So if you wants to import from another directory you have to use .. to imports from __init__.py file let's say your models directory include those files :
models/
__init__.py
UserModel.py
Now let's import models for auth module :
#auth/views.py
from .. import models # import froms models/__init__.py
from ..models import UserModel

How to separate flask routes to another modules

I have hundreds of routes in my flask main module,
I think it need to separate those hundred of routes from the main module.
How to do it ?
#!/usr/bin/env python3
# -*- coding: utf8 -*-
from flask import request, url_for
from flask import Flask, request, jsonify
from flask_request_params import bind_request_params
from flask import g
import datetime
import pandas as pd
import pymongo
from webargs import Arg
from webargs.flaskparser import use_args, use_kwargs
import yaml
import time, functools
from pdb import set_trace
from pandas_helper import PandasHelper
import errors
from app_helper import *
from release_schedule import ReleaseSchedule
from mongo import Mongo
#app.route('/next_release', methods=["GET"])
#return_json
def next_release():
schedules = ReleaseSchedule.next_release(DB)
return pd.DataFrame([sche for sche in schedules])
...
#app.route('/last_release', methods=["GET"])
This is what blueprints were made to do.
Another alternative is flask-classy (which is awesome). I'm going to talk about the blueprint approach since that's what I know better.
If I was in your position I would want to split my routes up based on common imports.
Without knowning your application I'm going to guess that a distribution like this
parse_user_data_views.py
from webargs import Arg
from webargs.flaskparser import use_args, use_kwargs
import yaml
push_to_db_views.py
from pandas_helper import PandasHelper
from mongo import Mongo
import pymongo
import pandas as pd
import datetime
release_views.py
from release_schedule import ReleaseSchedule
import pandas as pd
#app.route('/next_release', methods=["GET"])
#return_json
def next_release():
schedules = ReleaseSchedule.next_release(DB)
return pd.DataFrame([sche for sche in schedules])
is likely distribution. We can't answer this for you, only you can.
But this allows you to separate out your application in some pretty nice ways.
in __init__.py
from flask import Flask
from yourapplication.release_views import release_views
from yourapplication.push_to_db_views import push_to_db_views
from yourapplication.parse_user_data_views import parse_user_data_views
app = Flask(__name__)
app.register_blueprint(release_views)
app.register_blueprint(push_to_db_views)
app.register_blueprint(parse_user_data_views)
Create a new file called views.py and add all your routes there. Then import views.py in your __ init __.py .

How to import every model, function and other things in django project?

I am working on a Django project.
I currently import functions, models like:
from project.abc.models import *
from project.cba.models import *
from project.abc.views import *
from project.cba.views import *
Is there any syntax which can enable me to write just the name of project and it may return every model, functions and etc from every application like:
from project.models import *
from project.views import *
from project.urls import *
I am using Django1.3, and I know that it is not a good practice to import * of anything, but this is my need at the moment. Please help!
I think that it is not a good idea but if you want you can create a file models.py in your project root directory and write there:
from project.abc.models import *
from project.cba.models import *
after that you can import your models like:
from project.models import SomeModel
And you also can create views.py etc.