Ticket #87: management.py

File management.py, 25.4 KB (added by Jason Huggins, 19 years ago)
Line 
1# Django management-related functions, including "CREATE TABLE" generation and
2# development-server initialization.
3
4import django
5import os, re, sys
6
7MODULE_TEMPLATE = ''' {%% if perms.%(app)s.%(addperm)s or perms.%(app)s.%(changeperm)s %%}
8 <tr>
9 <th>{%% if perms.%(app)s.%(changeperm)s %%}<a href="%(app)s/%(mod)s/">{%% endif %%}%(name)s{%% if perms.%(app)s.%(changeperm)s %%}</a>{%% endif %%}</th>
10 <td class="x50">{%% if perms.%(app)s.%(addperm)s %%}<a href="%(app)s/%(mod)s/add/" class="addlink">{%% endif %%}Add{%% if perms.%(app)s.%(addperm)s %%}</a>{%% endif %%}</td>
11 <td class="x75">{%% if perms.%(app)s.%(changeperm)s %%}<a href="%(app)s/%(mod)s/" class="changelink">{%% endif %%}Change{%% if perms.%(app)s.%(changeperm)s %%}</a>{%% endif %%}</td>
12 </tr>
13 {%% endif %%}'''
14
15APP_ARGS = '[app app ...]'
16
17# Use django.__path__[0] because we don't know which directory django into
18# which has been installed.
19PROJECT_TEMPLATE_DIR = os.path.join(django.__path__[0], 'conf/%s_template')
20ADMIN_TEMPLATE_DIR = os.path.join(django.__path__[0], 'conf/admin_templates')
21
22def _get_packages_insert(app_label):
23 return "INSERT INTO packages (label, name) VALUES ('%s', '%s')" % (app_label, app_label)
24
25def _get_permission_codename(action, opts):
26 return '%s_%s' % (action, opts.object_name.lower())
27
28def _get_all_permissions(opts):
29 "Returns (codename, name) for all permissions in the given opts."
30 perms = []
31 if opts.admin:
32 for action in ('add', 'change', 'delete'):
33 perms.append((_get_permission_codename(action, opts), 'Can %s %s' % (action, opts.verbose_name)))
34 return perms + list(opts.permissions)
35
36def _get_permission_insert(name, codename, opts):
37 return "INSERT INTO auth_permissions (name, package, codename) VALUES ('%s', '%s', '%s')" % \
38 (name.replace("'", "''"), opts.app_label, codename)
39
40def _get_contenttype_insert(opts):
41 return "INSERT INTO content_types (name, package, python_module_name) VALUES ('%s', '%s', '%s')" % \
42 (opts.verbose_name, opts.app_label, opts.module_name)
43
44def _is_valid_dir_name(s):
45 return bool(re.search(r'^\w+$', s))
46
47def get_sql_create(mod):
48 "Returns a list of the CREATE TABLE SQL statements for the given module."
49 from django.core import db, meta
50 final_output = []
51 for klass in mod._MODELS:
52 opts = klass._meta
53 table_output = []
54 for f in opts.fields:
55 if isinstance(f, meta.ForeignKey):
56 rel_field = f.rel.get_related_field()
57 # If the foreign key points to an AutoField, the foreign key
58 # should be an IntegerField, not an AutoField. Otherwise, the
59 # foreign key should be the same type of field as the field
60 # to which it points.
61 if rel_field.__class__.__name__ == 'AutoField':
62 data_type = 'IntegerField'
63 else:
64 data_type = rel_field.__class__.__name__
65 else:
66 rel_field = f
67 data_type = f.__class__.__name__
68 col_type = db.DATA_TYPES[data_type]
69 if col_type is not None:
70 field_output = [f.name, col_type % rel_field.__dict__]
71 field_output.append('%sNULL' % (not f.null and 'NOT ' or ''))
72 if f.unique:
73 field_output.append('UNIQUE')
74 if f.primary_key:
75 field_output.append('PRIMARY KEY')
76 if f.rel:
77 field_output.append('REFERENCES %s (%s)' % \
78 (f.rel.to.db_table, f.rel.to.get_field(f.rel.field_name).name))
79 table_output.append(' '.join(field_output))
80 if opts.order_with_respect_to:
81 table_output.append('_order %s NULL' % db.DATA_TYPES['IntegerField'])
82 for field_constraints in opts.unique_together:
83 table_output.append('UNIQUE (%s)' % ", ".join(field_constraints))
84
85 full_statement = ['CREATE TABLE %s (' % opts.db_table]
86 for i, line in enumerate(table_output): # Combine and add commas.
87 full_statement.append(' %s%s' % (line, i < len(table_output)-1 and ',' or ''))
88 full_statement.append(')')
89 final_output.append('\n'.join(full_statement))
90
91 if (db.DATABASE_ENGINE == 'oracle') & (opts.has_auto_field):
92 # To simulate auto-incrementing primary keys in Oracle
93
94 sequence_statement = 'CREATE SEQUENCE %s_sq\n' % opts.db_table
95 final_output.append(sequence_statement)
96
97 trigger_statement = "" + \
98 "CREATE OR REPLACE trigger %s_tr\n" % opts.db_table + \
99 " before insert on %s\n" % opts.db_table + \
100 " for each row\n" + \
101 " begin\n" + \
102 " select %s_sq.NEXTVAL into :new.id from DUAL;\n" % opts.db_table + \
103 " end;\n"
104 final_output.append(trigger_statement)
105
106
107
108 for klass in mod._MODELS:
109 opts = klass._meta
110 for f in opts.many_to_many:
111 table_output = ['CREATE TABLE %s (' % f.get_m2m_db_table(opts)]
112 table_output.append(' id %s NOT NULL PRIMARY KEY,' % db.DATA_TYPES['AutoField'])
113 table_output.append(' %s_id %s NOT NULL REFERENCES %s (%s),' % \
114 (opts.object_name.lower(), db.DATA_TYPES['IntegerField'], opts.db_table, opts.pk.name))
115 table_output.append(' %s_id %s NOT NULL REFERENCES %s (%s),' % \
116 (f.rel.to.object_name.lower(), db.DATA_TYPES['IntegerField'], f.rel.to.db_table, f.rel.to.pk.name))
117 table_output.append(' UNIQUE (%s_id, %s_id)' % (opts.object_name.lower(), f.rel.to.object_name.lower()))
118 table_output.append(')')
119 final_output.append('\n'.join(table_output))
120
121 if (db.DATABASE_ENGINE == 'oracle') & (opts.has_auto_field):
122 sequence_statement = 'CREATE SEQUENCE %s_sq\n' % f.get_m2m_db_table(opts)
123 final_output.append(sequence_statement)
124
125 trigger_statement = "" + \
126 "CREATE OR REPLACE trigger %s_tr\n" % f.get_m2m_db_table(opts) + \
127 " before insert on %s\n" % f.get_m2m_db_table(opts) + \
128 " for each row\n" + \
129 " begin\n" + \
130 " select %s_sq.NEXTVAL into :new.id from DUAL;\n" % f.get_m2m_db_table(opts) + \
131 " end;\n"
132 final_output.append(trigger_statement)
133
134 return final_output
135get_sql_create.help_doc = "Prints the CREATE TABLE SQL statements for the given app(s)."
136get_sql_create.args = APP_ARGS
137
138def get_sql_delete(mod):
139 "Returns a list of the DROP TABLE SQL statements for the given module."
140 from django.core import db
141 try:
142 cursor = db.db.cursor()
143 except:
144 cursor = None
145 output = []
146 for klass in mod._MODELS:
147 try:
148 if cursor is not None:
149 # Check whether the table exists.
150 cursor.execute("SELECT COUNT(1) FROM %s" % klass._meta.db_table)
151 except:
152 # The table doesn't exist, so it doesn't need to be dropped.
153 db.db.rollback()
154 else:
155 output.append("DROP TABLE %s;" % klass._meta.db_table)
156 if db.DATABASE_ENGINE == 'oracle':
157 output.append("DROP SEQUENCE %s_sq" % klass._meta.db_table)
158
159 for klass in mod._MODELS:
160 opts = klass._meta
161 for f in opts.many_to_many:
162 try:
163 if cursor is not None:
164 cursor.execute("SELECT COUNT(1) FROM %s" % f.get_m2m_db_table(opts))
165 except:
166 db.db.rollback()
167 else:
168 output.append("DROP TABLE %s;" % f.get_m2m_db_table(opts))
169 if db.DATABASE_ENGINE == 'oracle':
170 output.append("DROP SEQUENCE %s_sq" % f.get_m2m_db_table(opts))
171 app_label = mod._MODELS[0]._meta.app_label
172
173 # Delete from packages, auth_permissions, content_types.
174 output.append("DELETE FROM packages WHERE label = '%s';" % app_label)
175 output.append("DELETE FROM auth_permissions WHERE package = '%s';" % app_label)
176 output.append("DELETE FROM content_types WHERE package = '%s';" % app_label)
177
178 # Delete from the admin log.
179 if cursor is not None:
180 cursor.execute("SELECT id FROM content_types WHERE package = %s", [app_label])
181 for row in cursor.fetchall():
182 output.append("DELETE FROM auth_admin_log WHERE content_type_id = %s;" % row[0])
183
184 return output[::-1] # Reverse it, to deal with table dependencies.
185get_sql_delete.help_doc = "Prints the DROP TABLE SQL statements for the given app(s)."
186get_sql_delete.args = APP_ARGS
187
188def get_sql_reset(mod):
189 "Returns a list of the DROP TABLE SQL, then the CREATE TABLE SQL, for the given module."
190 return get_sql_delete(mod) + get_sql_all(mod)
191get_sql_reset.help_doc = "Prints the DROP TABLE SQL, then the CREATE TABLE SQL, for the given app(s)."
192get_sql_reset.args = APP_ARGS
193
194def get_sql_initial_data(mod):
195 "Returns a list of the initial INSERT SQL statements for the given module."
196 output = []
197 app_label = mod._MODELS[0]._meta.app_label
198 output.append(_get_packages_insert(app_label))
199 app_dir = os.path.normpath(os.path.join(os.path.dirname(mod.__file__), '../sql'))
200 for klass in mod._MODELS:
201 opts = klass._meta
202 # Add custom SQL, if it's available.
203 sql_file_name = os.path.join(app_dir, opts.module_name + '.sql')
204 if os.path.exists(sql_file_name):
205 fp = open(sql_file_name, 'r')
206 output.append(fp.read())
207 fp.close()
208 # Content types.
209 output.append(_get_contenttype_insert(opts))
210 # Permissions.
211 for codename, name in _get_all_permissions(opts):
212 output.append(_get_permission_insert(name, codename, opts))
213 return output
214get_sql_initial_data.help_doc = "Prints the initial INSERT SQL statements for the given app(s)."
215get_sql_initial_data.args = APP_ARGS
216
217def get_sql_sequence_reset(mod):
218 "Returns a list of the SQL statements to reset PostgreSQL sequences for the given module."
219 from django.core import db, meta
220 output = []
221 for klass in mod._MODELS:
222 for f in klass._meta.fields:
223 if isinstance(f, meta.AutoField):
224 if db.DATABASE_ENGINE == 'postgresql':
225 output.append("SELECT setval('%s_%s_seq', (SELECT max(%s) FROM %s));" % (klass._meta.db_table, f.name, f.name, klass._meta.db_table))
226 else:
227 raise "Not implemented yet for %s!" % (db.DATABASE_ENGINE)
228 return output
229get_sql_sequence_reset.help_doc = "Prints the SQL statements for resetting PostgreSQL sequences for the given app(s)."
230get_sql_sequence_reset.args = APP_ARGS
231
232def get_sql_indexes(mod):
233 "Returns a list of the CREATE INDEX SQL statements for the given module."
234 output = []
235 for klass in mod._MODELS:
236 for f in klass._meta.fields:
237 if f.db_index:
238 unique = f.unique and "UNIQUE " or ""
239 output.append("CREATE %sINDEX %s_%s ON %s (%s);" % \
240 (unique, klass._meta.db_table, f.name, klass._meta.db_table, f.name))
241 return output
242get_sql_indexes.help_doc = "Prints the CREATE INDEX SQL statements for the given app(s)."
243get_sql_indexes.args = APP_ARGS
244
245def get_sql_all(mod):
246 "Returns a list of CREATE TABLE SQL and initial-data insert for the given module."
247 return get_sql_create(mod) + get_sql_initial_data(mod)
248get_sql_all.help_doc = "Prints the CREATE TABLE and initial-data SQL statements for the given app(s)."
249get_sql_all.args = APP_ARGS
250
251def database_check(mod):
252 "Checks that everything is properly installed in the database for the given module."
253 from django.core import db
254 cursor = db.db.cursor()
255 app_label = mod._MODELS[0]._meta.app_label
256
257 # Check that the package exists in the database.
258 cursor.execute("SELECT 1 FROM packages WHERE label = %s", [app_label])
259 if cursor.rowcount < 1:
260# sys.stderr.write("The '%s' package isn't installed.\n" % app_label)
261 print _get_packages_insert(app_label)
262
263 # Check that the permissions and content types are in the database.
264 perms_seen = {}
265 contenttypes_seen = {}
266 for klass in mod._MODELS:
267 opts = klass._meta
268 perms = _get_all_permissions(opts)
269 perms_seen.update(dict(perms))
270 contenttypes_seen[opts.module_name] = 1
271 for codename, name in perms:
272 cursor.execute("SELECT 1 FROM auth_permissions WHERE package = %s AND codename = %s", (app_label, codename))
273 if cursor.rowcount < 1:
274# sys.stderr.write("The '%s.%s' permission doesn't exist.\n" % (app_label, codename))
275 print _get_permission_insert(name, codename, opts)
276 cursor.execute("SELECT 1 FROM content_types WHERE package = %s AND python_module_name = %s", (app_label, opts.module_name))
277 if cursor.rowcount < 1:
278# sys.stderr.write("The '%s.%s' content type doesn't exist.\n" % (app_label, opts.module_name))
279 print _get_contenttype_insert(opts)
280
281 # Check that there aren't any *extra* permissions in the DB that the model
282 # doesn't know about.
283 cursor.execute("SELECT codename FROM auth_permissions WHERE package = %s", (app_label,))
284 for row in cursor.fetchall():
285 try:
286 perms_seen[row[0]]
287 except KeyError:
288# sys.stderr.write("A permission called '%s.%s' was found in the database but not in the model.\n" % (app_label, row[0]))
289 print "DELETE FROM auth_permissions WHERE package='%s' AND codename = '%s';" % (app_label, row[0])
290
291 # Check that there aren't any *extra* content types in the DB that the
292 # model doesn't know about.
293 cursor.execute("SELECT python_module_name FROM content_types WHERE package = %s", (app_label,))
294 for row in cursor.fetchall():
295 try:
296 contenttypes_seen[row[0]]
297 except KeyError:
298# sys.stderr.write("A content type called '%s.%s' was found in the database but not in the model.\n" % (app_label, row[0]))
299 print "DELETE FROM content_types WHERE package='%s' AND python_module_name = '%s';" % (app_label, row[0])
300database_check.help_doc = "Checks that everything is installed in the database for the given app(s) and prints SQL statements if needed."
301database_check.args = APP_ARGS
302
303def get_admin_index(mod):
304 "Returns admin-index template snippet (in list form) for the given module."
305 from django.utils.text import capfirst
306 output = []
307 app_label = mod._MODELS[0]._meta.app_label
308 output.append('{%% if perms.%s %%}' % app_label)
309 output.append('<div class="module"><h2>%s</h2><table>' % app_label.title())
310 for klass in mod._MODELS:
311 if klass._meta.admin:
312 output.append(MODULE_TEMPLATE % {
313 'app': app_label,
314 'mod': klass._meta.module_name,
315 'name': capfirst(klass._meta.verbose_name_plural),
316 'addperm': klass._meta.get_add_permission(),
317 'changeperm': klass._meta.get_change_permission(),
318 })
319 output.append('</table></div>')
320 output.append('{% endif %}')
321 return output
322get_admin_index.help_doc = "Prints the admin-index template snippet for the given app(s)."
323get_admin_index.args = APP_ARGS
324
325def init():
326 "Initializes the database with auth and core."
327 from django.core import db, meta
328 auth = meta.get_app('auth')
329 core = meta.get_app('core')
330 try:
331 cursor = db.db.cursor()
332 for sql in get_sql_create(core) + get_sql_create(auth) + get_sql_initial_data(core) + get_sql_initial_data(auth):
333 cursor.execute(sql)
334 cursor.execute("INSERT INTO %s (domain, name) VALUES ('mysite.com', 'My Django site')" % core.Site._meta.db_table)
335 except Exception, e:
336 sys.stderr.write("Error: The database couldn't be initialized. Here's the full exception:\n%s\n" % e)
337 db.db.rollback()
338 sys.exit(1)
339 db.db.commit()
340init.args = ''
341
342def install(mod):
343 "Executes the equivalent of 'get_sql_all' in the current database."
344 from django.core import db
345 sql_list = get_sql_all(mod)
346 try:
347 cursor = db.db.cursor()
348 for sql in sql_list:
349 cursor.execute(sql)
350 except Exception, e:
351 mod_name = mod.__name__[mod.__name__.rindex('.')+1:]
352 sys.stderr.write("""Error: %s couldn't be installed. Possible reasons:
353 * The database isn't running or isn't configured correctly.
354 * At least one of the database tables already exists.
355 * The SQL was invalid.
356Hint: Look at the output of 'django-admin.py sqlall %s'. That's the SQL this command wasn't able to run.
357The full error: %s\n""" % \
358 (mod_name, mod_name, e))
359 db.db.rollback()
360 sys.exit(1)
361 db.db.commit()
362install.help_doc = "Executes ``sqlall`` for the given app(s) in the current database."
363install.args = APP_ARGS
364
365def _start_helper(app_or_project, name, directory, other_name=''):
366 other = {'project': 'app', 'app': 'project'}[app_or_project]
367 if not _is_valid_dir_name(name):
368 sys.stderr.write("Error: %r is not a valid %s name. Please use only numbers, letters and underscores.\n" % (name, app_or_project))
369 sys.exit(1)
370 top_dir = os.path.join(directory, name)
371 try:
372 os.mkdir(top_dir)
373 except OSError, e:
374 sys.stderr.write("Error: %s\n" % e)
375 sys.exit(1)
376 template_dir = PROJECT_TEMPLATE_DIR % app_or_project
377 for d, subdirs, files in os.walk(template_dir):
378 relative_dir = d[len(template_dir)+1:].replace('%s_name' % app_or_project, name)
379 if relative_dir:
380 os.mkdir(os.path.join(top_dir, relative_dir))
381 for i, subdir in enumerate(subdirs):
382 if subdir.startswith('.'):
383 del subdirs[i]
384 for f in files:
385 if f.endswith('.pyc'):
386 continue
387 fp_old = open(os.path.join(d, f), 'r')
388 fp_new = open(os.path.join(top_dir, relative_dir, f.replace('%s_name' % app_or_project, name)), 'w')
389 fp_new.write(fp_old.read().replace('{{ %s_name }}' % app_or_project, name).replace('{{ %s_name }}' % other, other_name))
390 fp_old.close()
391 fp_new.close()
392
393def startproject(project_name, directory):
394 "Creates a Django project for the given project_name in the given directory."
395 from random import choice
396 _start_helper('project', project_name, directory)
397 # Populate TEMPLATE_DIRS for the admin templates, based on where Django is
398 # installed.
399 admin_settings_file = os.path.join(directory, project_name, 'settings/admin.py')
400 settings_contents = open(admin_settings_file, 'r').read()
401 fp = open(admin_settings_file, 'w')
402 settings_contents = re.sub(r'(?s)\b(TEMPLATE_DIRS\s*=\s*\()(.*?)\)', "\\1\n '%s',\\2)" % ADMIN_TEMPLATE_DIR, settings_contents)
403 fp.write(settings_contents)
404 fp.close()
405 # Create a random SECRET_KEY hash, and put it in the main settings.
406 main_settings_file = os.path.join(directory, project_name, 'settings/main.py')
407 settings_contents = open(main_settings_file, 'r').read()
408 fp = open(main_settings_file, 'w')
409 secret_key = ''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])
410 settings_contents = re.sub(r"(?<=SECRET_KEY = ')'", secret_key + "'", settings_contents)
411 fp.write(settings_contents)
412 fp.close()
413startproject.help_doc = "Creates a Django project directory structure for the given project name in the current directory."
414startproject.args = "[projectname]"
415
416def startapp(app_name, directory):
417 "Creates a Django app for the given project_name in the given directory."
418 # Determine the project_name a bit naively -- by looking at the name of
419 # the parent directory.
420 project_dir = os.path.normpath(os.path.join(directory, '../'))
421 project_name = os.path.basename(project_dir)
422 _start_helper('app', app_name, directory, project_name)
423startapp.help_doc = "Creates a Django app directory structure for the given app name in the current directory."
424startapp.args = "[appname]"
425
426def createsuperuser():
427 "Creates a superuser account."
428 from django.core import validators
429 from django.models.auth import users
430 import getpass
431 try:
432 while 1:
433 username = raw_input('Username (only letters, digits and underscores): ')
434 if not username.isalnum():
435 sys.stderr.write("Error: That username is invalid.\n")
436 continue
437 try:
438 users.get_object(username__exact=username)
439 except users.UserDoesNotExist:
440 break
441 else:
442 sys.stderr.write("Error: That username is already taken.\n")
443 while 1:
444 email = raw_input('E-mail address: ')
445 try:
446 validators.isValidEmail(email, None)
447 except validators.ValidationError:
448 sys.stderr.write("Error: That e-mail address is invalid.\n")
449 else:
450 break
451 while 1:
452 password = getpass.getpass()
453 password2 = getpass.getpass('Password (again): ')
454 if password != password2:
455 sys.stderr.write("Error: Your passwords didn't match.\n")
456 continue
457 if password.strip() == '':
458 sys.stderr.write("Error: Blank passwords aren't allowed.\n")
459 continue
460 break
461 except KeyboardInterrupt:
462 sys.stderr.write("\nOperation cancelled.\n")
463 sys.exit(1)
464 u = users.create_user(username, email, password)
465 u.is_staff = True
466 u.is_active = True
467 u.is_superuser = True
468 u.save()
469 print "User created successfully."
470createsuperuser.args = ''
471
472def inspectdb(db_name):
473 "Generator that introspects the tables in the given database name and returns a Django model, one line at a time."
474 from django.core import db
475 from django.conf import settings
476
477 def table2model(table_name):
478 object_name = table_name.title().replace('_', '')
479 return object_name.endswith('s') and object_name[:-1] or object_name
480
481 settings.DATABASE_NAME = db_name
482 cursor = db.db.cursor()
483 yield "# This is an auto-generated Django model module."
484 yield "# You'll have to do the following manually to clean this up:"
485 yield "# * Rearrange models' order"
486 yield "# * Add primary_key=True to one field in each model."
487 yield "# Feel free to rename the models, but don't rename db_table values or field names."
488 yield "#"
489 yield "# Also note: You'll have to insert the output of 'django-admin.py sqlinitialdata [appname]'"
490 yield "# into your database."
491 yield ''
492 yield 'from django.core import meta'
493 yield ''
494 for table_name in db.get_table_list(cursor):
495 yield 'class %s(meta.Model):' % table2model(table_name)
496 yield ' db_table = %r' % table_name
497 yield ' fields = ('
498 try:
499 relations = db.get_relations(cursor, table_name)
500 except NotImplementedError:
501 relations = {}
502 cursor.execute("SELECT * FROM %s LIMIT 1" % table_name)
503 for i, row in enumerate(cursor.description):
504 if relations.has_key(i):
505 rel = relations[i]
506 rel_to = rel[1] == table_name and "'self'" or table2model(rel[1])
507 field_desc = 'meta.ForeignKey(%s, name=%r' % (rel_to, row[0])
508 else:
509 try:
510 field_type = db.DATA_TYPES_REVERSE[row[1]]
511 except KeyError:
512 field_type = 'TextField'
513 yield " # The model-creator script used TextField by default, because"
514 yield " # it couldn't recognize your field type."
515 field_desc = 'meta.%s(%r' % (field_type, row[0])
516 if field_type == 'CharField':
517 field_desc += ', maxlength=%s' % (row[3])
518 yield ' %s),' % field_desc
519 yield ' )'
520 yield ''
521inspectdb.help_doc = "Introspects the database tables in the given database and outputs a Django model module."
522inspectdb.args = "[dbname]"
523
524def runserver(port):
525 "Starts a lightweight Web server for development."
526 from django.core.servers.basehttp import run, WSGIServerException
527 from django.core.handlers.wsgi import AdminMediaHandler, WSGIHandler
528 if not port.isdigit():
529 sys.stderr.write("Error: %r is not a valid port number.\n" % port)
530 sys.exit(1)
531 def inner_run():
532 from django.conf.settings import SETTINGS_MODULE
533 print "Starting server on port %s with settings module %r." % (port, SETTINGS_MODULE)
534 print "Go to http://127.0.0.1:%s/ for Django." % port
535 print "Quit the server with CONTROL-C (Unix) or CTRL-BREAK (Windows)."
536 try:
537 run(int(port), AdminMediaHandler(WSGIHandler()))
538 except WSGIServerException, e:
539 # Use helpful error messages instead of ugly tracebacks.
540 ERRORS = {
541 13: "You don't have permission to access that port.",
542 98: "That port is already in use.",
543 }
544 try:
545 error_text = ERRORS[e.args[0].args[0]]
546 except (AttributeError, KeyError):
547 error_text = str(e)
548 sys.stderr.write("Error: %s\n" % error_text)
549 sys.exit(1)
550 except KeyboardInterrupt:
551 sys.exit(0)
552 from django.utils import autoreload
553 autoreload.main(inner_run)
554runserver.args = '[optional port number]'
Back to Top