def fixed_sql_model_create(model, known_models, style): from django.db import connection if version == 'trunk': from django.db import connection return connection.creation.sql_create_model(model, style, known_models) elif version == '0.97': return management.sql_model_create(model, style, known_models) else: return management._get_sql_model_create(model, known_models)
def install(model): from django.core.management import sql, color from django.db import connection style = color.no_style() cursor = connection.cursor() statements, pending = sql.sql_model_create(model, style) for sql in statements: cursor.execute(sql)
def get_create_table(models): from django.core.management.color import no_style style = no_style() from django.core.management import sql statements = [] for model in models: statements += sql.sql_model_create(model, style)[0] statements += sql.sql_indexes_for_model(model, style) statements += sql.custom_sql_for_model(model) return statements
def create_sequence(name, initial_value=1, final_value=None): model = create_model(name) if not sequence_exists(name): style = color.no_style() cursor = connection.cursor() statements, pending = sql.sql_model_create(model, style) for sql in statements: cursor.execute(sql) set_limits(name, initial_value=1, final_value=None)
def install(model): # Standard syncdb expects models to be in reliable locations, # so dynamic models need to bypass django.core.management.syncdb. # On the plus side, this allows individual models to be installed # without installing the entire project structure. # On the other hand, this means that things like relationships and # indexes will have to be handled manually. # This installs only the basic table definition. # disable terminal colors in the sql statements style = color.no_style() cursor = connection.cursor() statements, pending = sql.sql_model_create(model, style) for sql in statements: cursor.execute(sql)
def teste_banco(request): app = load_app("modulos.noticia") app = import_module("modulos.noticia.admin") raise Exception(app) connection = connections["default"] style = color.no_style() criar = sql.sql_create(app, style, connection) raise Exception(criar) raise Exception(path) cor = color.no_style model = import_module("modulos.noticia.models") cursor = connection.cursor() statements, pending = sql.sql_model_create(model, style)
def install(model): from django.core.management import sql, color from django.db import connection style = color.no_style() cursor = connection.cursor() statements, pending = sql.sql_model_create(model, style) for sql in statements: cursor.execute(sql) # def create_db_table(model_class): # """ Takes a Django model class and create a database table, if necessary. # """ # # XXX Create related tables for ManyToMany etc # db.start_transaction() # table_name = model_class._meta.db_table # # # Introspect the database to see if it doesn't already exist # if (connection.introspection.table_name_converter(table_name) # not in connection.introspection.table_names()): # # fields = _get_fields(model_class) # # db.create_table(table_name, fields) # # Some fields are added differently, after table creation # # eg GeoDjango fields # db.execute_deferred_sql() # logger.debug("Created table '%s'" % table_name) # # db.commit_transaction() # # def delete_db_table(model_class): # table_name = model_class._meta.db_table # db.start_transaction() # db.delete_table(table_name) # logger.debug("Deleted table '%s'" % table_name) # db.commit_transaction() # # def write(request, type, num, sensor, storage): # n=num # s=Sensor.objects.filter(index=sensor).filter(storage__index__exact=storage) # storage=Storage.objects.get(index=storage) # for s1 in s: # if type == 'air': # for i in range(num): # a=Air() # a.sensor_index = s1 # a.storage=storage # a.temp=uniform(15,25) # a.hum=uniform(15,25) # a.time=datetime.datetime(2014, 12, 22, randint(0, 24), randint(0, 60), 0) # a.save() # return redirect('storagemanage') # def data(request, id): # sensor=Sensor.objects.get(id=id) # rlist = [] # rlist.append({"id" : id, "addr" : sensor.addr, "type" : sensor.type, "storage": sensor.storage}) # rjson = json.dumps(rlist) # response = HttpResponse() # response['Content-Type'] = "text/javascript" # response.write(rjson) # return response # def ShowNode(request,Station): # nodes_list = NodeInfo.objects.filter(station__station__exact = Station) # nlist=[] # for node in nodes_list: # nlist.append({"index":node.index, "status":node.status}) # sjson=json.dumps(nlist) # response=HttpResponse() # response['Content-type']="text/javascript" # response.write(sjson) # return response # def test(request): # nodes_list = NodeInfo.objects.filter(station__id__exact = 1) # num=nodes_list.all().count() # y=np.arange(num) # for i in range(len(y)): # y[i]=nodes_list[i].index # # # def func(i): # # return a[i] # # #x=np.linspace(1,num,10) # x=np.arange(num) # plot(x,y,'--*b') # savefig('/home/nero/myfig.svg') # # return redirect("/")
class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option( '--verbosity', action='store', dest='verbosity', default='1', type='choice', choices=['0', '1', '2'], help= 'Verbosity level; 0=minimal output, 1=normal output, 2=all output' ), make_option( '--noinput', action='store_false', dest='interactive', default=True, help='Tells Django to NOT prompt the user for input of any kind.'), ) help = "Create the database tables for all apps in INSTALLED_APPS whose tables haven't already been created." def handle_noargs(self, **options): from django.db import connection, transaction, models from django.conf import settings from django.core.management.sql import table_names, installed_models, sql_model_create, sql_for_pending_references, many_to_many_sql_for_model, custom_sql_for_model, sql_indexes_for_model, emit_post_sync_signal verbosity = int(options.get('verbosity', 1)) interactive = options.get('interactive') show_traceback = options.get('traceback', False) self.style = no_style() # Import the 'management' module within each installed app, to register # dispatcher events. for app_name in settings.INSTALLED_APPS: try: __import__(app_name + '.management', {}, {}, ['']) except ImportError, exc: # This is slightly hackish. We want to ignore ImportErrors # if the "management" module itself is missing -- but we don't # want to ignore the exception if the management module exists # but raises an ImportError for some reason. The only way we # can do this is to check the text of the exception. Note that # we're a bit broad in how we check the text, because different # Python implementations may not use the same text. # CPython uses the text "No module named management" # PyPy uses "No module named myproject.myapp.management" msg = exc.args[0] if not msg.startswith( 'No module named') or 'management' not in msg: raise cursor = connection.cursor() if connection.features.uses_case_insensitive_names: table_name_converter = lambda x: x.upper() else: table_name_converter = lambda x: x # Get a list of all existing database tables, so we know what needs to # be added. tables = [table_name_converter(name) for name in table_names()] # Get a list of already installed *models* so that references work right. seen_models = installed_models(tables) created_models = set() pending_references = {} # Create the tables for each model for app in models.get_apps(): app_name = app.__name__.split('.')[-2] model_list = models.get_models(app) for model in model_list: # Create the model's database table, if it doesn't already exist. if verbosity >= 2: print "Processing %s.%s model" % (app_name, model._meta.object_name) if table_name_converter(model._meta.db_table) in tables: continue sql, references = sql_model_create(model, self.style, seen_models) seen_models.add(model) created_models.add(model) for refto, refs in references.items(): pending_references.setdefault(refto, []).extend(refs) if refto in seen_models: sql.extend( sql_for_pending_references(refto, self.style, pending_references)) sql.extend( sql_for_pending_references(model, self.style, pending_references)) if verbosity >= 1: print "Creating table %s" % model._meta.db_table for statement in sql: cursor.execute(statement) tables.append(table_name_converter(model._meta.db_table)) # Create the m2m tables. This must be done after all tables have been created # to ensure that all referred tables will exist. for app in models.get_apps(): app_name = app.__name__.split('.')[-2] model_list = models.get_models(app) for model in model_list: if model in created_models: sql = many_to_many_sql_for_model(model, self.style) if sql: if verbosity >= 2: print "Creating many-to-many tables for %s.%s model" % ( app_name, model._meta.object_name) for statement in sql: cursor.execute(statement) transaction.commit_unless_managed() # Send the post_syncdb signal, so individual apps can do whatever they need # to do at this point. emit_post_sync_signal(created_models, verbosity, interactive) # The connection may have been closed by a syncdb handler. cursor = connection.cursor() # Install custom SQL for the app (but only if this # is a model we've just created) for app in models.get_apps(): app_name = app.__name__.split('.')[-2] for model in models.get_models(app): if model in created_models: custom_sql = custom_sql_for_model(model) if custom_sql: if verbosity >= 1: print "Installing custom SQL for %s.%s model" % ( app_name, model._meta.object_name) try: for sql in custom_sql: cursor.execute(sql) except Exception, e: sys.stderr.write("Failed to install custom SQL for %s.%s model: %s\n" % \ (app_name, model._meta.object_name, e)) if show_traceback: import traceback traceback.print_exc() transaction.rollback_unless_managed() else: transaction.commit_unless_managed() else: if verbosity >= 2: print "No custom SQL for %s.%s model" % ( app_name, model._meta.object_name)
def fixed_sql_model_create(model, known_models, style): if version == 'trunk': return management.sql_model_create( model, style, known_models ) else: return management._get_sql_model_create( model, known_models )
def handle_noargs(self, **options): from django.db import connection, transaction, models from django.conf import settings from django.core.management.sql import table_names, installed_models, sql_model_create, sql_for_pending_references, many_to_many_sql_for_model, custom_sql_for_model, sql_indexes_for_model, emit_post_sync_signal verbosity = int(options.get('verbosity', 1)) interactive = options.get('interactive') show_traceback = options.get('traceback', False) self.style = no_style() # Import the 'management' module within each installed app, to register # dispatcher events. for app_name in settings.INSTALLED_APPS: try: __import__(app_name + '.management', {}, {}, ['']) except ImportError as exc: # This is slightly hackish. We want to ignore ImportErrors # if the "management" module itself is missing -- but we don't # want to ignore the exception if the management module exists # but raises an ImportError for some reason. The only way we # can do this is to check the text of the exception. Note that # we're a bit broad in how we check the text, because different # Python implementations may not use the same text. # CPython uses the text "No module named management" # PyPy uses "No module named myproject.myapp.management" msg = exc.args[0] if not msg.startswith('No module named') or 'management' not in msg: raise cursor = connection.cursor() if connection.features.uses_case_insensitive_names: table_name_converter = lambda x: x.upper() else: table_name_converter = lambda x: x # Get a list of all existing database tables, so we know what needs to # be added. tables = [table_name_converter(name) for name in table_names()] # Get a list of already installed *models* so that references work right. seen_models = installed_models(tables) created_models = set() pending_references = {} # Create the tables for each model for app in models.get_apps(): app_name = app.__name__.split('.')[-2] model_list = models.get_models(app) for model in model_list: # Create the model's database table, if it doesn't already exist. if verbosity >= 2: print("Processing %s.%s model" % (app_name, model._meta.object_name)) if table_name_converter(model._meta.db_table) in tables: continue sql, references = sql_model_create(model, self.style, seen_models) seen_models.add(model) created_models.add(model) for refto, refs in list(references.items()): pending_references.setdefault(refto, []).extend(refs) if refto in seen_models: sql.extend(sql_for_pending_references(refto, self.style, pending_references)) sql.extend(sql_for_pending_references(model, self.style, pending_references)) if verbosity >= 1: print("Creating table %s" % model._meta.db_table) for statement in sql: cursor.execute(statement) tables.append(table_name_converter(model._meta.db_table)) # Create the m2m tables. This must be done after all tables have been created # to ensure that all referred tables will exist. for app in models.get_apps(): app_name = app.__name__.split('.')[-2] model_list = models.get_models(app) for model in model_list: if model in created_models: sql = many_to_many_sql_for_model(model, self.style) if sql: if verbosity >= 2: print("Creating many-to-many tables for %s.%s model" % (app_name, model._meta.object_name)) for statement in sql: cursor.execute(statement) transaction.commit_unless_managed() # Send the post_syncdb signal, so individual apps can do whatever they need # to do at this point. emit_post_sync_signal(created_models, verbosity, interactive) # The connection may have been closed by a syncdb handler. cursor = connection.cursor() # Install custom SQL for the app (but only if this # is a model we've just created) for app in models.get_apps(): app_name = app.__name__.split('.')[-2] for model in models.get_models(app): if model in created_models: custom_sql = custom_sql_for_model(model) if custom_sql: if verbosity >= 1: print("Installing custom SQL for %s.%s model" % (app_name, model._meta.object_name)) try: for sql in custom_sql: cursor.execute(sql) except Exception as e: sys.stderr.write("Failed to install custom SQL for %s.%s model: %s\n" % \ (app_name, model._meta.object_name, e)) if show_traceback: import traceback traceback.print_exc() transaction.rollback_unless_managed() else: transaction.commit_unless_managed() else: if verbosity >= 2: print("No custom SQL for %s.%s model" % (app_name, model._meta.object_name)) # Install SQL indicies for all newly created models for app in models.get_apps(): app_name = app.__name__.split('.')[-2] for model in models.get_models(app): if model in created_models: index_sql = sql_indexes_for_model(model, self.style) if index_sql: if verbosity >= 1: print("Installing index for %s.%s model" % (app_name, model._meta.object_name)) try: for sql in index_sql: cursor.execute(sql) except Exception as e: sys.stderr.write("Failed to install index for %s.%s model: %s\n" % \ (app_name, model._meta.object_name, e)) transaction.rollback_unless_managed() else: transaction.commit_unless_managed() # Install the 'initial_data' fixture, using format discovery from django.core.management import call_command call_command('loaddata', 'initial_data', verbosity=verbosity)