google cloud plaform에서 ssh사용하는 방법의 예시
google official doc에서는 app engine standard는 ssh사용불가 flexible은 사용가능하다고 하나 사실상 없는것 같다. compute engine은 사용가능하나 비용이 올라 갈거 같아서 사용하지 않았다.
google cloud plaform에서 ssh사용하는 방법의 예시
google official doc에서는 app engine standard는 ssh사용불가 flexible은 사용가능하다고 하나 사실상 없는것 같다. compute engine은 사용가능하나 비용이 올라 갈거 같아서 사용하지 않았다.
기본적으로 위 링크의 방법을 따랐다. 이 post는 django pd_drycleaning pickup delivery webapp 작업중에 작성되었다. 이때 django 502 bad gateway on production server with logging 관련 문제로 시간을 많이 소요했다. 그당시 문제는 logging을 file로 생성 출력하는데 app engine내부에 화일 생성을 막아서생기는 문제였다.
참고링크)
official doc https://cloud.google.com/python/django/appengine 공식문서이나 설명이 충분하지 않다. 위 링크가 좀더 상세하다. app.yaml, main.py를 만들어야 하는데 그런 내용이 공식문서에 없다.
참고링크)
공식 문서 https://cloud.google.com/appengine/docs/standard/python3/quickstart
위위링크, 아래 글내용이 좀더 자세하다.
You’ll need the following to follow along with this guide:
google sdk는 CLI 도구인 gcloud 를 말하며 한 machine에 하나만 설치하면 된다. 하나로 여러프로젝트 관리할수 있다.
macos에서의 설치설명 링크) https://youtu.be/IF09pGo833g
google sdk gcloud 퀵스타트 공식문서 https://cloud.google.com/sdk/docs/quickstart-macos
This post breaks down into the following sections in order to get an App Engine instance running properly with a Django application. Each section has a clear goal so you know when you’re ready to move on to the next step.
I won’t spend much time here, because this is basic Django stuff and outside the scope of this guide. However, needless to say your app should run locally on your computer.
It’s useful to think about how your app actually works before we start trying to deploy it. In my case, my app has a Django web server that handles routing and rendering web pages. In addition, the Django server connects to a SQL server in order to store model information in a database.
Since most apps have a database, most apps really need two servers to be runnning simultaneously: the web server and the SQL server. You’ll need to start the SQL server before the web server so the web server has something to connect to when it starts up.
Goal: You can move on when you can type python manage.py runserver
and your application works locally at 127.0.0:8000 (or whatever port you’re using).
공식문서 ) https://cloud.google.com/sql/docs/mysql/quickstart-proxy-test
Since the database comes first for any application, you’ll need to create your Google Cloud SQL instance before you can think about deploying the app itself to Google’s App Engine.
Visit your Cloud SQL instances dashboard. Click “Create Instance” to start a new SQL instance.
For the purposes of this guide, I used a MySQL 2nd Gen instance. I recommend it as it was fairly easy to set up.
Once the instance is created, you can get information about your SQL server from the command line using the Google Cloud SDK (install it if you haven’t already).
gcloud sql instances describe [YOUR_INSTANCE_NAME]
If this command runs successfully, it means you’ve done a few things right. If it fails, check the following:
Look toward the top of the output for a field called connectionName
. Copy the connectionName as we’ll need it to connect to the SQL instance remotely.
Alternatively, you can also get the connectionName from your Instance Details page in the GCP Console, under “Connect to this instance”
We’ve successfully created the SQL instance, but that doesn’t mean we’re home free. We still need to connect to it from our local machine to allow our app to run.
We need a server that can accept requests locally and relay them to our new remote server. Luckily Google has already built such a tool, known as Cloud SQL Proxy. To install it, navigate to the directory where your Django app’s manage.py
is located. Then run the following command to download the proxy, if you’re on Ubuntu:
wget https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64 -O
cloud_sql_proxy
macos는
curl -o cloud_sql_proxy https://dl.google.com/cloudsql/cloud_sql_proxy.darwin.amd64
를 사용한다.
You’ll need to change that downloaded file’s permissions in order for your machine to execute it:
chmod +x cloud_sql_proxy
Now we’re ready to do some linkage between our local machine and the Cloud SQL instance we just created. This will start the SQL server for our local development purposes and our Django app will be able to connect to the SQL server (once we change the app’s settings).
To start the SQL server locally:
아래에서 “”마크를 없애고 instance connection name을 넣어야 한다.
./cloud_sql_proxy
-instances"[YOUR_INSTANCE_CONNECTION_NAME]"=tcp:3306
Replace [YOUR_INSTANCE_CONNECTION_NAME] with the connectionName
that we copied above.
Goal: If you’re successful, you should see:
2018/11/16 13:52:35 Listening on 127.0.0.1:3306 for [connectionName]
2018/11/16 13:52:35 Ready for new connections
One more step: Now that your SQL instance is working, you’ll need to create a user to connect to that SQL instance and a database inside that instance. This is fairly easy inside the Google Cloud Dashboard –https://console.cloud.google.com/sql/instances/ .
Create both a new user and a new database.
Leave the database server (Cloud SQL Proxy) running in the background. It needs to be listening for requests, because we’re about to connect to it!
Open settings.py
in your Django project. We need to update the database settings so they’ll point to Google Cloud SQL instead of whatever local database you were using.
Typically, we specify only one database within settings.py
. But in this case, we’re going to use an if/else statement to let the application determine if it’s being run locally in development or on the actual web server in staging/production.
This will be useful when we actually deploy the application. In production, the application will connect directly to Cloud SQL via a URL. In development on our local machine, it will know to use the Cloud SQL Proxy that we just installed and are running in the background.
To set up this if/else statement, replace your current database config information with this in settings.py
:
google app engien을 사용하고 아니고에 따라 다른 database를 사용하게 한 경우이다.
# [START db_setup]
if os.getenv('GAE_APPLICATION', None):
# Running on production App Engine, so connect to Google Cloud SQL using
# the unix socket at /cloudsql/<your-cloudsql-connection string>
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '/cloudsql/[YOUR-CONNECTION-NAME]',
'USER': '[YOUR-USERNAME]',
'PASSWORD': '[YOUR-PASSWORD]',
'NAME': '[YOUR-DATABASE]',
}
}else:
# Running locally so connect to either a local MySQL instance or connect
# to Cloud SQL via the proxy. To start the proxy via command line:
# $ cloud_sql_proxy -instances=[INSTANCE_CONNECTION_NAME]=tcp:3306
# See https://cloud.google.com/sql/docs/mysql-connect-proxy
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '127.0.0.1',
'PORT': '3306',
'NAME': '[YOUR-DATABASE]',
'USER': '[YOUR-USERNAME]',
'PASSWORD': '[YOUR-PASSWORD]',
}
}
# [END db_setup]
Use connectionName
and the username, password, and database names you created in the previous step.
Notice that the else
statement specifies a port for the SQL server of 3306 when you’re running locally. When you initialize the proxy server, make sure to include the =tcp:3306
at the end of the command. Otherwise, Django will never find the server and you’ll get a timeout error.
Goal: If you’ve updated settings.py
correctly, you should be able to run your app locally.
Before you try it, though, keep in mind that you’re using a fresh new database. It doesn’t have any information about the tables/models it needs to contain. So, we need to makemigrations
first.
python manage.py makemigrations
You might see that Django doesn’t think there are new migrations. Especially if you’ve been developing this app locally already for a while.
To get Django to makemigrations
from scratch you’ll need to move or remove all the existing migrations from the migrations
folder in your app.
Once you’ve got Django making migrations from scratch use the python manage.py migrate
command to apply those migrations to your Cloud SQL database. This is the first test of your database setup, so cross your fingers it works!
If successful, you should be able to run python manage.py runserver
and your app will deploy locally, but using the Cloud SQL server as the database.
Bonus Step: You can go ahead and create a Django admin superuser now. Just type python manage.py createsuperuser
At this point, your app works using a Google Cloud SQL database. Now, you just need to be able to deploy the Django app itself to the Google App Engine.
However, this is the point where Google’s Django deployment tutorial ends. It just says to type $ gcloud app deploy
and voila, everything should work!
Of course, that works with Google’s carefully prepared tutorial repository and app, but it leaves out a lot of stuff you need to do to get an existing Django app ready for deployment on App Engine.
I’ll create subheadings for each file you’ll need to create/update in your app for it to work on App Engine. All of these edits are necessary.
I’ll use the directory names /
, /mysite
, and /myapp
to specify which folder all these files go in in your Django project. Obviously, use whatever naming scheme your Django app uses.
app.yaml 관련 공식 문서) https://cloud.google.com/appengine/docs/standard/python3/config/appref
/app.yaml
This is the basic config file for App Engine. You can change a lot of settings here, but the most basic configuration will get your app up and running for now. Just use this:
# [START django_app]
runtime: python37handlers:
# This configures Google App Engine to serve the files in the app's
# static directory.
- url: /static
static_dir: static/# This handler routes all requests not caught above to the main app.
# It is required when static routes are defined, but can be omitted
# (along with the entire handlers section) when there are no static
# files defined.
- url: /.*
script: auto# [END django_app]
/main.py
This is a file App Engine looks for by default. In it, we import the WSGI information so GAE knows how to start our app.
아래 코드에서 mysite.wsgi에서 mysite는 내 프로젝트 이름으로 수정한다.
from mysite.wsgi import application# App Engine by default looks for a main.py file at the root of the app
# directory with a WSGI-compatible object called app.
# This file imports the WSGI-compatible object of the Django app,
# application from mysite/wsgi.py and renames it app so it is
# discoverable by App Engine without additional configuration.
# Alternatively, you can add a custom entrypoint field in your app.yaml:
# entrypoint: gunicorn -b :$PORT mysite.wsgi
app = application
/requirements.txt
App Engine needs to know what dependencies to install in order to get your app running. If you’ve got your app running locally with no problems (In an IDE or on Ubuntu), you can use pip to freeze your dependencies. Ideally, you used a virtual environment to separate your app’s dependencies from the rest of your machine’s installations. If not, that’s something to read up on and implement, but it’s way outside the scope of this post.
Freeze your dependencies like so:
$ pip freeze > requirements.txt
/mysite/settings.py
We already changed the database settings in settings.py
but we need to add one more thing. A STATIC_ROOT
to tell the App Engine where to look for CSS, Javascript, Images, etc.
The STATIC_URL
field should already be in your settings.py
, but if it’s not or if it’s not configured as below, update it.
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/# Google App Engine: set static root for local static files
# https://cloud.google.com/appengine/docs/flexible/python/serving-static-files
STATIC_URL = '/static/'
STATIC_ROOT = 'static'
/mysite/wsgi.py
This file should already exist and be correctly implemented. But if you’ve made changes to it, or if there are problems, here is what it should look like. Take care to change all references to mysite
to whatever your Django app’s naming scheme is.
"""
WSGI config for mysite project.It exposes the WSGI callable as a module-level variable named ``application``.For more information on this file, see
https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/
"""import osfrom django.core.wsgi import get_wsgi_applicationos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')application = get_wsgi_application()
The final step before you deploy your app is to gather all your app’s static content in a single folder that the App Engine knows it won’t have to update and can always access.
Django does this for you pretty easily:
python manage.py collectstatic
Hopefully after you’ve frozen the requirements, added necessary files, and collected static, your app should be ready for deployment. So try:
gcloud app deploy
If you get a success message, congratulations! If you get a traceback, see what the error is and try to debug. Google is your friend here.
A success message alone isn’t enough though — actually load your application via the URL that gcloud app deploy
provides. For instance, I got a 502 Bad Gateway error, even though my app “successfully” deployed.
In my case, the problem was with my settings.py
configuration. If you have remaining errors, you’ll have to Google them, but this guide should have gotten you pretty close to a fully working Django app on Google’s App Engine.
잘 deploy이 되었는 확인은 https://console.cloud.google.com/appengine 오른쪽에 있는 project instance의 주소를 웹브라우저에 넣어 보면 된다.
(여기 doc에서는 app의 개념이다. 전체구성은 project라한다.)
Django contains a registry of installed applications that stores configuration and provides introspection. It also maintains a list of available models.
This registry is called apps
and it’s available in django.apps
:
>>> from django.apps import apps
>>> apps.get_app_config(‘admin’).verbose_name ‘Administration’
django는 각각의 설치된 app의 설정들을 apps이라는 registry(목록) 안에 보관하며 이를 통해 introspection이 가능하게 한다. 또한 사용가능한 model들을 관리한다.
The term project describes a Django web application. The project Python package is defined primarily by a settings module, but it usually contains other things. For example, when you run django-admin startproject mysite
you’ll get a mysite
project directory that contains a mysite
Python package with settings.py
, urls.py
, asgi.py
and wsgi.py
. The project package is often extended to include things like fixtures, CSS, and templates which aren’t tied to a particular application.
django-admin startproject 명령을 통해 만들어지는 것이 project이다. 이안에
settings.py
,urls.py
,asgi.py
andwsgi.py
. 이 있으며 fixtures, CSS, and templates 들도 포함된다.
A project’s root directory (the one that contains manage.py
) is usually the container for all of a project’s applications which aren’t installed separately.
The term application describes a Python package that provides some set of features. Applications may be reused in various projects.
application은 python manage.py startapp 명령을 통해 만들어진다.
Applications include some combination of models, views, templates, template tags, static files, URLs, middleware, etc. They’re generally wired into projects with the INSTALLED_APPS
setting and optionally with other mechanisms such as URLconfs, the MIDDLEWARE
setting, or template inheritance.
app은 보통 INSTALLED_APPS에 기입함으로써 프로젝트에 연결된다.
It is important to understand that a Django application is a set of code that interacts with various parts of the framework. There’s no such thing as an Application
object. However, there’s a few places where Django needs to interact with installed applications, mainly for configuration and also for introspection. That’s why the application registry maintains metadata in an AppConfig
instance for each installed application.
app은 obj로 존재하지 않는다. django가 app과 상호반응해야 하는데(주로 configuration, introspection의 목적으로) 그런 목적으로 apps registry의 AppConfig안에 metadata를 유지한다.
There’s no restriction that a project package can’t also be considered an application and have models, etc. (which would require adding it to INSTALLED_APPS
).
To configure an application, subclass AppConfig
and put the dotted path to that subclass in INSTALLED_APPS
.
When INSTALLED_APPS
contains the dotted path to an application module, Django checks for a default_app_config
variable in that module.
INSTALLED_APPS 안에 . path 형태로 app 의 module경로가 지정되어있는 경우 해당 module의 __init__.py 안의 default_app_config 를 확인하게 된다.
If it’s defined, it’s the dotted path to the AppConfig
subclass for that application.
default_app_config 안에는 . path 형태로 AppConfig 를 implement한 subclass 위치가 지정되어야한다.
If there is no default_app_config
, Django uses the base AppConfig
class.
default_app_config
allows applications that predate Django 1.7 such as django.contrib.admin
to opt-in to AppConfig
features without requiring users to update their INSTALLED_APPS
.
이부분은 정확하게 이해하지는 않았다. 추측해보면 ‘default_app_config 를 설정해서 app을 만든경우 app을 사용하는 다른 사용자(개발자)가 INSTALLED_APPS에 기입하지 않고도 사용가능하다’ 인것 같다.
New applications should avoid default_app_config
. Instead they should require the dotted path to the appropriate AppConfig
subclass to be configured explicitly in INSTALLED_APPS
.
새 app을 만들 경우 default_app_config 를 설정할 필요는 없으며 보통
INSTALLED_APPS에
AppConfig subclass 까지의 경로를 직접 . path형태로 기입하면 된다.
If you’re creating a pluggable app called “Rock ’n’ roll”, here’s how you would provide a proper name for the admin:
# rock_n_roll/apps.py from django.apps import AppConfig class RockNRollConfig(AppConfig): name = 'rock_n_roll' verbose_name = "Rock ’n’ roll"
You can make your application load this AppConfig
subclass by default as follows:
# rock_n_roll/__init__.py default_app_config = 'rock_n_roll.apps.RockNRollConfig'
That will cause RockNRollConfig
to be used when INSTALLED_APPS
contains 'rock_n_roll'
. This allows you to make use of AppConfig
features without requiring your users to update their INSTALLED_APPS
setting. Besides this use case, it’s best to avoid using default_app_config
and instead specify the app config class in INSTALLED_APPS
as described next.
Of course, you can also tell your users to put 'rock_n_roll.apps.RockNRollConfig'
in their INSTALLED_APPS
setting. You can even provide several different AppConfig
subclasses with different behaviors and allow your users to choose one via their INSTALLED_APPS
setting.
app 개발자는 두가지 선택지를 가진다. 하나는 default_app_config 를 설정함으로써 app의 사용자(다른개발자)가
INSTALLED_APPS에 특별히 기입하지않고도 app을 사용할수 있게 하는 것. 또다른 하나는
INSTALLED_APPS에
AppConfig를 extends한 subclass까지의 경로를 . path형태로 직접 입력하는 것이다. 결과적으로 두가지 방법 모두 AppConfig subclass를 거쳐 가게 된다.
The recommended convention is to put the configuration class in a submodule of the application called apps
. However, this isn’t enforced by Django.
You must include the name
attribute for Django to determine which application this configuration applies to. You can define any attributes documented in the AppConfig
API reference.
If your code imports the application registry in an application’s __init__.py
, the name apps
will clash with the apps
submodule. The best practice is to move that code to a submodule and import it. A workaround is to import the registry under a different name:
from django.apps import apps as django_apps
If you’re using “Rock ’n’ roll” in a project called anthology
, but you want it to show up as “Jazz Manouche” instead, you can provide your own configuration:
# anthology/apps.py from rock_n_roll.apps import RockNRollConfig class JazzManoucheConfig(RockNRollConfig): verbose_name = "Jazz Manouche" # anthology/settings.py INSTALLED_APPS = [ 'anthology.apps.JazzManoucheConfig', # ... ]
Again, defining project-specific configuration classes in a submodule called apps
is a convention, not a requirement.
class
AppConfig
Application configuration objects store metadata for an application. Some attributes can be configured in AppConfig
subclasses. Others are set by Django and read-only.
AppConfig.
name
Full Python path to the application, e.g. 'django.contrib.admin'
.
This attribute defines which application the configuration applies to. It must be set in all AppConfig
subclasses.
It must be unique across a Django project.
AppConfig.
label
Short name for the application, e.g. 'admin'
This attribute allows relabeling an application when two applications have conflicting labels. It defaults to the last component of name
. It should be a valid Python identifier.
It must be unique across a Django project.
AppConfig.
verbose_name
Human-readable name for the application, e.g. “Administration”.
This attribute defaults to label.title()
.
AppConfig.
path
Filesystem path to the application directory, e.g. '/usr/lib/pythonX.Y/dist-packages/django/contrib/admin'
.
In most cases, Django can automatically detect and set this, but you can also provide an explicit override as a class attribute on your AppConfig
subclass. In a few situations this is required; for instance if the app package is a namespace package with multiple paths.
AppConfig.
module
Root module for the application, e.g. <module 'django.contrib.admin' from 'django/contrib/admin/__init__.py'>
.
AppConfig.
models_module
Module containing the models, e.g. <module 'django.contrib.admin.models' from 'django/contrib/admin/models.py'>
.
It may be None
if the application doesn’t contain a models
module. Note that the database related signals such as pre_migrate
and post_migrate
are only emitted for applications that have a models
module.
Methods
AppConfig.
get_models
()
Returns an iterable of Model
classes for this application.
Requires the app registry to be fully populated.
AppConfig.
get_model
(model_name, require_ready=True)
Returns the Model
with the given model_name
. model_name
is case-insensitive.
Raises LookupError
if no such model exists in this application.
Requires the app registry to be fully populated unless the require_ready
argument is set to False
. require_ready
behaves exactly as in apps.get_model()
.
AppConfig.
ready
()
Subclasses can override this method to perform initialization tasks such as registering signals. It is called as soon as the registry is fully populated.
Although you can’t import models at the module-level where AppConfig
classes are defined, you can import them in ready()
, using either an import
statement or get_model()
.
If you’re registering model signals
, you can refer to the sender by its string label instead of using the model class itself.
Example:
from django.apps import AppConfig from django.db.models.signals import pre_save class RockNRollConfig(AppConfig): # ... def ready(self): # importing model classes from .models import MyModel # or... MyModel = self.get_model('MyModel') # registering signals with the model's string label pre_save.connect(receiver, sender='app_label.MyModel')
Warning
Although you can access model classes as described above, avoid interacting with the database in your ready()
implementation. This includes model methods that execute queries (save()
, delete()
, manager methods etc.), and also raw SQL queries via django.db.connection
. Your ready()
method will run during startup of every management command. For example, even though the test database configuration is separate from the production settings, manage.py test
would still execute some queries against your production database!
Note
In the usual initialization process, the ready
method is only called once by Django. But in some corner cases, particularly in tests which are fiddling with installed applications, ready
might be called more than once. In that case, either write idempotent methods, or put a flag on your AppConfig
classes to prevent re-running code which should be executed exactly one time.
Python packages without an __init__.py
file are known as “namespace packages” and may be spread across multiple directories at different locations on sys.path
(see PEP 420).
Django applications require a single base filesystem path where Django (depending on configuration) will search for templates, static assets, etc. Thus, namespace packages may only be Django applications if one of the following is true:
AppConfig
class used to configure the application has a path
class attribute, which is the absolute directory path Django will use as the single base path for the application.If neither of these conditions is met, Django will raise ImproperlyConfigured
.
apps
The application registry provides the following public API. Methods that aren’t listed below are considered private and may change without notice.
apps.
ready
Boolean attribute that is set to True
after the registry is fully populated and all AppConfig.ready()
methods are called.
apps.
get_app_configs
()
Returns an iterable of AppConfig
instances.
apps.
get_app_config
(app_label)
Returns an AppConfig
for the application with the given app_label
. Raises LookupError
if no such application exists.
apps.
is_installed
(app_name)
Checks whether an application with the given name exists in the registry. app_name
is the full name of the app, e.g. 'django.contrib.admin'
.
apps.
get_model
(app_label, model_name, require_ready=True)
Returns the Model
with the given app_label
and model_name
. As a shortcut, this method also accepts a single argument in the form app_label.model_name
. model_name
is case-insensitive.
Raises LookupError
if no such application or model exists. Raises ValueError
when called with a single argument that doesn’t contain exactly one dot.
Requires the app registry to be fully populated unless the require_ready
argument is set to False
.
Setting require_ready
to False
allows looking up models while the app registry is being populated, specifically during the second phase where it imports models. Then get_model()
has the same effect as importing the model. The main use case is to configure model classes with settings, such as AUTH_USER_MODEL
.
When require_ready
is False
, get_model()
returns a model class that may not be fully functional (reverse accessors may be missing, for example) until the app registry is fully populated. For this reason, it’s best to leave require_ready
to the default value of True
whenever possible.
How applications are loaded
When Django starts, django.setup()
is responsible for populating the application registry.
setup
(set_prefix=True)
Configures Django by:
set_prefix
is True, setting the URL resolver script prefix to FORCE_SCRIPT_NAME
if defined, or /
otherwise.This function is called automatically:
It must be called explicitly in other cases, for instance in plain Python scripts.
The application registry is initialized in three stages. At each stage, Django processes all applications in the order of INSTALLED_APPS
.
First Django imports each item in INSTALLED_APPS
.
If it’s an application configuration class, Django imports the root package of the application, defined by its name
attribute. If it’s a Python package, Django creates a default application configuration.
At this stage, your code shouldn’t import any models!
In other words, your applications’ root packages and the modules that define your application configuration classes shouldn’t import any models, even indirectly.
Strictly speaking, Django allows importing models once their application configuration is loaded. However, in order to avoid needless constraints on the order of INSTALLED_APPS
, it’s strongly recommended not import any models at this stage.
Once this stage completes, APIs that operate on application configurations such as get_app_config()
become usable.
Then Django attempts to import the models
submodule of each application, if there is one.
You must define or import all models in your application’s models.py
or models/__init__.py
. Otherwise, the application registry may not be fully populated at this point, which could cause the ORM to malfunction.
Once this stage completes, APIs that operate on models such as get_model()
become usable.
Finally Django runs the ready()
method of each application configuration.
Here are some common problems that you may encounter during initialization:
AppRegistryNotReady
: This happens when importing an application configuration or a models module triggers code that depends on the app registry.
For example, gettext()
uses the app registry to look up translation catalogs in applications. To translate at import time, you need gettext_lazy()
instead. (Using gettext()
would be a bug, because the translation would happen at import time, rather than at each request depending on the active language.)
Executing database queries with the ORM at import time in models modules will also trigger this exception. The ORM cannot function properly until all models are available.
This exception also happens if you forget to call django.setup()
in a standalone Python script.
ImportError: cannot import name ...
This happens if the import sequence ends up in a loop.
To eliminate such problems, you should minimize dependencies between your models modules and do as little work as possible at import time. To avoid executing code at import time, you can move it into a function and cache its results. The code will be executed when you first need its results. This concept is known as “lazy evaluation”.
django.contrib.admin
automatically performs autodiscovery of admin
modules in installed applications. To prevent it, change your INSTALLED_APPS
to contain 'django.contrib.admin.apps.SimpleAdminConfig'
instead of 'django.contrib.admin'
.
If you’ve ever built anything using Django, you’ll be used to including apps in your INSTALLED_APPS
setting:
# settings.py
INSTALLED_APPS = [
'django.contrib.auth',
'myapp',
]
This is something we take for granted, but it’s not always obvious why we need to do this. For something we use so routinely, it’s a concept we’re surprisingly vague about.
So, what are Django apps for? Why do we need to install them? Why can’t they just be plain old Python packages? Before you read on, think for a moment and try to answer these questions for yourself.
What apps are for: a general rule
Here’s a general rule for the purpose of a Django app:
Apps are for introspection.
When you declare a particular Python package as an app (by including it in INSTALLED_APPS
), you allow your project to ‘look into itself’ (i.e. introspect) and discover and enable functionality within that package.
By way of contrast, look at an aspect of Django that doesn’t use the apps system: middleware. Middleware classes can sit anywhere in your project, but they need to be explicitly configured:
MIDDLEWARE = [
'myapp.middleware.MyMiddleware',
]
In contrast, features which use the apps system (e.g. models) don’t need any specific configuration to let the framework know about them other than app installation.
models
module within your package and handles the necessary database migrations.admin
module.templatetags
package to allow loading of custom template tags.TEMPLATES
setting with APP_DIRS
as True
, Django will know about any files within a templates
subdirectory in your app.tasks.py
and Celery will automatically pick them up.Autodiscovery
Notice that all of these examples follow a similar pattern: for each piece of functionality, Django looks in every installed app for a particular module/directory name; if it’s there, it will use it. This is the foundation of Django’s pluggable architecture; providing a package is in your Python path, adding it to INSTALLED_APPS
allows it to hook in to other parts of the system.
This process is called autodiscovery, and there is a built in function for it: django.utils.module_loading.autodiscover_modules
. To use, simply call it with the name of the module you want, and Django will import any modules that have that name (providing they are in INSTALLED_APPS
, of course). For example, to import every module named foo.py
, just call:
from django.utils.module_loading import autodiscover_modules
autodiscover_modules('foo')
Tip
A good place to call autodiscover_modules
is in the ready()
method of your application configuration class.
# myapp/__init__.py
from django.apps import AppConfig as BaseAppConfig
from django.utils.module_loading import autodiscover_modules
class AppConfig(BaseAppConfig):
name = 'myapp'
def ready(self):
autodiscover_modules('products')
default_app_config = 'myapp.AppConfig'
Understanding INSTALLED_APPS can improve your Django
Why is knowing this useful? If you understand the fundamental concept of what an app is, you should be able to structure your projects better. Apps should be pluggable, discoverable modules, so design them accordingly.
That means if you have a large amount of interdependent functionality, there really is no need to split it up into multiple apps. You’re probably better off splitting up the code into a manageable file structure. For example, there’s nothing special about models.py
other than it gets automatically imported during certain model-related tasks. To make things more manageable, you could turn models.py
into a subpackage within your app, distribute the models within different files inside it, and import those models within the models/__init__.py
.
Conversely, if parts of your project could be designed as plugins, consider making them apps (even if they don’t declare any models). Let’s say you have a site that defines a range of different products by inheriting from a base Product
class. Rather than manually importing them, or configuring them in your settings, you could have your core products app autodiscover modules named products
. This would allow you to have separate, per-product apps that declare their products in products.py
files. (For more ideas about this, you may like to watch my talk on Encapsulated Django.)
To sum up, the concept of a Django app is a powerful one that goes beyond mere models. It’s the magic that allows the framework to find out about what’s inside your project. Knowing this can help you understand how certain things get imported, and give you confidence to be inventive in the way you architect your code.
original source : https://stackoverflow.com/a/26692768
The app
namespace is not specific to a library, but it is used for all attributes defined in your app, whether by your code or by libraries you import, effectively making a single global namespace for custom attributes – i.e., attributes not defined by the android system.In this case, the appcompat-v7
library uses custom attributes mirroring the android:
namespace ones to support prior versions of android (for example: android:showAsAction
was only added in API11, but app:showAsAction
(being provided as part of your application) works on all API levels your app does) – obviously using the android:showAsAction
wouldn’t work on API levels where that attribute is not defined.
original source : https://stackoverflow.com/a/38493589
Xmlns stands for ‘XML Namespace’
(For further details see https://en.wikipedia.org/wiki/XML_namespace)
The namespace ‘schemas.android.com/tools’ is for specifying options to build the app by Android Studio, and are not included in the final app package
The namespace ‘schemas.android.com/apk/res-auto’ is used for all custom attributes – defined in libraries or in code. See this answer for details.
Note that any prefix can be used for a namespace, it is not mandatory to use ‘app’ for schemas.android.com/apk/res-auto. But the same prefix must be used when defining the custom attributes in the document, otherwise an error will be shown.
So, because met_maxCharacters is a custom attribute, it is shown when the ‘schemas.android.com/apk/res-auto’ namespace is used, and not with
‘schemas.android.com/tools’