Sei sulla pagina 1di 10

Django run-through Install through command line, or pip/ etc? I'm using python 2.6.

.6.5 Environment setup (from http://www.saltycrane.com/blog/2009/05/notes-using-pip-andvirtualenv-django/)


Required installations: Easy Install: sudo apt-get install python-setuptools python-dev build-essential

pip: sudo easy_install -U pip virtualenv: sudo pip install -U virtualenv Setting up virtual environment:
Make directory for virtual environments: sudo mkdir -p /srv/pythonenvironments, cd /srv/python-environments Make a specific virtual environment: sudo virtualenv --no-sitepackages --distribute env_name(learning_django) Install package yolk, which tells which packages are instaled: sudo pip install -E env_name yolk

activate environment (from working directory python-environments): source env_name/bin/activate Is the virtual environment worthwhile right now? Or jump into django on my system asis? Use virtual environment until proves too complicated. Use mod_python? (long-running processes such as keeping db connections open) Could use this to create a virtual environment for each student in a class? Install django to virtual environment: sudo pip install -E env_name Django (installs django 1.3 on 10.04. Installs to python_environments/lib/python2.6/sitepackages/django) learn to shorten command prompt in terminal? Does installing to virtual environment take up significant disk space? (ie multiple copies of python, django, etc - I believe so.) Freeze requirements: sudo pip freeze - E env_name > requirements.txt done from py-env working directory, with env deactivated (may work with env activated as well) stores requirements.txt in env_name directory needed to chmod a+w python_env from /srv working directory used to re-create this environment with exact libraries used in this environment I believe to do this, I would create the environment on a different computer/ virtual machine, using the same virtual environment name; copy the requirements file to that directory; run "sudo pip install -E env_name -r /srv/env_name/piprequirements.txt" Next: mod_python, or mod_wsgi? My guess is mod_python, may not need to decide right now. Might work to just jump into using django in the virtual environment. Nice that this environment is isolated from the rest of my machine!

Need to install apache, mysql to this virtual environment? I can't imagine not needing mysql in the virtual env. Test by running it on my system, and on virtual env. Appears to already have access to mysql, because get message I'm not allowed. Try installing to virtual environment? Then after setting up a mysql account for django_programs or something like that, try accessing that account through my system, outside virtual env. Use pip to install virtual env. Next: install mysql to virtual environment, give django proper access. This is a security point, so set up account properly, ie not just for django but for a specific django app? In a VPS hosting environment, do I install my own instance of apache? Look at a tutorial/ guide to setting up an ubuntu server on a VPS environment, preferably linode. Next, briefly: install mysql to virtual env; set django to use mysql?; build sample django site/ app Seem to be unable to install mysql itself to the virtual environment; may be limited to one version of mysql on a system? Can be done, but not worthwhile right now. Need to install from source and compile with certain custom parameters, like where to listen for db connections. Check out virtualenvwrapper, which eases use of virtualenv, especially things like switching between environments. May be less meaningful if I only have one environment, or don't switch often. Check out fabric. Used for deployment, one-step rather than many ssh commands. Next: Start using django in sample environment; add /srv to backup script. Server questions: apache or something lighter like inginx? Does ubuntu server use one of these by default? Separate installation in virtualenv, or use system server? On a VPS, do I install my own server? Can I run more than one website from a VPS? Do I need to take care of DNS setup and propagation on a VPS? mod_wsgi: embedded or daemon mode? Ubuntu server does not have a windowing system by default. Explore git and github at some point? apache with mod_wsgi Where install apache? system, or virtualenv? how set up mod_wsgi? daemon mode or embedded mode? daemon mode for different users on the same server? daemon mode better choice, requires less tuning of apache (from wsgi docs). Needs apache 2.0 or 2.2, compiled with support for threading. python installation must have been compiled with threading support as well. going to go with the apache instance installed on my system, since apache used for serving multiple sites. If it were a VPS, I'd have apache on my virtual server. I would not have multiple instances of apache on an ubuntu server machine. But, I will install mod_wsgi to the virtual environment, and point it to the python in my virtual environment. Scrap that, mod_wsgi is in synaptic, so I will install to system until need to do otherwise. Installing "libapache2-mod-wsgi", which is mod-wsgi2.8 (done); I have the "apache2" metapackage installed, which is apache 2.2.14, a highspeed threaded model. For the record, I also have the mysql-server and mysql-client metapackages installed, which is mysql 5.1.41. python-mysqldb is also installed to the system. Could install mod_wsgi from source, compiling to use specific python version, but rather specify that from the virtual environment.

Script all of this from the practice django_learning environment, and set up as much as possible of the CDB django project by running one script? Configuring apache: apache stop/ start: "/etc/init.d/apache2 stop" start Added line "LoadModule wsgi_module modules/mod_wsgi.so" to httpd.conf (/etc/apache2/httpd.conf) Restarted server. Seems that wsgi was already enabled (ran "apache2ctl -t -D DUMP_MODULES) before restarting server. Restarting tells me I did not need that LoadModule line, because "module wsgi_module" is already loaded. Still need to tell it to use python from the virtual environment. Believe that will happen through settings within the virtual environment, not in apache itself. After restarting apache, simple python CBE site still works. Start issue tracker, rather than just these notes! Modified httpd.conf as described at https://docs.djangoproject.com/en/1.3/howto/deployment/modwsgi/
WSGIScriptAlias / /path/to/mysite/apache/django.wsgi

WSGIScriptAlias / /srv/pythonenvironments/learning_django/apache/django.wsgi need to restart apache? Actually restart, or just reread httpd.conf? created django.wsgi in project directory in virtual environment - mysite.settings or project_name.settings? created learning_django.settings, empty file for now. further modified httpd.conf to serve static files After restarting apache2, original cdb site no longer works; 500 error. Just 'deactivate' to stop virtual environment Configure mysql Install dependencies to regular system: sudo apt-get build-dep python-mysqldb Within virtual environment, install mysql-db: sudo pip install -E env_name MySQL-python Django uses SQL corresponding to database specified in settings file working from "Django at a glance" - no, but might be useful Starting a project creates a settings file working from Writing your first Django app, part 1 establish a project, "learning_django" from directory where project code will be stored: "django-admin.py startproject mysite" Make sure this code is outside of the document root (set in apache httpd.conf) (security issue) MySQL configuration u root, pw eR new user ld_user@localhost, pw learning_django CREATE USER ld_user@localhost IDENTIFIED BY 'learning_django'; mysql -u uname -p CREATE DATABASE IF NOT EXISTS learning_django_db CHARACTER SET

utf8; GRANT ALTER, CREATE, SELECT, INSERT, UPDATE, DELETE, INDEX, LOCK TABLES ON learning_django_db.* TO ld_user@localhost; not sure if necessarily needs INDEX privilege, but probably should! Do NOT do this while using mysql db, because grants these privileges on db being used. How make sure appropriate engine? InnoDB? expects support of transactions and referential integrity current mysql installation using myisam table types by default 'ALTER TABLE t1 ENGINE=InnoDB' changed /etc/mysql/my.cnf to include line 'default-storage-engine=innodb', restarted mysql server 'sudo service mysql restart' - verify by 'show engines' that innodb is now default. check table type: 'SHOW TABLE STATUS WHERE name=table_name' edit settings.py most straightforward. Do not specify @localhost in user setting. Can specify this in host, or leave host blank. python manage.py syncdb gets error unable to CREATE. need specify host, or need server running when issue command? connecting to database, because changing user to ld_userr causes msyql access error. ld_user is not able to create (CREATE command denied to user 'ld_user'@'localhost') problem was grant privileges statement - privileges granted on db.table, not just db. To grant on all tables, 'grant privileges on db.* to user@host' Does my backup script back up my mysql databases? believe data stored in /var/lib/mysql, but this directory is non-inspectable 'python manage.py runserver' starts development server does closing that terminal stop the server? If so, run invisibly? Stop if running, restart, or just start? running 'python manage.py syncdb' creates tables installs auth system; create superuser? yes; username ld_superuser, pw learning_django very happy to be using mysql, and not be learning a new db syntax was using isam, so drop database and recreate database in mysql console, then run syncdb Creating models projects v. apps: "An app is a Web application that does something -- e.g., a Weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular Web site. A project can contain multiple apps. An app can be in multiple projects." models: A model is the single, definitive source of data about your data. It contains the essential fields and behaviors of the data you're storing. Django follows the DRY Principle. The goal is to define your data model in one place and automatically derive things from it. create an app

'python manage.py startapp app_name' - creates directory structure for app basic steps: create models edit installed apps in settings.py run syncdb add __unicode__() methods to model classes emacs reconfigure emacs to open currently used default directory review dired commands useful commands 'python manage.py sql app_name' - shows the sql django uses to implement app in db 'python manage.py validate' - checks for errors in construction of models 'python manage.py sqlindex app_name' - generates the sql to create indexes in db for this app Need to run this manually to optimize - no, syncdb runs sql from 'sqlall app_name' 'python manage.py shell' - opens an interactive shell that lets you use the django api After changing files, need to quit and start new shell to see effects 'object.save()' - saves an object into the database This affects actual database! ie saved objects do not disappear after quitting the current shell. object gets an id after this, which can then be used for lookups Methods for accessing data 'Class.objects.all()' - returns all saved class objects 'Class.objects.filter(id=#)' - returns desired object 'Class.objects.get(pk=#)' - finds by primary key (same as fitler(id=#)?) "Class.objects.filter(attribute__startswith='string')" - searches by attribute 'Class.objects.get(datetimeAttribute__year=#)' - searches by datetime data if not found, returns DoesNotExist exception Methods for setting data 'classObject.attribute_set.all()' - creates a set of attributes linked to object, ie choices for a poll attributes have access to their related object, ie choices have access to the poll they are related to Admin site Activation uncomment 'django.contrib.admin' in INSTALLED_APPS syncdb uncomment admin lines in 'mysite/urls.py' create 'admin.py' in app directory; file imports Model, django.contrib.admin, and registers Model modifying a file does not require restarting server (unlike interactive shell); creating a file does

admin site can make easy editing of competencies, but need a soft update rather than the presumed hard update, to show competency hx to customize admin site, create a "model admin object", ie ModelnameAdmin, and pass it as the second argument to "admin.site.register()" in admin.py - usability issue Admin pages can be customized many ways - change order of fields displayed, connect related objects, allow easy filtering, sorting, and searching. Look and feel can be changed by copying templates from default directory to my directory, and overriding defaults much like css. templates should be stored off document root right now, templates in 'srv/pythonenvironments/learning_django/lib/python2.6/sitepackages/django/contrib/admin/templates/admin' Views super easy to mess up a url regex, and get a 404 error because no regexes match, or a syntax error from url page. Make this an alert/ email trigger, not just a logged event, in production code? Research proper placement of my_templates directory Edit 'mysite/urls.py' to support desired url configuration - using includes, we actually create a series of urls.py files, one for each app, in their own directories and include them within 'mysite/urls.py' url regex form: "(r'regex', 'directory.directory.file.function_name') When a regex is matched for a url, it calls the given function name in the given file, in the given directory function is called with an http request object as first arg, then whatever is captured from the regex regexes do not search domain name or GET/ POST parameters overall process define url patterns; define views; define templates; set up 404 template, and 500 template use get_object_or_404(), then render_to_response() will only see 404 or 500 pages if debug=False in settings.py factor out common prefixes, make an app-specific urls.py and include it in site's urls.py question - in tutorial, I get empty bullets in choice list between each choice. Not sure why. Forms forms are written in templates; research templating before moving forward identify and print further resources i.e. templates, auth, etc. css to pdf? organize existing django documentation high load values - quitting mysql monitor seems to bring loads down use POST method when altering data server-side; GET for client-side (general web best practice, not just django) why - cleaner? security - POST form vulnerability is cross site request forgery (cross-site scripting?

django guards against it using csrf_token cross-site scripting - attacker takes post data, modifies it, resubmits it? for csrf token to work, need RequestContext in view that calls form template basic form processing: try to get selected choice (form data) catch data does not exist exception/ error else do what intended with data, including processing data and saving it, and then use HttpResponseRedirect with reverse to prevent double-submitting if user hits Back in tutorial, vote view is really a handler for the form - no template for vote, either calls detail template again if no data, or results template if successful processing any possibility of failed save? what happens on db error??? HttpResponseRedirect should take a 'reverse' call that redirects to a view, rather than a hard-coded url. Generic views If generic views good fit for purpose, use them from the start change urls.py to use ListView or DetailView abstract the concepts "display a list of objects" and "display a detail page for a particular type of object" each generic view needs to know what model it will work with DetailView expects a primary key value captured from url, called "pk", so (? P<pk>\d+) should be in regex generic views can have a "name" attribute so they can be called later on research "naming URL patterns". Use url() function in urlconf when using named patterns. Why? generic views have default generic templates. Look at them for familiarity, but should probably customize. "template_name" tells generic view which template to use instead of default. generic views make their best guess at context variable name, probably something like model_name_list. Specify with "context_object_name", which matches a context variable used in the template. in HttpRequestRedirect after processing a form, need to use the name given for the generic view, because there is no view in views.py. HRR needs to be handled in urls, and this is done by referring to the generic view by name. Final notes on initial run-through Restarting site from fresh system restart Need to activate virtual environment, then restart server From mysite (ie "/srv/python-environments/project_name"), "source bin/activate"; or from python-environments "source env_name/bin/activate" cd env_name python manage.py runserver Running without a terminal window probably by writing a short bash script, and make panel icon to run without a terminal window being shown. Django design philosophies DRY - don't repeat yourself redundancy bad, normalization good

Model behavior based on keyword arguments and type of field, not names of fields why is save() called explicitly? Does it allow fewer sql connections, more operations into one query? research "select_related()" - select all objects related to a given object? urls loose coupling of urls to models and apps means that different people/ sites can use different urls for accessing the same app, ie app "stories" under /stories/ on one site, and /news/ on another site. accomplished, in part, by not dealing with domain name in url examination? url structure does not require inclusion of file extensions within urls better to have pretty urls than ugly ones. templates templates use inheritance, to accomodate headers, footers, nav bars, etc. templates output html, text, other formats - pdf? .doc? .odt? whitespace treated simply - if it's outside of tags, it's displayed. template system is not a programming language - simplicity, broader user base, security custom template tags and filters can be created views simplicity - no class instantiation needed, just write a function can pass "fake" request objects to views, for testing Models documentation research - official repository of model examples (test/modeltests in django) project corresponds to database, models correspond to tables. research - model field reference custom model fields can be created question - what happens if data in a varchar field (CharField) is too long - rejected? truncated? what happens if design revised, field declaration changed, and existing data violates declaration? What does syncdb return? null/ blank null=False is default blank=False is default null is purely database-related; blank is about validation by django "choices" can be specified for a field's values seems wise to be careful, because requires reprogramming the model to allow for a choice that was not foreseen - i.e. a subject such as music, or technology seems better to code that carefully within logic primary key is by default an auto-generated id column, but any unique column can be made primary key by keyword "primary_key=True" cdb - should be straightforward, but look at db design from previous iteration "unique=True" is an option cdb - good for fields such as subjects vebose_name keyword for relations, other fields just first positional argument no need to capitalize - django takes care of that relationships

research - model field reference many-to-one: use ForeignKey many-to-many: use ManyToManyField field goes in the object that's going to be edited in admin, ie Toppings in Pizza not Pizzas in Topping can create a model that describes the many-to-many relationship, ie Membership that describes relationship between Musician and Group stores details about relationship, such as date_joined and invite_reason if implemented, relationships must be defined using the relationship object one-to-one: use OneToOneField useful on primary key of an object when that object "extends" another object, ie Restaurant extends a Place seems to border on being an Abstract Class models from one app can elate to models from another app; simply import the other model. field name cannot be a reserved python word field names cannot have more than one underscore in a row Meta options used to store things like ordering, db_table name if nonstandard model methods store "row-level" behavior, as opposed to "table-level" behavior should always define some, such as __unicode__() any object that has a URL uniquely identifying it should have get_absolute_url() defined - ??? Overriding predefined methods over ride save() to do something custom, then save cdb - is this the way to archive historical data? for overriding standard deleting behavior, may want pre_delete or post_delete signals instead model inheritance Abstract base class factor out common information Meta "abstract=True" in the base class no database table created - fields are added to each derived class children inherit parent's meta class some confusion around related_name attribute??? "reverse name"??? Multi-table inheritance each model in the hierarchy is a model all by itself - every model in the chain gets its own database table. each model can be queried and created individually why do this? why not just use a foreign key? ie why is Restaurant a subclass of Place, rather than just having Place as an fk in Restaurant? children do not inherit parents' Meta, except for "ordering" and "get_latest_by" attributes Proxy models

used if only want to customize behavior - no new fields in child classes Meta "proxy=True" cdb - may be useful in extending user functionality what happens if need to add an attribute later? used for changing "python-only behavior of a model" general - keep inheritance hierarchies as simple and straightforward as possible research model manager Further reading from official documentation: Model field reference Sending e-mail (print) Logging (print) Pagination (print) Signals validators (print) admin (print) django forum/ community

Potrebbero piacerti anche