Here are the examples of the python api django.conf taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
45 Examples
3
Source : fixtures.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def _disable_native_migrations():
from django.conf import settings
from django.core.management.commands import migrate
from .migrations import DisableMigrations
settings.MIGRATION_MODULES = DisableMigrations()
class MigrateSilentCommand(migrate.Command):
def handle(self, *args, **kwargs):
kwargs["verbosity"] = 0
return super(MigrateSilentCommand, self).handle(*args, **kwargs)
migrate.Command = MigrateSilentCommand
def _set_suffix_to_test_databases(suffix):
3
Source : fixtures.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def __getattr__(self, item):
from django.conf import settings
return getattr(settings, item)
def finalize(self):
3
Source : test_fixtures.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_settings_before(self):
from django.conf import settings
assert (
"%s.%s" % (settings.__class__.__module__, settings.__class__.__name__)
== "django.conf.Settings"
)
TestLiveServer._test_settings_before_run = True
def test_url(self, live_server):
3
Source : test_fixtures.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_settings_restored(self):
"""Ensure that settings are restored after test_settings_before."""
import django
from django.conf import settings
assert TestLiveServer._test_settings_before_run is True
assert (
"%s.%s" % (settings.__class__.__module__, settings.__class__.__name__)
== "django.conf.Settings"
)
if django.VERSION >= (1, 11):
assert settings.ALLOWED_HOSTS == ["testserver"]
else:
assert settings.ALLOWED_HOSTS == ["*"]
def test_transactions(self, live_server):
3
Source : registry.py
with GNU General Public License v3.0
from JohannesAutenrieb
with GNU General Public License v3.0
from JohannesAutenrieb
def _autodiscover_modules(module_name): # pragma: no cover
"Django 1.6 compat to provide `autodiscover_modules`"
from django.conf import settings
from django.utils.importlib import import_module
for app in settings.INSTALLED_APPS:
# Attempt to import the app's `module_name`.
try:
import_module('{app}.{module}'.format(app=app, module=module_name))
except Exception:
pass
def load_modules(modules=None):
3
Source : test_django.py
with MIT License
from kiwicom
with MIT License
from kiwicom
def test_settings_access():
"""When `setting` are accessed in this way after patching."""
# Explicit import to check how custom __getattribute__ is working
from django.conf import settings
assert settings.SECRET == "value"
@override_settings(ALLOWED_HOSTS=["localhost"])
3
Source : migrate.py
with BSD 3-Clause "New" or "Revised" License
from kogan
with BSD 3-Clause "New" or "Revised" License
from kogan
def migrate(name):
from django.conf import settings
settings.configure(**SETTINGS_DICT)
import django
django.setup()
from django.core import management
management.call_command("makemigrations", "subscriptions", name=name)
if __name__ == "__main__":
3
Source : simpletags.py
with MIT License
from newpanjing
with MIT License
from newpanjing
def __get_config(name):
from django.conf import settings
value = os.environ.get(name, getattr(settings, name, None))
return value
@register.simple_tag
3
Source : simpletags.py
with MIT License
from newpanjing
with MIT License
from newpanjing
def get_language():
from django.conf import settings
return settings.LANGUAGE_CODE.lower()
@register.filter
3
Source : simpletags.py
with MIT License
from newpanjing
with MIT License
from newpanjing
def get_language_code(val):
from django.conf import settings
return settings.LANGUAGE_CODE.lower()
def get_analysis_config():
3
Source : simpletags.py
with MIT License
from newpanjing
with MIT License
from newpanjing
def has_enable_admindoc():
from django.conf import settings
apps = settings.INSTALLED_APPS
return 'django.contrib.admindocs' in apps
@register.simple_tag(takes_context=True)
3
Source : simpletags.py
with MIT License
from pmeta
with MIT License
from pmeta
def __get_config(name):
from django.conf import settings
value = os.environ.get(name, getattr(settings, name, None))
return value
@register.filter
3
Source : runtests.py
with MIT License
from xuchaoa
with MIT License
from xuchaoa
def teardown(state):
from django.conf import settings
# Removing the temporary TEMP_DIR. Ensure we pass in unicode
# so that it will successfully remove temp trees containing
# non-ASCII filenames on Windows. (We're assuming the temp dir
# name itself does not contain non-ASCII characters.)
shutil.rmtree(smart_text(TEMP_DIR))
# Restore the old settings.
for key, value in state.items():
setattr(settings, key, value)
def django_tests(verbosity, interactive, failfast, test_labels):
3
Source : runtests.py
with MIT License
from xuchaoa
with MIT License
from xuchaoa
def django_tests(verbosity, interactive, failfast, test_labels):
from django.conf import settings
state = setup(verbosity, test_labels)
extra_tests = []
# Run the test suite, including the extra validation tests.
from django.test.utils import get_runner
if not hasattr(settings, 'TEST_RUNNER'):
settings.TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=verbosity, interactive=interactive,
failfast=failfast)
failures = test_runner.run_tests(test_labels or get_test_modules(), extra_tests=extra_tests)
teardown(state)
return failures
if __name__ == "__main__":
0
Source : nmap_to_sqlite.py
with MIT License
from arch4ngel
with MIT License
from arch4ngel
def configure(db_config,base_dir,migrate=True):
'''Configure a fake Django application and initialize an SQLite
database to capture the scan data.
'''
import django
from django.conf import settings
from django.apps.config import AppConfig
# =========================
# CONFIGURE THE APPLICATION
# =========================
INSTALLED_APPS=[
'nmap',
]
DATABASES = {
'default': db_config
}
settings.configure(
INSTALLED_APPS = INSTALLED_APPS,
DATABASES = DATABASES,
)
# =======================
# INITIALIZE THE DATABASE
# =======================
if migrate:
execute_from_command_line([base_dir,'makemigrations'])
execute_from_command_line([base_dir,'migrate'])
def processHost(host,import_info,models):
0
Source : conftest.py
with MIT License
from AsheKR
with MIT License
from AsheKR
def pytest_configure(config):
from django.conf import settings
settings.configure(
DEBUG_PROPAGATE_EXCEPTIONS=True,
DATABASES={
"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"},
},
SECRET_KEY="not very secret in tests",
USE_I18N=True,
STATIC_URL="/static/",
ROOT_URLCONF="tests.urls",
TEMPLATES=[
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"APP_DIRS": True,
"OPTIONS": {
"debug": True, # We want template errors to raise
},
},
],
MIDDLEWARE=(
"django.middleware.common.CommonMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
),
INSTALLED_APPS=(
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.sites",
"django.contrib.staticfiles",
"news",
),
PASSWORD_HASHERS=("django.contrib.auth.hashers.MD5PasswordHasher",),
USE_L10N=True,
)
django.setup()
0
Source : conftest.py
with BSD 2-Clause "Simplified" License
from blubber
with BSD 2-Clause "Simplified" License
from blubber
def pytest_configure(config):
from django.conf import settings
settings.configure(
DEBUG=True,
DEBUG_PROPAGATE_EXCEPTIONS=True,
DATABASES={},
SECRET_KEY='not so secret',
ROOT_URLCONF='tests.test_django_injector',
TEMPLATES=[
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'debug': True,
'context_processors': [
'tests.test_django_injector.context_processor',
],
},
},
],
MIDDLEWARES=[
'django.middleware.common.CommonMiddleware',
],
INSTALLED_APPS=[
'django.contrib.contenttypes',
'django.contrib.auth',
'django_injector',
'tests',
],
USE_I18N=False,
USE_L10N=False,
INJECTOR_MODULES=[
'tests.test_django_injector.configure_django_injector',
'tests.test_django_injector.TestModule',
],
)
django.setup()
0
Source : run_test.py
with MIT License
from chaitin
with MIT License
from chaitin
def setup_django_environment():
from django.conf import settings
settings.configure(
DEBUG_PROPAGATE_EXCEPTIONS=True,
DATABASES={
"default": dj_database_url.config(env="DATABASE_URL",
default="postgres://test:test@localhost/test",
conn_max_age=20)
},
SECRET_KEY="not very secret in tests",
USE_I18N=True,
USE_L10N=True,
USE_TZ=True,
TIME_ZONE="Asia/Shanghai",
INSTALLED_APPS=(
"pg_partitioning",
"tests",
),
LOGGING={
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"standard": {
"format": "[%(asctime)s] %(message)s",
"datefmt": "%Y-%m-%d %H:%M:%S"
}
},
"handlers": {
"console": {
"level": "DEBUG",
"class": "logging.StreamHandler",
"formatter": "standard"
}
},
"loggers": {
"pg_partitioning.shortcuts": {
"handlers": ["console"],
"level": "DEBUG",
"propagate": False,
},
"pg_partitioning.patch.schema": {
"handlers": ["console"],
"level": "DEBUG",
"propagate": False,
},
},
}
)
django.setup()
if __name__ == "__main__":
0
Source : fixtures.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def _set_suffix_to_test_databases(suffix):
from django.conf import settings
for db_settings in settings.DATABASES.values():
test_name = db_settings.get("TEST", {}).get("NAME")
if not test_name:
if db_settings["ENGINE"] == "django.db.backends.sqlite3":
continue
test_name = "test_{}".format(db_settings["NAME"])
if test_name == ":memory:":
continue
db_settings.setdefault("TEST", {})
db_settings["TEST"]["NAME"] = "{}_{}".format(test_name, suffix)
# ############### User visible fixtures ################
@pytest.fixture(scope="function")
0
Source : conftest.py
with MIT License
from instruct-br
with MIT License
from instruct-br
def pytest_configure(config):
from django.conf import settings
settings.configure(
DEBUG_PROPAGATE_EXCEPTIONS=True,
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
},
'secondary': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
}
},
SITE_ID=1,
SECRET_KEY='not very secret in tests',
USE_I18N=True,
USE_L10N=True,
STATIC_URL='/static/',
ROOT_URLCONF='tests.urls',
TEMPLATES=[
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
"debug": True, # We want template errors to raise
}
},
],
MIDDLEWARE=(
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
),
INSTALLED_APPS=(
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.staticfiles',
),
PASSWORD_HASHERS=(
'django.contrib.auth.hashers.MD5PasswordHasher',
),
)
django.setup()
0
Source : conftest.py
with ISC License
from jllorencetti
with ISC License
from jllorencetti
def pytest_configure():
from django.conf import settings
settings.configure(
DEBUG_PROPAGATE_EXCEPTIONS=True,
DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'}},
SITE_ID=1,
SECRET_KEY='not very secret in tests',
USE_I18N=True,
USE_L10N=True,
STATIC_URL='/static/',
ROOT_URLCONF='tests.urls',
TEMPLATE_LOADERS=(
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
),
MIDDLEWARE_CLASSES=(
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
),
INSTALLED_APPS=(
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'tests',
),
PASSWORD_HASHERS=(
'django.contrib.auth.hashers.SHA1PasswordHasher',
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.BCryptPasswordHasher',
'django.contrib.auth.hashers.MD5PasswordHasher',
'django.contrib.auth.hashers.CryptPasswordHasher',
),
)
try:
import oauth2 # NOQA
import oauth_provider # NOQA
except ImportError:
pass
else:
settings.INSTALLED_APPS += (
'oauth_provider',
)
try:
import provider # NOQA
except ImportError:
pass
else:
settings.INSTALLED_APPS += (
'provider',
'provider.oauth2',
)
# guardian is optional
try:
import guardian # NOQA
except ImportError:
pass
else:
settings.ANONYMOUS_USER_ID = -1
settings.AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'guardian.backends.ObjectPermissionBackend',
)
settings.INSTALLED_APPS += (
'guardian',
)
try:
import django
django.setup()
except AttributeError:
pass
0
Source : runtests.py
with MIT License
from jroslaniec
with MIT License
from jroslaniec
def run_tests():
# Making Django run this way is a two-step process. First, call
# config.configure() to give Django config to work with:
from django.conf import settings
settings.configure(**SETTINGS)
# Then, call django.setup() to initialize the application cache
# and other bits:
import django
if hasattr(django, 'setup'):
django.setup()
# Now we instantiate a test runner...
from django.test.utils import get_runner
TestRunner = get_runner(settings)
# And then we run tests and return the results.
test_runner = TestRunner(verbosity=2, interactive=True)
failures = test_runner.run_tests(['tests'])
sys.exit(bool(failures))
if __name__ == '__main__':
0
Source : runtests.py
with BSD 3-Clause "New" or "Revised" License
from kogan
with BSD 3-Clause "New" or "Revised" License
from kogan
def run_tests():
# First configure settings, then call django.setup() to initialise
from django.conf import settings
settings.configure(**SETTINGS_DICT)
import django
django.setup()
# Now create the test runner
from django.test.utils import get_runner
TestRunner = get_runner(settings)
# And then we run tests and return the results.
test_runner = TestRunner(verbosity=2, interactive=True)
failures = test_runner.run_tests(["tests"])
sys.exit(failures)
if __name__ == "__main__":
0
Source : base.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def execute(self, *args, **options):
"""
Try to execute this command, performing model validation if
needed (as controlled by the attribute
``self.requires_model_validation``, except if force-skipped).
"""
self.stdout = OutputWrapper(options.get('stdout', sys.stdout))
self.stderr = OutputWrapper(options.get('stderr', sys.stderr), self.style.ERROR)
if self.can_import_settings:
from django.conf import settings
saved_locale = None
if not self.leave_locale_alone:
# Only mess with locales if we can assume we have a working
# settings file, because django.utils.translation requires settings
# (The final saying about whether the i18n machinery is active will be
# found in the value of the USE_I18N setting)
if not self.can_import_settings:
raise CommandError("Incompatible values of 'leave_locale_alone' "
"(%s) and 'can_import_settings' (%s) command "
"options." % (self.leave_locale_alone,
self.can_import_settings))
# Switch to US English, because django-admin.py creates database
# content like permissions, and those shouldn't contain any
# translations.
from django.utils import translation
saved_locale = translation.get_language()
translation.activate('en-us')
try:
if self.requires_model_validation and not options.get('skip_validation'):
self.validate()
output = self.handle(*args, **options)
if output:
if self.output_transaction:
# This needs to be imported here, because it relies on
# settings.
from django.db import connections, DEFAULT_DB_ALIAS
connection = connections[options.get('database', DEFAULT_DB_ALIAS)]
if connection.ops.start_transaction_sql():
self.stdout.write(self.style.SQL_KEYWORD(connection.ops.start_transaction_sql()))
self.stdout.write(output)
if self.output_transaction:
self.stdout.write('\n' + self.style.SQL_KEYWORD("COMMIT;"))
finally:
if saved_locale is not None:
translation.activate(saved_locale)
def validate(self, app=None, display_num_errors=False):
0
Source : makemessages.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def handle_noargs(self, *args, **options):
locale = options.get('locale')
self.domain = options.get('domain')
self.verbosity = int(options.get('verbosity'))
process_all = options.get('all')
extensions = options.get('extensions')
self.symlinks = options.get('symlinks')
ignore_patterns = options.get('ignore_patterns')
if options.get('use_default_ignore_patterns'):
ignore_patterns += ['CVS', '.*', '*~', '*.pyc']
self.ignore_patterns = list(set(ignore_patterns))
self.wrap = '--no-wrap' if options.get('no_wrap') else ''
self.location = '--no-location' if options.get('no_location') else ''
self.no_obsolete = options.get('no_obsolete')
self.keep_pot = options.get('keep_pot')
if self.domain not in ('django', 'djangojs'):
raise CommandError("currently makemessages only supports domains "
"'django' and 'djangojs'")
if self.domain == 'djangojs':
exts = extensions if extensions else ['js']
else:
exts = extensions if extensions else ['html', 'txt']
self.extensions = handle_extensions(exts)
if (locale is None and not process_all) or self.domain is None:
raise CommandError("Type '%s help %s' for usage information." % (
os.path.basename(sys.argv[0]), sys.argv[1]))
if self.verbosity > 1:
self.stdout.write('examining files with the extensions: %s\n'
% get_text_list(list(self.extensions), 'and'))
# Need to ensure that the i18n framework is enabled
from django.conf import settings
if settings.configured:
settings.USE_I18N = True
else:
settings.configure(USE_I18N = True)
self.invoked_for_django = False
if os.path.isdir(os.path.join('conf', 'locale')):
localedir = os.path.abspath(os.path.join('conf', 'locale'))
self.invoked_for_django = True
# Ignoring all contrib apps
self.ignore_patterns += ['contrib/*']
elif os.path.isdir('locale'):
localedir = os.path.abspath('locale')
else:
raise CommandError("This script should be run from the Django Git "
"tree or your project or app tree. If you did indeed run it "
"from the Git checkout or your project or application, "
"maybe you are just missing the conf/locale (in the django "
"tree) or locale (for project and application) directory? It "
"is not created automatically, you have to create it by hand "
"if you want to enable i18n for your project or application.")
check_programs('xgettext')
potfile = self.build_pot_file(localedir)
# Build po files for each selected locale
locales = []
if locale is not None:
locales = locale
elif process_all:
locale_dirs = filter(os.path.isdir, glob.glob('%s/*' % localedir))
locales = [os.path.basename(l) for l in locale_dirs]
if locales:
check_programs('msguniq', 'msgmerge', 'msgattrib')
try:
for locale in locales:
if self.verbosity > 0:
self.stdout.write("processing locale %s\n" % locale)
self.write_po_file(potfile, locale)
finally:
if not self.keep_pot and os.path.exists(potfile):
os.unlink(potfile)
def build_pot_file(self, localedir):
0
Source : conftest.py
with ISC License
from mauricioabreu
with ISC License
from mauricioabreu
def pytest_configure():
from django.conf import settings
settings.configure(
DEBUG_PROPAGATE_EXCEPTIONS=True,
DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'}},
SITE_ID=1,
SECRET_KEY='not very secret in tests',
USE_I18N=True,
USE_L10N=True,
STATIC_URL='/static/',
ROOT_URLCONF='tests.urls',
TEMPLATE_LOADERS=(
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
),
MIDDLEWARE_CLASSES=(
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
),
INSTALLED_APPS=(
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'tests',
),
PASSWORD_HASHERS=(
'django.contrib.auth.hashers.SHA1PasswordHasher',
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.BCryptPasswordHasher',
'django.contrib.auth.hashers.MD5PasswordHasher',
'django.contrib.auth.hashers.CryptPasswordHasher',
),
REST_FRAMEWORK={
'DEFAULT_RENDERER_CLASSES': (
'rest_framework_orjson.renderers.ORJSONRenderer',
),
'DEFAULT_PARSER_CLASSES': (
'rest_framework_orjson.parsers.ORJSONParser',
),
},
)
try:
import oauth_provider # NOQA
import oauth2 # NOQA
except ImportError:
pass
else:
settings.INSTALLED_APPS += (
'oauth_provider',
)
try:
import provider # NOQA
except ImportError:
pass
else:
settings.INSTALLED_APPS += (
'provider',
'provider.oauth2',
)
# guardian is optional
try:
import guardian # NOQA
except ImportError:
pass
else:
settings.ANONYMOUS_USER_ID = -1
settings.AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'guardian.backends.ObjectPermissionBackend',
)
settings.INSTALLED_APPS += (
'guardian',
)
try:
import django
django.setup()
except AttributeError:
pass
0
Source : conftest.py
with MIT License
from Mng-dev-ai
with MIT License
from Mng-dev-ai
def pytest_configure(config):
from django.conf import settings
# USE_L10N is deprecated, and will be removed in Django 5.0.
use_l10n = {"USE_L10N": True} if django.VERSION < (4, 0) else {}
settings.configure(
DEBUG_PROPAGATE_EXCEPTIONS=True,
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
},
'secondary': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
}
},
SITE_ID=1,
SECRET_KEY='not very secret in tests',
USE_I18N=True,
MIDDLEWARE=(
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
),
INSTALLED_APPS=(
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'tests',
),
PASSWORD_HASHERS=(
'django.contrib.auth.hashers.MD5PasswordHasher',
),
**use_l10n,
)
django.setup()
0
Source : deal_antd_pages.py
with MIT License
from mtianyan
with MIT License
from mtianyan
def gen_antd_pages(project_name_settings, user_label_list, focus_model=None, template_type="base"):
init_django_env(project_name_settings)
import django
from django.conf import settings
if not user_label_list:
user_label_list = settings.TY_ADMIN_CONFIG["GEN_APPS"]
try:
force_cover = settings.TY_ADMIN_CONFIG['FORCED_COVER']
except KeyError:
force_cover = False
gen_labels = SYS_LABELS + user_label_list
model_pic_dict = {}
model_date_dict = {}
model_service_dict = {}
user = get_user_model()
model_list = django.apps.apps.get_models()
for one in model_list:
columns = []
model_name = one._meta.model.__name__
model_ver_name = trans(one._meta.verbose_name_raw)
app_name = one._meta.app_label
model_meta = one.objects.model._meta
if focus_model and model_name != focus_model:
continue
if app_name in gen_labels:
img_field_list = []
date_row_list = []
model_add_item_list = []
model_many_to_many_list = []
model_import_item_list = []
model_service_item_list = []
date_field_list = []
fields_count = len(model_meta.fields)
# 处理字段类型
for field in model_meta.fields:
field_name = field.name
# 进行第三方Field重写,优先级高
try:
cur_adapter = FIELD_ADAPTER[app_name][model_name][field_name]
except KeyError:
cur_adapter = None
if cur_adapter and adapter_priority(app_name, model_name, field_name, "index_import"):
model_import_item_list.append(cur_adapter["index_import"])
if cur_adapter and adapter_priority(app_name, model_name, field_name, "effect_state"):
model_add_item_list.append(cur_adapter["effect_state"])
if cur_adapter and adapter_priority(app_name, model_name, field_name, "services"):
model_service_item_list.append(cur_adapter["services"])
if cur_adapter and adapter_priority(app_name, model_name, field_name, "field"):
current_field = cur_adapter["field"]
elif isinstance(field, ForeignKey):
associated_model = field.related_model._meta.object_name
current_field = Field_Template_Factory(field)
# print(current_field)
field_first_up = field_name[0].upper() + field_name[1:]
model_add_item = f"""
const [{field_name}ForeignKeyList, set{field_first_up}ForeignKeyList] = useState([]);
useEffect(() => {{
query{associated_model}({{all: 1}}).then(value => {{
set{field_first_up}ForeignKeyList(value);
}});
}}, []);
const [{field_name}VerboseNameMap, set{field_first_up}VerboseNameMap] = useState([]);
useEffect(() => {{
query{associated_model}VerboseName().then(value => {{
set{field_first_up}VerboseNameMap(value);
}});
}}, []);"""
model_add_item_list.append(model_add_item)
model_import_item = f"""import {{query{associated_model}, query{associated_model}VerboseName}} from '@/pages/AutoGenPage/{associated_model}List/service';"""
if model_import_item not in model_import_item_list and model_name != associated_model:
# 外键self 处理
model_import_item_list.append(model_import_item)
elif isinstance(field, CharField):
current_field = Field_Template_Factory(field)
elif isinstance(field, DateTimeField):
current_field = Field_Template_Factory(field)
date_field_list.append('"' + field_name + '"')
date_row_list.append(f'record.{field_name} = record.{field_name} === null ? record.{field_name} : moment(record.{field_name});')
elif isinstance(field, DateField):
current_field = Field_Template_Factory(field)
date_field_list.append('"' + field_name + '"')
date_row_list.append(f'record.{field_name} = record.{field_name} === null ? record.{field_name} : moment(record.{field_name});')
elif isinstance(field, BooleanField):
current_field = Field_Template_Factory(field)
elif isinstance(field, IntegerField):
current_field = Field_Template_Factory(field)
elif isinstance(field, FloatField):
current_field = Field_Template_Factory(field)
elif isinstance(field, ImageField) or isinstance(field, SImageField):
img_field_list.append('"' + field_name + '"')
current_field = Field_Template_Factory(field)
elif isinstance(field, FileField):
img_field_list.append('"' + field_name + '"')
current_field = Field_Template_Factory(field)
elif isinstance(field, TextField):
current_field = Field_Template_Factory(field)
elif field.__class__.__name__ == "UEditorField" or isinstance(field, richTextField):
current_field = Field_Template_Factory(field)
elif field.__class__.__name__ == "TimeZoneField":
current_field = Field_Template_Factory(field)
else:
current_field = Field_Template_Factory(field)
# print(current_field)
model_pic_dict[model_name] = img_field_list
model_date_dict[model_name] = date_field_list
columns.append(current_field)
model_service_dict[model_name] = model_service_item_list
# 处理多对多关系
for field in model_meta.many_to_many:
associated_model = field.related_model._meta.object_name
if style_adapter_priority(app_name, model_name, field.name, "many_to_many"):
try:
many_style = settings.TY_ADMIN_CONFIG["REWRITE"][app_name][model_name][field.name]["many_to_many"]
except KeyError:
many_style = ty_admin_settings.TY_ADMIN_CONFIG["REWRITE"][app_name][model_name][field.name]["many_to_many"]
else:
many_style = None
current_field = Field_Template_Factory(field, many=True, manyStyle=many_style)
field_name = field.name
field_first_up = field_name[0].upper() + field_name[1:]
model_many_to_many_item = f"""const [{field.name}ManyToManyList, set{field_first_up}ManyToManyList] = useState([]);
useEffect(() => {{
query{associated_model}({{all:1}}).then(value => {{
set{field_first_up}ManyToManyList(value);
}});
}}, []);"""
model_many_to_many_list.append(model_many_to_many_item)
model_import_item = f"""import {{query{associated_model}}} from '@/pages/AutoGenPage/{associated_model}List/service';"""
if model_import_item not in model_import_item_list and model_name != associated_model:
model_import_item_list.append(model_import_item)
columns.append(current_field)
if app_name == user._meta.app_label and model_name == user._meta.object_name:
opera = UserOptionColumn.replace(">>MODEL_NAME < < ", model_ver_name)
else:
opera = GeneralOptionColumn.replace(">>MODEL_NAME < < ", model_ver_name)
opera = opera.replace(">>TIME_DEAL_PLACEHOLDER < < ", "".join(date_row_list))
columns.append(opera)
dest_path = f'{os.path.dirname(__file__)}/antd_page_templates/{template_type}'
with open(f'{dest_path}/index.jsx', encoding='utf-8') as fr:
content = fr.read()
if fields_count > 8:
new_content = content.replace(">>TWO_COLUMNS_COL < < ", "twoColumns")
else:
new_content = content.replace(">>TWO_COLUMNS_COL < < ", "{}")
new_content = new_content.replace(">>COLUMNS_LIST < < ", "".join(columns))
new_content = new_content.replace(">>MODEL_NAME < < ", model_name)
new_content = new_content.replace(">>MODEL_VERBOSE_NAME < < ", str(model_ver_name))
new_content = new_content.replace(">>FOREIGNKEY_PLACE < < ", "".join(model_add_item_list))
new_content = new_content.replace(">>MANY_TO_MANY_PLACE < < ", "".join(model_many_to_many_list))
new_content = new_content.replace(">>IMPORT_PLACE < < ", "".join(model_import_item_list))
new_content = new_content.replace(">>TIME_PLACE < < ", ",".join(model_date_dict[model_name]))
if app_name == user._meta.app_label and model_name == user._meta.object_name:
# 更新自己的密码
new_content = new_content.replace(">>PASSWORD_FORM < < ", PASSWORD_FORM)
new_content = new_content.replace(">>PASSWORD_PLACE < < ", PASSWORD_PLACE)
new_content = new_content.replace(">>UPDATE_PASSWORD_METHOD < < ", UPDATE_PASSWORD_METHOD)
new_content = new_content.replace(">>PASSWORD_UPDATE_FORM < < ", PASSWORD_UPDATE_FORM)
else:
new_content = new_content.replace(">>PASSWORD_FORM < < ", "")
new_content = new_content.replace(">>PASSWORD_PLACE < < ", '')
new_content = new_content.replace(">>UPDATE_PASSWORD_METHOD < < ", '')
new_content = new_content.replace(">>PASSWORD_UPDATE_FORM < < ", '')
with open(f'{dest_path}/service.js', encoding='utf-8') as fr:
content = fr.read()
new_services = content.replace(">>MODEL_NAME_LOWER_CASE < < ", get_lower_case_name(model_name))
new_services = new_services.replace(">>MODEL_NAME < < ", model_name)
new_services = new_services.replace(">>IMAGE_FIELD_LIST < < ", ",".join(model_pic_dict[model_name]))
new_services = new_services.replace(">>ADAPTER_SERVICE < < ", "\n".join(model_service_dict[model_name]))
if app_name == user._meta.app_label:
new_services = new_services.replace(">>UPDATE_PASSWORD_SERVICE < < ", """
export async function updateUserPassword(params) {
return request('/api/xadmin/v1/list_change_password', {
method: 'POST',
data: { ...params},
});
}""")
else:
new_services = new_services.replace(">>UPDATE_PASSWORD_SERVICE < < ", "")
with open(f'{dest_path}/components/CreateForm.jsx', encoding='utf-8') as fr:
create_form = fr.read()
create_form = create_form.replace(">>MODEL_VERBOSE_NAME < < ", str(model_ver_name))
if fields_count > 8:
create_form = create_form.replace(">>WIDTH_PLACEHOLDER < < ", 'width={1200}')
else:
create_form = create_form.replace(">>WIDTH_PLACEHOLDER < < ", "width={800}")
with open(f'{dest_path}/components/UpdateForm.jsx', encoding='utf-8') as fr:
update_form = fr.read()
update_form = update_form.replace(">>MODEL_VERBOSE_NAME < < ", str(model_ver_name))
if fields_count > 8:
update_form = update_form.replace(">>WIDTH_PLACEHOLDER < < ", 'width={1200}')
else:
update_form = update_form.replace(">>WIDTH_PLACEHOLDER < < ", "width={800}")
with open(f'{dest_path}/components/UpdatePasswordForm.jsx', encoding='utf-8') as fr:
change_password_form = fr.read()
target_path = f'{settings.BASE_DIR}/tyadmin/src/pages/AutoGenPage'
cur_path = f'{target_path}/{model_name}List'
if not os.path.exists(cur_path):
os.makedirs(cur_path)
cur_path_co = f'{target_path}/{model_name}List/components'
if not os.path.exists(cur_path_co):
os.makedirs(cur_path_co)
index_jsx_path = f'{target_path}/{model_name}List/index.jsx'
if not force_cover and os.path.exists(index_jsx_path):
pass
else:
with open(index_jsx_path, 'w', encoding='utf-8') as fw:
fw.write(new_content)
service_jsx_path = f'{target_path}/{model_name}List/service.js'
if not force_cover and os.path.exists(service_jsx_path):
pass
else:
with open(service_jsx_path, 'w', encoding='utf-8') as fw:
fw.write(new_services)
create_form_path = f'{target_path}/{model_name}List/components/CreateForm.jsx'
if not force_cover and os.path.exists(create_form_path):
pass
else:
with open(create_form_path, 'w', encoding='utf-8') as fw:
fw.write(create_form)
update_form_path = f'{target_path}/{model_name}List/components/UpdateForm.jsx'
if not force_cover and os.path.exists(update_form_path):
pass
else:
with open(update_form_path, 'w', encoding='utf-8') as fw:
fw.write(update_form)
if app_name == user._meta.app_label:
update_password_form_path = f'{target_path}/{model_name}List/components/UpdatePasswordForm.jsx'
if not force_cover and os.path.exists(update_password_form_path):
pass
else:
with open(update_password_form_path, 'w', encoding='utf-8') as fw:
fw.write(change_password_form)
if __name__ == '__main__':
0
Source : deal_antd_route.py
with MIT License
from mtianyan
with MIT License
from mtianyan
def gen_route(project_name_settings, user_label_list):
import django
from django.conf import settings
init_django_env(project_name_settings)
if not user_label_list:
user_label_list = settings.TY_ADMIN_CONFIG["GEN_APPS"]
# before
inner_before_list = ["\n".join([
"[",
"{",
" name: 'Home',",
" path: '/xadmin/index',",
" icon: 'dashboard',",
" component: './TyAdminBuiltIn/DashBoard'",
"}"]),
"\n".join([
"{",
" path: '/xadmin/',",
" redirect: '/xadmin/index',",
"}",
])]
# route
gen_labels = SYS_LABELS + user_label_list
gen_labels = [one for one in gen_labels if one != "contenttypes"]
menu_groups = OrderedDict()
menu_display_dict = {}
for model in django.apps.apps.get_models():
if model._meta.app_label not in gen_labels:
continue
# 中文
# group_name = model._meta.app_config.verbose_name
# model_name = trans(model._meta.verbose_name)
group_display = model._meta.app_config.verbose_name
group_name = model._meta.app_label
menu_display_dict[group_name] = group_display
model_name = model._meta.verbose_name
url = f'/xadmin/{group_name}/{get_lower_case_name(model._meta.model.__name__)}'
menu = "\n".join([
"{",
f" name: '{model_name}',",
f" path: '{url}',",
f" component: './AutoGenPage/{model._meta.model.__name__}List',",
"}",
])
if group_name not in menu_groups:
menu_groups[group_name] = []
menu_groups[group_name].append(menu)
group_route_list = inner_before_list
for group_name, route_list in menu_groups.items():
group_route = "\n".join([
"{",
f" name: '{menu_display_dict[group_name]}',",
" icon: 'BarsOutlined',",
f" path: '/xadmin/{group_name}',",
" routes:",
" [",
',\n'.join(route_list),
" ]"]) + "\n }"
group_route_list.append(group_route)
# after
group_route_list.append("\n".join([
"{",
" name: 'TyadminBuiltin',",
" icon: 'VideoCamera',",
" path: '/xadmin/sys',",
" routes:",
" [",
" {",
" name: 'TyAdminLog',",
" icon: 'smile',",
" path: '/xadmin/sys/ty_admin_sys_log',",
" component: './TyAdminBuiltIn/TyAdminSysLogList'",
" },",
" {",
" name: 'TyAdminVerify',",
" icon: 'smile',",
" path: '/xadmin/sys/ty_admin_email_verify_record',",
" component: './TyAdminBuiltIn/TyAdminEmailVerifyRecordList'",
" }",
" ]",
"}"]))
password_routes = '\n'.join([
" {",
" name: 'passwordModify',",
" path: '/xadmin/account/change_password',",
" hideInMenu: true,",
" icon: 'dashboard',",
" component: './TyAdminBuiltIn/ChangePassword',",
" }", ])
not_found_route = '\n'.join([
" {",
" component: './404',",
" },",
])
menu_string = ',\n'.join(group_route_list) + '\n]'
menu_string = format_json_string(menu_string)
group_route_list.append(password_routes)
group_route_list.append(not_found_route)
route_string = ',\n'.join(group_route_list) + '\n]'
route_string = format_json_string(route_string)
# Used for menu items loading from server side
path = f'{settings.BASE_DIR}/tyadmin_api/menu.json'
print(f'gen: {path}')
with open(path, 'w', encoding='utf-8') as fw:
fw.write(menu_string)
# Used for frontend url route in config.js
path = f'{settings.BASE_DIR}/tyadmin/config/routes.js'
print(f'gen: {path}')
with open(path, 'w', encoding='utf-8') as fw:
fw.write(route_string)
if __name__ == '__main__':
0
Source : gen_filter.py
with MIT License
from mtianyan
with MIT License
from mtianyan
def gen_filter(project_name_settings, user_label_list):
init_django_env(project_name_settings)
import django
from django.conf import settings
if not user_label_list:
user_label_list = settings.TY_ADMIN_CONFIG["GEN_APPS"]
model_list = []
model_pic_dict = {}
model_fk_dict = {}
model_date_dict = {}
app_model_import_dict = {}
gen_labels = SYS_LABELS + user_label_list
for model in django.apps.apps.get_models():
columns = []
model_name = model._meta.model.__name__
model_ver_name = model._meta.verbose_name
app_label = model._meta.app_label
import_path = get_model_import_path(model)
if app_label in gen_labels:
try:
app_model_import_dict[import_path].append(model_name)
except KeyError:
app_model_import_dict[import_path] = [model_name]
img_field_list = []
fk_field_list = []
date_field_list = []
for field in model.objects.model._meta.fields:
name = field.name
ver_name = field.verbose_name
if isinstance(field, ImageField):
img_field_list.append('"' + name + '"')
if isinstance(field, FileField):
img_field_list.append('"' + name + '"')
if isinstance(field, ForeignKey):
help_text = field.help_text.replace(MAIN_DISPLAY + "__", "")
fk_field_list.append(name + "$分割$" + help_text)
if isinstance(field, DateTimeField):
date_field_list.append(name)
if field.__class__.__name__ == "TimeZoneField":
img_field_list.append('"' + name + '"')
model_pic_dict[model_name] = img_field_list
model_fk_dict[model_name] = fk_field_list
model_date_dict[model_name] = date_field_list
model_list.append(model_name)
filters_txt = "\n".join(["from django_filters import rest_framework as filters",
"from tyadmin_api.custom import DateFromToRangeFilter",
f"$model_import占位$"])
model_import_rows = []
for import_path, m_list in app_model_import_dict.items():
txt = f'from {import_path}.models import {", ".join(m_list)}\n'
model_import_rows.append(txt)
model_import_rows = model_import_rows[:-1] + [model_import_rows[-1].replace("\n", "")]
filters_txt = filters_txt.replace("$model_import占位$", "".join(model_import_rows))
for (model, img_field_l), (model_2, fk_field_l), (model_3, date_field_l) in zip(model_pic_dict.items(), model_fk_dict.items(),
model_date_dict.items()):
fk_display_p = []
for one_fk in fk_field_l:
fk_name, fk_text = one_fk.split("$分割$")
fk_one_line = f' {fk_name}_text = filters.CharFilter(field_name="{fk_name}")\n'
fk_display_p.append(fk_one_line)
date_range_p = []
for one_date in date_field_l:
date_one_line = f' {one_date} = DateFromToRangeFilter(field_name="{one_date}")\n'
date_range_p.append(date_one_line)
filters_txt += "\n".join(["\n",
f"class {model}Filter(filters.FilterSet):",
f"{''.join(fk_display_p)}{''.join(date_range_p)}",
" class Meta:",
f" model = {model}",
f" exclude = [{','.join(img_field_l)}]",
])
# if os.path.exists(f'{settings.BASE_DIR}/tyadmin_api/auto_filters.py'):
# print("已存在filters.py跳过")
# else:
with open(f'{settings.BASE_DIR}/tyadmin_api/auto_filters.py', 'w', encoding='utf-8') as fw:
fw.write(filters_txt)
if __name__ == '__main__':
0
Source : gen_serializer.py
with MIT License
from mtianyan
with MIT License
from mtianyan
def gen_serializer(project_name_settings, user_label_list):
init_django_env(project_name_settings)
import django
from django.conf import settings
if not user_label_list:
user_label_list = settings.TY_ADMIN_CONFIG["GEN_APPS"]
model_list = []
model_fk_dict = {}
model_many_2_many_dict = {}
app_model_import_dict = {}
gen_labels = SYS_LABELS + user_label_list
finish_model_list = []
finish_many_list = []
for one in django.apps.apps.get_models():
columns = []
model_name = one._meta.model.__name__
model_ver_name = one._meta.verbose_name
app_label = one._meta.app_label
import_path = get_model_import_path(one)
if app_label in gen_labels:
fk_field_list = []
try:
app_model_import_dict[import_path].append(model_name)
except KeyError:
app_model_import_dict[import_path] = [model_name]
for field in one.objects.model._meta.fields:
name = field.name
ver_name = field.verbose_name
if isinstance(field, ForeignKey):
field_object_name = field.target_field.model._meta.object_name
fk_field_list.append(name + "$分割$" + field_object_name)
model_fk_dict[model_name] = fk_field_list
model_list.append(model_name)
many_2_many_list = []
for field in one.objects.model._meta.many_to_many:
name = field.name
rela_model = field.related_model._meta.object_name
# print("&&&" * 30)
# print(one._meta.app_label, one._meta.model.__name__, rela_model)
many_2_many_list.append(name + "$分割$" + rela_model)
# print("&&&" * 30)
model_many_2_many_dict[one._meta.model.__name__] = many_2_many_list
# status_text = serializers.CharField(source="status.text", read_only=True)
# print(model_fk_dict)
# print(model_many_2_many_dict)
app_name = "tyadmin_api"
serializers_txt = f"""from rest_framework import serializers
$model_import占位$"""
model_import_rows = []
for import_path, m_list in app_model_import_dict.items():
txt = f'from {import_path}.models import {", ".join(m_list)}\n'
model_import_rows.append(txt)
serializers_txt = serializers_txt.replace("$model_import占位$", "".join(model_import_rows))
# print(model_fk_dict)
wait_model_list = list(model_fk_dict.keys())
for (model, fk_field_l), (_, many_2) in zip(model_fk_dict.items(), model_many_2_many_dict.items()):
fk_display_p = inner_deal_foreign(model, fk_field_l, many_2)
fk_list = model_fk_dict[model]
my_list = model_many_2_many_dict[model]
if len(fk_list) == 0 and len(my_list) == 0:
serializers_txt = gen_ser_txt(serializers_txt, model, fk_display_p)
wait_model_list.remove(model)
finish_model_list.append(model)
finish_many_list.append(model)
for model in wait_model_list:
fk_display_p = inner_deal_foreign(model, model_fk_dict[model], model_many_2_many_dict[model])
serializers_txt = gen_ser_txt(serializers_txt, model, fk_display_p)
# serializers_txt = deal_write(finish_model_list, model_fk_dict, model_many_2_many_dict, serializers_txt, wait_model_list, finish_many_list)
#
# if os.path.exists(f'{settings.BASE_DIR}/tyadmin_api/auto_serializers.py'):
# print("已存在serializers跳过")
# else:
with open(f'{settings.BASE_DIR}/tyadmin_api/auto_serializers.py', 'w', encoding='utf-8') as fw:
fw.write(serializers_txt)
def inner_deal_foreign(model, fk_field_l, many_2):
0
Source : gen_url.py
with MIT License
from mtianyan
with MIT License
from mtianyan
def gen_url(project_name_settings, user_label_list):
init_django_env(project_name_settings)
import django
from django.conf import settings
model_list = []
model_fk_dict = {}
app_model_import_dict = {}
gen_labels = SYS_LABELS + user_label_list
for one in django.apps.apps.get_models():
columns = []
model_name = one._meta.model.__name__
model_ver_name = one._meta.verbose_name
app_label = one._meta.app_label
if app_label in gen_labels:
model_list.append(model_name)
url_txt = f"""from tyadmin_api import auto_views
from django.urls import re_path, include, path
from rest_framework.routers import DefaultRouter
router = DefaultRouter(trailing_slash=False)
"""
for model_name in model_list:
url_txt += f"""
router.register('{get_lower_case_name(model_name)}', auto_views.{model_name}ViewSet)
"""
url_txt += """
urlpatterns = [
re_path('^', include(router.urls)),
]
"""
# if os.path.exists(f'{settings.BASE_DIR}/tyadmin_api/auto_url.py'):
# print("已存在urls跳过")
# else:
with open(f'{settings.BASE_DIR}/tyadmin_api/auto_url.py', 'w', encoding='utf-8') as fw:
fw.write(url_txt)
if __name__ == '__main__':
0
Source : gen_view.py
with MIT License
from mtianyan
with MIT License
from mtianyan
def gen_view(project_name_settings, user_label_list):
init_django_env(project_name_settings)
import django
from django.conf import settings
if not user_label_list:
user_label_list = settings.TY_ADMIN_CONFIG["GEN_APPS"]
model_list = []
app_name = "tyadmin_api"
model_search_dict = {}
app_model_import_dict = {}
gen_labels = SYS_LABELS + user_label_list
for one in django.apps.apps.get_models():
model_name = one._meta.model.__name__
model_ver_name = one._meta.verbose_name
app_label = one._meta.app_label
import_path = get_model_import_path(one)
if app_label in gen_labels:
try:
app_model_import_dict[import_path].append(model_name)
except KeyError:
app_model_import_dict[import_path] = [model_name]
search_list = []
model_list.append(model_name)
for field in one.objects.model._meta.fields:
name = field.name
ver_name = field.verbose_name
if isinstance(field, CharField):
search_list.append('"' + name + '"')
elif isinstance(field, CharField):
search_list.append('"' + name + '"')
model_search_dict[model_name] = search_list
serializers_list = [one + "ListSerializer" for one in model_list]
serializers_update_list = [one + "CreateUpdateSerializer" for one in model_list]
filters_list = [one + "Filter" for one in model_list]
viewset_txt = f"""
from rest_framework import viewsets
from tyadmin_api.custom import XadminViewSet
$model_import占位$
from {app_name}.auto_serializers import {", ".join(serializers_list)}
from {app_name}.auto_serializers import {", ".join(serializers_update_list)}
from {app_name}.auto_filters import {", ".join(filters_list)}
"""
model_import_rows = []
for import_path, m_list in app_model_import_dict.items():
print(m_list)
txt = f'from {import_path}.models import {", ".join(m_list)}\n'
model_import_rows.append(txt)
viewset_txt = viewset_txt.replace("$model_import占位$", "".join(model_import_rows))
for model_name in model_list:
viewset_txt += f"""
class {model_name}ViewSet(XadminViewSet):
serializer_class = {model_name}ListSerializer
queryset = {model_name}.objects.all().order_by('-pk')
filter_class = {model_name}Filter
search_fields = [{",".join(model_search_dict[model_name])}]
def get_serializer_class(self):
if self.action == "list":
return {model_name}ListSerializer
else:
return {model_name}CreateUpdateSerializer
"""
with open(f'{settings.BASE_DIR}/tyadmin_api/auto_views.py', 'w', encoding='utf-8') as fw:
fw.write(viewset_txt)
if __name__ == '__main__':
0
Source : setup.py
with MIT License
from palewire
with MIT License
from palewire
def run(self):
import django
from django.conf import settings
from django.core.management import call_command
settings.configure(
DATABASES={
'default': {
'NAME': 'test',
'USER': 'postgres',
'ENGINE': 'django.contrib.gis.db.backends.postgis'
},
},
MEDIA_ROOT="media",
INSTALLED_APPS=("anss",),
)
django.setup()
call_command('test', 'anss')
setup(
0
Source : conftest.py
with MIT License
from PostHog
with MIT License
from PostHog
def pytest_configure():
from django.conf import settings
settings.configure(
SECRET_KEY="#mk0y8q%rh!ieekh5h#39b@a99u3eg$93kc9oq#z1kpzvg+k2_",
INSTALLED_APPS=[
"django.contrib.contenttypes",
"django.contrib.auth",
"rest_framework",
"test_project.test_app",
],
ROOT_URLCONF="test_project.mysite.urls",
DATABASES={
"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}
},
REST_FRAMEWORK={
"EXCEPTION_HANDLER": "exceptions_hog.exception_handler",
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework.authentication.BasicAuthentication",
],
},
)
try:
import django
django.setup()
except AttributeError:
pass
@pytest.fixture
0
Source : conftest.py
with MIT License
from ridi
with MIT License
from ridi
def pytest_configure():
from django.conf import settings
settings.configure(
DEBUG_PROPAGATE_EXCEPTIONS=True,
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
}
},
SITE_ID=1,
SECRET_KEY='not very secret in tests',
USE_I18N=True,
USE_L10N=True,
STATIC_URL='/static/',
TEMPLATE_LOADERS=(
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
),
MIDDLEWARE_CLASSES=(
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
),
INSTALLED_APPS=(
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'test',
),
)
try:
import django
django.setup()
except AttributeError:
pass
0
Source : conftest.py
with MIT License
from SomeoneInParticular
with MIT License
from SomeoneInParticular
def pytest_configure():
from django.conf import settings
settings.configure(
DEBUG=True,
TEMPLATE_DEBUG=True,
SECRET_KEY='T35TK3Y',
DATABASES={
'default': {
'ENGINE': 'djongo',
'NAME': 'default'
}
},
INSTALLED_APPS=(
'rest_framework',
'rest_meets_djongo',
'tests'
)
)
try:
import django
django.setup()
except AttributeError as err:
print(err)
0
Source : runtests.py
with BSD 3-Clause "New" or "Revised" License
from ubernostrum
with BSD 3-Clause "New" or "Revised" License
from ubernostrum
def run_tests():
# Making Django run this way is a two-step process. First, call
# settings.configure() to give Django settings to work with:
from django.conf import settings
settings.configure(**SETTINGS_DICT)
# Then, call django.setup() to initialize the application cache
# and other bits:
import django
django.setup()
# Now we instantiate a test runner...
from django.test.utils import get_runner
TestRunner = get_runner(settings)
# And then we run tests and return the results.
test_runner = TestRunner(verbosity=2, interactive=True)
failures = test_runner.run_tests(
['django_referrer_policy.tests']
)
sys.exit(bool(failures))
if __name__ == '__main__':
0
Source : runtests.py
with BSD 3-Clause "New" or "Revised" License
from ubernostrum
with BSD 3-Clause "New" or "Revised" License
from ubernostrum
def run_tests():
# Making Django run this way is a two-step process. First, call
# settings.configure() to give Django settings to work with:
from django.conf import settings
settings.configure(**SETTINGS_DICT)
# Then, call django.setup() to initialize the application registry
# and other bits:
import django
django.setup()
# Now we instantiate a test runner...
from django.test.utils import get_runner
TestRunner = get_runner(settings)
# And then we run tests and return the results.
test_runner = TestRunner(verbosity=2, interactive=True)
failures = test_runner.run_tests(["tests"])
sys.exit(failures)
if __name__ == "__main__":
0
Source : runtests.py
with MIT License
from webstack
with MIT License
from webstack
def run_tests():
# Making Django run this way is a two-step process. First, call
# settings.configure() to give Django settings to work with:
from django.conf import settings
# Then, call django.setup() to initialize the application registry
# and other bits:
import django
django.setup()
# Now we instantiate a test runner...
from django.test.utils import get_runner
TestRunner = get_runner(settings)
# And then we run tests and return the results.
test_runner = TestRunner(verbosity=2, interactive=True)
failures = test_runner.run_tests(["tests"])
sys.exit(failures)
if __name__ == "__main__":
0
Source : conftest.py
with MIT License
from WinterFramework
with MIT License
from WinterFramework
def pytest_configure():
from django.conf import settings
app_dir = Path(__file__)
settings.configure(
ROOT_URLCONF='tests.urls',
REST_FRAMEWORK={
'DEFAULT_RENDERER_CLASSES': ('winter_django.renderers.JSONRenderer',),
'UNAUTHENTICATED_USER': Guest,
},
TEMPLATES=[
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [app_dir.parent.name + '/templates'],
'APP_DIRS': True,
'OPTIONS': {
'debug': True, # We want template errors to raise
},
},
],
INSTALLED_APPS=(
# Hack for making module discovery working
'django.contrib.admin',
'django.contrib.contenttypes',
# End hack
'tests',
),
)
injector = Injector([Configuration])
set_injector(injector)
django.setup()
class Configuration(Module):
0
Source : runtests.py
with MIT License
from xuchaoa
with MIT License
from xuchaoa
def setup(verbosity, test_labels):
from django.conf import settings
state = {
'INSTALLED_APPS': settings.INSTALLED_APPS,
'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""),
'TEMPLATE_DIRS': settings.TEMPLATE_DIRS,
'USE_I18N': settings.USE_I18N,
'LOGIN_URL': settings.LOGIN_URL,
'LANGUAGE_CODE': settings.LANGUAGE_CODE,
'MIDDLEWARE_CLASSES': settings.MIDDLEWARE_CLASSES,
'STATIC_URL': settings.STATIC_URL,
'STATIC_ROOT': settings.STATIC_ROOT,
}
# Redirect some settings for the duration of these tests.
settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS
settings.ROOT_URLCONF = 'urls'
settings.STATIC_URL = '/static/'
settings.STATIC_ROOT = os.path.join(TEMP_DIR, 'static')
settings.TEMPLATE_DIRS = (os.path.join(RUNTESTS_DIR, TEST_TEMPLATE_DIR),)
settings.USE_I18N = True
settings.LANGUAGE_CODE = 'en'
settings.MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.common.CommonMiddleware',
)
settings.SITE_ID = 1
# For testing comment-utils, we require the MANAGERS attribute
# to be set, so that a test email is sent out which we catch
# in our tests.
settings.MANAGERS = ("[email protected]",)
# Load all the ALWAYS_INSTALLED_APPS.
# (This import statement is intentionally delayed until after we
# access settings because of the USE_I18N dependency.)
# Load all the test model apps.
test_labels_set = set([label.split('.')[0] for label in test_labels])
test_modules = get_test_modules()
for module_name in test_modules:
module_label = module_name
# if the module was named on the command line, or
# no modules were named (i.e., run all), import
# this module and add it to the list to test.
if not test_labels or module_name in test_labels_set:
if verbosity >= 2:
print("Importing application %s" % module_name)
if module_label not in settings.INSTALLED_APPS:
settings.INSTALLED_APPS.append(module_label)
django.setup()
[a.models_module for a in apps.get_app_configs()]
return state
def teardown(state):
0
Source : match_monitor.py
with GNU General Public License v3.0
from YukkuriC
with GNU General Public License v3.0
from YukkuriC
def unit_monitor(type, name, data, error_logger=None):
'''
比赛维护进程
每个监控进程维护一个比赛进程
监控数据库获取其维护比赛的状态,并进行中止等操作
'''
# 初始化
setup_django()
from django.conf import settings
from time import perf_counter as pf, sleep
from match_sys import models
from . import helpers
from .factory import Factory
# 重定向错误输出
if error_logger:
import sys
sys.stdout = sys.stderr = queue_io(error_logger)
# 运行比赛进程
match_dir = os.path.join(settings.PAIRMATCH_DIR, name)
os.makedirs(match_dir, exist_ok=1)
if type == None: # 扩展区域
pass
else: # 默认type=='match'一对一比赛
AI_type, params = data
match_process = Factory(AI_type, name, params, error_logger)
match_process.start()
# 循环监测运行状态与数据库
cycle = 0
while 1:
# 检查运行状况
now = pf()
if not match_process.check_active(now):
break
# 检查数据库注册条目
cycle += 1
if cycle >= settings.MONITOR_DB_CHECK_CYCLE:
cycle -= settings.MONITOR_DB_CHECK_CYCLE
match_process.reload_match()
if match_process.match.status == -1: # 外部中止
match_process.timeout = -1
sleep(settings.MONITOR_CYCLE) # 待机
def start_match(AI_type,
0
Source : conftest.py
with ISC License
from zapier
with ISC License
from zapier
def pytest_configure():
from django.conf import settings
settings.configure(
DEBUG_PROPAGATE_EXCEPTIONS=True,
DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'}},
SITE_ID=1,
SECRET_KEY='not very secret in tests',
USE_I18N=True,
USE_L10N=True,
STATIC_URL='/static/',
ROOT_URLCONF='tests.urls',
TEMPLATE_LOADERS=(
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
),
MIDDLEWARE_CLASSES=(
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
),
INSTALLED_APPS=(
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'tests',
),
PASSWORD_HASHERS=(
'django.contrib.auth.hashers.SHA1PasswordHasher',
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.BCryptPasswordHasher',
'django.contrib.auth.hashers.MD5PasswordHasher',
'django.contrib.auth.hashers.CryptPasswordHasher',
),
)
try:
import oauth_provider # NOQA
import oauth2 # NOQA
except ImportError:
pass
else:
settings.INSTALLED_APPS += (
'oauth_provider',
)
try:
import provider # NOQA
except ImportError:
pass
else:
settings.INSTALLED_APPS += (
'provider',
'provider.oauth2',
)
# guardian is optional
try:
import guardian # NOQA
except ImportError:
pass
else:
settings.ANONYMOUS_USER_ID = -1
settings.AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'guardian.backends.ObjectPermissionBackend',
)
settings.INSTALLED_APPS += (
'guardian',
)
try:
import django
django.setup()
except AttributeError:
pass
0
Source : runtests.py
with MIT License
from zecollokaris
with MIT License
from zecollokaris
def run_tests():
# Making Django run this way is a two-step process. First, call
# settings.configure() to give Django settings to work with:
from django.conf import settings
settings.configure(**SETTINGS_DICT)
# Then, call django.setup() to initialize the application cache
# and other bits:
import django
if hasattr(django, 'setup'):
django.setup()
# Now we instantiate a test runner...
from django.test.utils import get_runner
TestRunner = get_runner(settings)
# And then we run tests and return the results.
test_runner = TestRunner(verbosity=2, interactive=True)
failures = test_runner.run_tests(['registration.tests'])
sys.exit(bool(failures))
if __name__ == '__main__':