45
Django - Sql Alchemy - JQuery Rafie Tarabay [email protected]

Django - sql alchemy - jquery

Embed Size (px)

DESCRIPTION

suggested development framework using python

Citation preview

Page 1: Django - sql alchemy - jquery

Django - Sql Alchemy - JQuery

Rafie Tarabay

[email protected]

Page 2: Django - sql alchemy - jquery

Django

Apache IIS Google App Server Tornado Django

Sql A

lche

my

JQuery

IEFirefoxChromeSafary

Oracle

MySql

MSSql

Others

My Application

Page 3: Django - sql alchemy - jquery

SQL AlchemyTo write SQL query compatible with

all databases using ORM

Page 4: Django - sql alchemy - jquery

Creating Table, Class and Mapperfrom sqlalchemy.ext.declarative import declarative_baseBase = 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)

Page 5: Django - sql alchemy - jquery

Creating a Session to DBfrom 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:[email protected]:1521/sidname’)• create_engine(’mssql://mydsn’)• create_engine(’sqlite:////absolute/path/to/foo.db’)

Page 6: Django - sql alchemy - jquery

Adding new ObjectsAdd Rowed_user = User(’ed’, ’Ed Jones’, ’edspassword’)session.add(ed_user)

Edit Rowed_user.password = ’f8s7ccs’

Add Batchsession.add_all([

User(’wendy’, ’Wendy Williams’, ’foobar’),User(’mary’, ’Mary Contrary’, ’xxg527’),User(’fred’, ’Fred Flinstone’, ’blah’)])

Apply Changessession.commit()session.rollback()

Page 7: Django - sql alchemy - jquery

Queryour_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

NoteYou 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’)

Page 8: Django - sql alchemy - jquery

Common Filter Operatorsequals: 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 timesfilter(User.name == ’ed’).filter(User.fullname == ’EdOR:from sqlalchemy import or_filter(or_(User.name == ’ed’, User.name == ’wendy’))

Page 9: Django - sql alchemy - jquery

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()

Page 10: Django - sql alchemy - jquery

Count

session.query(User).filter(User.name.like('%ed')).count()

Page 11: Django - sql alchemy - jquery

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")

Page 12: Django - sql alchemy - jquery

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.

Page 13: Django - sql alchemy - jquery

Working with Related Objects

• jack = User(’jack’, ’Jack Bean’, ’gjffdd’)• jack.addresses =

[Address(email_address='[email protected]'), Address(email_address='[email protected]')]

Page 14: Django - sql alchemy - jquery

Another Method

SQL EXPRESSION

Page 15: Django - sql alchemy - jquery

Connectionfrom sqlalchemy import create_engineengine = create_engine(’sqlite:///:memory:’, echo=True)

Create Tablefrom sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKeymetadata = MetaData()users = Table(’users’, metadata,

Column(’id’, Integer, primary_key=True),Column(’name’, String),Column(’fullname’, String),)

addresses = Table(’addresses’, metadata,Column(’id’, Integer, primary_key=True),Column(’user_id’, None, ForeignKey(’users.id’)),Column(’email_address’, String, nullable=False))

metadata.create_all(engine)

Insert DataWe Have 4 methods

Page 16: Django - sql alchemy - jquery

Method 1conn = engine.connect()ins = users.insert().values(name=’jack’, fullname=’Jack Jones’)result = conn.execute(ins)result.inserted_primary_keyMethod 2conn = engine.connect()conn.execute(addresses.insert(), [ {’user_id’: 1, ’email_address’ : ’[email protected]’}, {’user_id’: 1, ’email_address’ : ’[email protected]’}, {’user_id’: 2, ’email_address’ : ’[email protected]’}, {’user_id’: 2, ’email_address’ : ’[email protected]’}, ])Method 3result = engine.execute(users.insert(), name=’fred’, fullname=“Flintstone")Method 4metadata.bind = engineresult = users.insert().execute(name="mary", fullname="Mary Contrary")

Page 17: Django - sql alchemy - jquery

Delete

conn.execute(users.delete().where(users.c.name > ’m’))

Page 18: Django - sql alchemy - jquery

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)

Page 19: Django - sql alchemy - jquery

QueryEx1sql = select([users, addresses], users.c.id==addresses.c.user_id)for row in conn.execute(sql): print row

Ex2s = select([(users.c.fullname + ", " + addresses.c.email_address).label(’title’)], and_( users.c.id==addresses.c.user_id, users.c.name.between(’m’, ’z’), or_( addresses.c.email_address.like(’%@aol.com’), addresses.c.email_address.like(’%@msn.com’) ) ) )print conn.execute(s).fetchall()

Page 20: Django - sql alchemy - jquery

Normal Queryfrom 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 approachs = 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()

Page 21: Django - sql alchemy - jquery

Transaction# method_a starts a transaction and calls method_bdef method_a(connection):

trans = connection.begin() # open a transactiontry:method_b(connection)trans.commit() # transaction is committed hereexcept:trans.rollback() # this rolls back the transaction unconditionallyRaise

# 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 yetexcept:trans.rollback() # this rolls back the transaction unconditionallyRaise

# open a Connection and call method_aconn = engine.connect()method_a(conn)

Page 22: Django - sql alchemy - jquery

JQuery

To write JavaScript Compatible with all web browsers

Page 23: Django - sql alchemy - jquery

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>

Page 24: Django - sql alchemy - jquery

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 expectedjQuery('#content span a'); // all anchor within all span elements within #contentjQuery(‘.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

Page 25: Django - sql alchemy - jquery

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

Page 26: Django - sql alchemy - jquery

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)');

Page 27: Django - sql alchemy - jquery

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 }

Page 28: Django - sql alchemy - jquery

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.

Page 29: Django - sql alchemy - jquery

Navigate in DOMjQuery('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>sjQuery('li:eq(1)').parent().children(':last') //selects the last <li>

Page 30: Django - sql alchemy - jquery

Apply Effect on Selected ElementsjQuery('div'). css('border','1px solid #993300');

//add a class attribute with a value of updatedContent to all divsjQuery('div')[0].addClass("updatedContent");

//hide all divs on the pagejQuery('div').hide();

//update the text contained inside of all divsjQuery('div').text('new content');

//show all divs on the pagejQuery('div').show();

jQuery('a').lengthjQuery('input',$('form')).lengthjQuery('input','body').lengthjQuery('input',document.forms[0]).length

jQuery('#username').focus(); //<input name="username" id="username" type="text" />jQuery('#username'). val();

Page 31: Django - sql alchemy - jquery

<style>table tr.even {background: #CCC;}<style>

<table><tr><td>0</td><td>even</td></tr><tr><td>1</td><td>odd</td></tr><tr><td>2</td><td>even</td></tr><tr><td>3</td><td>odd</td></tr><tr><td>4</td><td>even</td></tr></table>

jQuery('tr:even').addClass('even');

Page 32: Django - sql alchemy - jquery

Inject DOM/Remove/Replacing/Copy

Inject ElementsappendTo() Example jQuery('<p><a>jQuery</a></p>'). appendTo('body');insertAfter()insertBefore()

Remove ElementjQuery('a').remove(); //Delete all tags A in the pagejQuery('a').remove('.ClassZ'); // Remove Class=ClassZ from any A tags

Replace ElementsjQuery('li.ClassZ').replaceWith('<li>removed</li>');

Copy ElementsjQuery('ul').clone().appendTo('body'); //copy ul tags add again to body

Page 33: Django - sql alchemy - jquery

Add/Delete AttributesAdd AttributejQuery(document.body).attr('bgcolor') // get bgcolorjQuery('a').attr('href','http://www.jquery.com') //set new href to all a tagsjQuery('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 AttributejQuery('a').removeAttr('title')

Page 34: Django - sql alchemy - jquery

Adding/Get InnerHTML

jQuery('p').html('<strong>Hello </strong');jQuery('p').html()

Page 35: Django - sql alchemy - jquery

Looping Through a Set of Selected Results

$("ul > li:odd").addClass("odd");$("ul > li:even").addClass(“even");

Page 36: Django - sql alchemy - jquery

<ul id="a"><li>list</li><li>list</li><li>list</li><li>list</li></ul><ul id="b"></ul>

Attach Events

jQuery('ul#a li').click(function(){alert('List Item Clicked')});

jQuery("div").click(function() {alert(“Div index "+ jQuery("div").index(this));})

Page 37: Django - sql alchemy - jquery

jQuery('div').click(function(e){ alert('event'); }) .keydown(function(e){ alert('event'); });

Page 38: Django - sql alchemy - jquery

Events Binding function buttonClicked(e){

jQuery('div.panel').hide();jQuery('#panel'+e.data.panel).show();jQuery('#desc').text('You clicked the '+e.data.color+' button');

}jQuery('#button1').bind('click',{panel:1, color:'red'}, buttonClicked);jQuery('#button2').bind('click',{panel:2, color:'blue'}, buttonClicked);jQuery('#button3').bind('click',{panel:3, color:'green'}, buttonClicked);

Page 39: Django - sql alchemy - jquery

Form Validationinitializing 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.

Page 40: Django - sql alchemy - jquery

<script src="jquery-latest.js"></script> <script src="jquery.validate.js"></script>

<script type="text/javascript"> $(document).ready(function() { $("#form1").validate({ rules: {

date1: true ,email1: {required: true,email: true },url1: {url: true},comment1: {required: true}

}, messages: { email1: { required: "We need your email ", email: "format Err" }

comment1: "Please enter a comment." }

}); }); </script>

<form id="form1" method="post" action=""><input type="text" name="date1" /><input type="text" name="email1" /><input type="text" name="url1" /><textarea name="comment1" ></textarea><input class="submit" type="submit" value="Submit">

</form>

Page 41: Django - sql alchemy - jquery

Django

Page 42: Django - sql alchemy - jquery

Create Project and Applicationbash-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

bash-3.00$ python manage.py runserverbash-3.00$ python manage.py syncdb

You can now visit the default server home page at http://127.0.0.1:8000

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.

Page 43: Django - sql alchemy - jquery

Create Your First Applicationbash-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 listINSTALLED_APPS = ('django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.sites',' ProjectName.eulcProj1')

Page 44: Django - sql alchemy - jquery

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

Page 45: Django - sql alchemy - jquery

Test DB Using commad line

python manage.py shellfrom ProjectName.eulcProj1.models import Personp = Person(name="your name", email="your eMail")

p.save()