4. Creating Table, Class and Mapper
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = ’users’
id = Column(Integer, primary_key=True)
name = Column(’f2’, String(50))
fullname = Column(’f3’, String(50))
password = Column(’f4’, String(50))
def __init__(self, name, fullname, password):
self.name = name
self.fullname = fullname
self.password = password
def __repr__(self):
return "<User(’%s’,’%s’, ’%s’)>" % (self.name, self.fullname, self.password)
5. Creating a Session to DB
from sqlalchemy.orm import sessionmaker
engine = create_engine(’sqlite:///:memory:’, echo=True)
Session = sessionmaker(bind=engine)
For Other DB Connections:
• create_engine(’mysql://scott:tiger@localhost/foo’)
• create_engine(’oracle://scott:tiger@127.0.0.1:1521/sidname’)
• create_engine(’mssql://mydsn’)
• create_engine(’sqlite:////absolute/path/to/foo.db’)
7. Query
our_user = session.query(User).filter_by(name=’ed’).first()
for name, in session.query(User.name).filter(User.fullname==’Ed Jones’):
print name
for user in session.query(User).filter(User.id>5).filter(User.fullname==’Ed’):
print user
for instance in session.query(User).order_by(User.id):
print instance.name, instance.fullname
Note
You can control the names using the label() construct for scalar attributes and
aliased() for class constructs:
user_alias = aliased(User, name=’user_alias’)
user_alias.name.label(’name_label’)
8. Common Filter Operators
equals: query.filter(User.name == ’ed’)
not equals: query.filter(User.name != ’ed’)
LIKE: query.filter(User.name.like(’%ed%’))
IN: query.filter(User.name.in_(*’ed’, ’wendy’+))
Nested SQL:
query.filter(User.name.in_(session.query(User.name).filter(User.name.like(’%ed%’))))
NOT IN: query.filter(~User.name.in_(*’ed’, ’wendy’, ’jack’+))
IS NULL: filter(User.name == None)
IS NOT NULL: filter(User.name != None)
AND:
from sqlalchemy import and_
filter(and_(User.name == ’ed’, User.fullname == ’Ed Jones’))
# or call filter()/filter_by() multiple times
filter(User.name == ’ed’).filter(User.fullname == ’Ed
OR:
from sqlalchemy import or_
filter(or_(User.name == ’ed’, User.name == ’wendy’))
9. Parameter
session.query(User).filter("id<:value and name=:name").
params(value=224, name=’fred’).order_by(User.id).one()
session.query(User).from_statement("SELECT * FROM users where
name=:name").params(name=’asfasdf’)
session.query("id", "name", "thenumber12")
.from_statement("SELECT id, name, 12 as thenumber12 FROM users
where name=:name").params(name='ed').all()
11. Building a Relationship
>>> from sqlalchemy import ForeignKey
>>> from sqlalchemy.orm import relationship, backref
>>> class Address(Base):
... __tablename__ = 'addresses'
... id = Column(Integer, primary_key=True)
... email_address = Column(String, nullable=False)
... user_id = Column(Integer, ForeignKey('users.id'))
...
... user = relationship(User, backref=backref('addresses', order_by=id))
...
... def __init__(self, email_address):
... self.email_address = email_address
...
... def __repr__(self):
... return "<Address('%s')>" % self.email_address
==================================================================================
class User(Base):
# ....
addresses = relationship(Address, order_by=Address.id, backref="user")
12. Notes
• The above class introduces a foreign key constraint
which references the users table. This defines for
SQLAlchemy the relationship between the two tables
at the database level.
• The relationship between the User and Address classes
is defined separately using the relationship() function,
which defines an attribute user to be placed on the
Address class, as well as an addresses collection to be
placed on the User class. Such a relationship is known
as a bidirectional relationship.
• We free to not define a backref, and to define the
relationship() only on one class and not the other.
13. Working with Related Objects
• jack = User(’jack’, ’Jack Bean’, ’gjffdd’)
• jack.addresses =
[Address(email_address='jack@google.com'), Addr
ess(email_address='j25@yahoo.com')]
18. Connection /Connectionless
We’re executing our Insert using a Connection
(Method1,2).
Or allow you to not have to deal with the
connection part. You can execute in the
connectionless style, using the engine, which
opens and closes a connection for you
(Method 3,4)
20. Normal Query
from sqlalchemy.sql import text
s = text(""“
SELECT users.fullname || ’, ’ || addresses.email_address AS title
FROM users, addresses
WHERE users.id = addresses.user_id AND users.name BETWEEN :x AND :y AND
(addresses.email_address LIKE :e1 OR addresses.email_address LIKE :e2)
""")
print conn.execute(s, x=’m’, y=’z’, e1=’%@aol.com’, e2=’%@msn.com’).fetchall()
hybrid approach
s = select(["users.fullname || ’, ’ || addresses.email_address AS title"],
and_(
"users.id = addresses.user_id",
"users.name BETWEEN ’m’ AND ’z’",
"(addresses.email_address LIKE :x OR addresses.email_address LIKE :y)"
),
from_obj=*’users’, ’addresses’+
)
print conn.execute(s, x=’%@aol.com’, y=’%@msn.com’).fetchall()
21. Transaction
# method_a starts a transaction and calls method_b
def method_a(connection):
trans = connection.begin() # open a transaction
try:
method_b(connection)
trans.commit() # transaction is committed here
except:
trans.rollback() # this rolls back the transaction unconditionally
Raise
# method_b also starts a transaction
def method_b(connection):
trans = connection.begin() # open a transaction - this runs in the context of method_a’s try:
connection.execute("insert into mytable values (’bat’, ’lala’)")
connection.execute(mytable.insert(), col1=’bat’, col2=’lala’)
trans.commit() # transaction is not committed yet
except:
trans.rollback() # this rolls back the transaction unconditionally
Raise
# open a Connection and call method_a
conn = engine.connect()
method_a(conn)
23. Compare onLoad & Ready
window.onload : work only if all page +Images+Swf loaded
Solution
<script type="text/JavaScript">
jQuery(document).ready(function()
{
alert(‘All TextPage Loaded’);
}
);
</script>
24. Select Element
<script type="text/JavaScript” src=“jquery.min.js"></script>
<a href="/category">Category</a>
<ul id="nav“ class=“ClassZ”>
<li><a href="#anchor1">Anchor 1</a></li>
<li><a href="#anchor2">Anchor 2</a></li>
<li><span><a href="#anchor3">Anchor 3</a></span></li>
</ul>
jQuery('#nav’)
jQuery('#nav li > a'); // This selects two elements, as expected
jQuery('#content span a'); // all anchor within all span elements within #content
jQuery(‘.ClassZ'); // Select elelments with calss= classZ
jQuery('li:eq(1)'); //selects the second element in the set of <li>'s by index, index starts at 0
25. Attributes Help In Selections
:first Matches the first selected element
:last Matches the last selected element
:even Matches even elements (zero-indexed)
:odd Matches odd elements (zero-indexed)
:eq(n) Matches a single element by its index (n)
:lt(n) Matches all elements with index below n
:gt(n) Matches all elements with index above n
26. Selecting Elements Based on What
They Contain
<span>Hello Bob!</span>
// Select all SPANs with 'Bob' in:
jQuery('span:contains("Bob")'); //it’s case sensitive
jQuery('div:not(#content)'); // Select all DIV elements except #content
To test for nested elements, you can use the :has() filter.
jQuery('div:has(p a)');
27. Selecting Elements Based on Their
Visibility
jQuery('div:hidden');
jQuery('p:visible').hide(); // Hiding only elements that are currently visible
if (jQuery('#elem').is(':hidden')) {
// Do something conditionally
}
28. Selecting Form Elements by Type
:text <input type="text" />
:password <input type="password" />
:radio <input type="radio" />
:checkbox <input type="checkbox" />
:submit <input type="submit" />
:image <input type="image" />
:reset <input type="reset" />
:button <input type="button" />
:file <input type="file" />
:hidden <input type="hidden" />
jQuery(':text'); //select all text inputs,
jQuery(':input:not(:hidden)'); // Selects all input elements not hidden.
29. Navigate in DOM
jQuery('li:eq(1)').next() //selects the third <li>
jQuery('li:eq(1)').prev() //selects the first <li>
jQuery('li:eq(1)').parent() //selects the <ul>
jQuery('li:eq(1)').nextAll() //selects all the <li>s after the second <li>
jQuery('li:eq(1)').prevAll() //selects all the <li>s before the second <li>
jQuery('li:eq(1)').parent().children() //selects all <li>s
jQuery('li:eq(1)').parent().children(':last') //selects the last <li>
30. Apply Effect on Selected Elements
jQuery('div'). css('border','1px solid #993300');
//add a class attribute with a value of updatedContent to all divs
jQuery('div')[0].addClass("updatedContent");
//hide all divs on the page
jQuery('div').hide();
//update the text contained inside of all divs
jQuery('div').text('new content');
//show all divs on the page
jQuery('div').show();
jQuery('a').length
jQuery('input',$('form')).length
jQuery('input','body').length
jQuery('input',document.forms[0]).length
jQuery('#username').focus(); //<input name="username" id="username" type="text" />
jQuery('#username'). val();
32. Inject DOM/Remove/Replacing/Copy
Inject Elements
appendTo() Example jQuery('<p><a>jQuery</a></p>'). appendTo('body');
insertAfter()
insertBefore()
Remove Element
jQuery('a').remove(); //Delete all tags A in the page
jQuery('a').remove('.ClassZ'); // Remove Class=ClassZ from any A tags
Replace Elements
jQuery('li.ClassZ').replaceWith('<li>removed</li>');
Copy Elements
jQuery('ul').clone().appendTo('body'); //copy ul tags add again to body
33. Add/Delete Attributes
Add Attribute
jQuery(document.body).attr('bgcolor') // get bgcolor
jQuery('a').attr('href','http://www.jquery.com') //set new href to all a tags
jQuery('a').attr({'href':'http://www.jquery.com','title':'jquery.com'}).attr(‘class')
Since the class attribute can contain several values (e.g., class="class1 class2 class3"),
addClass()
hasClass()
removeClass()
toggleClass() //Adds the specified class if it is not present; removes the specified class if it is present
Remove Attribute
jQuery('a').removeAttr('title')
39. Form Validation
initializing the validation of the form using the validate() function.
The two parameters we used are:
rules: allows you to specify which fields you want to validate. In this case, we are validating name, email, url
and comment. For each field, we specify if the field is required (required: true). We can specify that it must
be a valid e-mail address, URL, etc.
messages: allows you to specify the error message for a particular field (like the comments field in the example
above). If you don't specify it, a default message is provided that says "this field is required".
Validation methods
• remote: requests a resource to check the element for validity.
• min: makes the element require a given minimum.
• date: makes the element require a date.
• creditcard: makes the element require a credit card number.
• equalTo: requires the element to be the same as another one.
42. Create Project and Application
bash-3.00$ python django-admin.py startproject ProjectName
command creates the following files:
– __init__.py is an empty file that tells Python that the website directory should be treated as a
Python package.
– manage.py is the command-line utility that allows the administrator to start and manage the
Django project.
– settings.py configuration file of the Django project (Need DB to manage internal Process).
– urls.py is a Python file that defines the syntax and configures the behavior of the URLs that
will be used to access the website.
Then Edit settings.py File for DB conn
DATABASE_ENGINE = 'mysql' # 'sqlite3' or 'oracle'.
DATABASE_NAME = 'test' # Or path to database file if using sqlite3.
DATABASE_USER = 'root' # Not used with sqlite3.
DATABASE_PASSWORD = 'muhammad'
DATABASE_HOST = ‘192.168.200.95' # Set to empty string for localhost.
DATABASE_PORT = '' # Set to empty string for default.
bash-3.00$ python manage.py runserver
bash-3.00$ python manage.py syncdb
You can now visit the default server home page at http://127.0.0.1:8000
43. Create Your First Application
bash-3.00$ python manage.py startapp eulcProj1
command creates the following files:
– __init__.py website directory should be treated as a Python package.
– models.py code for model classes
– views.py code for views
Reedit Setting.py add new project name to the list
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
' ProjectName.eulcProj1'
)
44. Django Has built in ORM
OPEN models.py file
from django.db import models
class Person(models.Model):
name = models.CharField('name', max_length=200)
text = models.TextField('Desc', max_length=500, blank=True)
def __str__(self): return '%s' % (self.name)
Then call python manage.py syncdb to create the table in DB
45. Test DB Using commad line
python manage.py shell
from ProjectName.eulcProj1.models import Person
p = Person(name="your name", email="your eMail")
p.save()