Django - sql alchemy - jquery


Published on

suggested development framework using python

Published in: Technology

Django - sql alchemy - jquery

  1. 1. Django - Sql Alchemy - JQuery Rafie Tarabay
  2. 2. Others Safary Chrome Firefox IE JQuery Oracle Sql Alchemy My Application MySql Django MSSql Google AppApache IIS Tornado Django Server
  3. 3. SQL AlchemyTo write SQL query compatible with all databases using ORM
  4. 4. 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): = name self.fullname = fullname self.password = password def __repr__(self): return "<User(’%s’,’%s’, ’%s’)>" % (, self.fullname, self.password)
  5. 5. Creating a Session to DBfrom sqlalchemy.orm import sessionmakerengine = 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@’)• create_engine(’mssql://mydsn’)• create_engine(’sqlite:////absolute/path/to/foo.db’)
  6. 6. 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()
  7. 7. Queryour_user = session.query(User).filter_by(name=’ed’).first()for name, in session.query(’Ed Jones’): print namefor user in session.query(User).filter(>5).filter(User.fullname==’Ed’): print userfor instance in session.query(User).order_by( print, instance.fullnameNoteYou can control the names using the label() construct for scalar attributes and aliased() for class constructs:user_alias = aliased(User, name=’user_alias’)’name_label’)
  8. 8. Common Filter Operatorsequals: query.filter( == ’ed’)not equals: query.filter( != ’ed’)LIKE: query.filter(’%ed%’))IN: query.filter(*’ed’, ’wendy’+))Nested SQL:query.filter(’%ed%’))))NOT IN: query.filter(*’ed’, ’wendy’, ’jack’+))IS NULL: filter( == None)IS NOT NULL: filter( != None)AND:from sqlalchemy import and_filter(and_( == ’ed’, User.fullname == ’Ed Jones’))# or call filter()/filter_by() multiple timesfilter( == ’ed’).filter(User.fullname == ’EdOR:from sqlalchemy import or_filter(or_( == ’ed’, == ’wendy’))
  9. 9. Parametersession.query(User).filter("id<:value and name=:name"). params(value=224, name=’fred’).order_by("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()
  10. 10. Countsession.query(User).filter(
  11. 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( 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,, backref="user")
  12. 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. 13. Working with Related Objects• jack = User(’jack’, ’Jack Bean’, ’gjffdd’)• jack.addresses = [Address(, Addr ess(]
  14. 14. Another Method SQL EXPRESSION
  15. 15. 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(’’)), Column(’email_address’, String, nullable=False) )metadata.create_all(engine)Insert DataWe Have 4 methods
  16. 16. 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’ : ’’-, ,’user_id’: 1, ’email_address’ : ’’-, ,’user_id’: 2, ’email_address’ : ’’-, ,’user_id’: 2, ’email_address’ : ’’-, ])Method 3result = engine.execute(users.insert(), name=’fred’, fullname=“Flintstone")Method 4metadata.bind = engineresult = users.insert().execute(name="mary", fullname="Mary Contrary")
  17. 17. Deleteconn.execute(users.delete().where( > ’m’))
  18. 18. Connection /ConnectionlessWe’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)
  19. 19. QueryEx1sql = select([users, addresses], row in conn.execute(sql): print rowEx2s = select([(users.c.fullname + ", " + addresses.c.email_address).label(’title’)+, and_(,’m’, ’z’), or_(’’),’’) ) ) )print conn.execute(s).fetchall()
  20. 20. Normal Queryfrom sqlalchemy.sql import text s = text(""“ SELECT users.fullname || ’, ’ || addresses.email_address AS title FROM users, addresses WHERE = addresses.user_id AND 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=’’, e2=’’).fetchall()hybrid approachs = select(["users.fullname || ’, ’ || addresses.email_address AS title"], and_( " = addresses.user_id", " BETWEEN ’m’ AND ’z’", "(addresses.email_address LIKE :x OR addresses.email_address LIKE :y)" ), from_obj=*’users’, ’addresses’+ )print conn.execute(s, x=’’, y=’’).fetchall()
  21. 21. Transaction# method_a starts a transaction and calls method_bdef 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 transactiondef 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_aconn = engine.connect()method_a(conn)
  22. 22. JQueryTo write JavaScript Compatible with all web browsers
  23. 23. Compare onLoad & Readywindow.onload : work only if all page +Images+Swf loadedSolution<script type="text/JavaScript">jQuery(document).ready(function() { alert(‘All TextPage Loaded’); });</script>
  24. 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 expectedjQuery(#content span a); // all anchor within all span elements within #contentjQuery(‘.ClassZ); // Select elelments with calss= classZjQuery(li:eq(1)); //selects the second element in the set of <li>s by index, index starts at 0
  25. 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. 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 sensitivejQuery(div:not(#content)); // Select all DIV elements except #contentTo test for nested elements, you can use the :has() filter.jQuery(div:has(p a));
  27. 27. Selecting Elements Based on Their VisibilityjQuery(div:hidden);jQuery(p:visible).hide(); // Hiding only elements that are currently visibleif (jQuery(#elem).is(:hidden)) { // Do something conditionally }
  28. 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. 29. 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>
  30. 30. 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]).lengthjQuery(#username).focus(); //<input name="username" id="username" type="text" />jQuery(#username). val();
  31. 31. <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);
  32. 32. Inject DOM/Remove/Replacing/CopyInject 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 tagsReplace ElementsjQuery(li.ClassZ).replaceWith(<li>removed</li>);Copy ElementsjQuery(ul).clone().appendTo(body); //copy ul tags add again to body
  33. 33. Add/Delete AttributesAdd AttributejQuery(document.body).attr(bgcolor) // get bgcolorjQuery(a).attr(href, //set new href to all a tagsjQuery(a).attr({href:,}).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 presentRemove AttributejQuery(a).removeAttr(title)
  34. 34. Adding/Get InnerHTMLjQuery(p).html(<strong>Hello </strong);jQuery(p).html()
  35. 35. Looping Through a Set of Selected Results $("ul > li:odd").addClass("odd"); $("ul > li:even").addClass(“even");
  36. 36. Attach Events <ul id="a"> <li>list</li> <li>list</li> <li>list</li> <li>list</li> </ul> <ul id="b"></ul>jQuery(ul#a li).click(function(){alert(List Item Clicked)});jQuery("div").click(function() ,alert(“Div index "+ jQuery("div").index(this));})
  37. 37. jQuery(div).click(function(e){ alert(event); }) .keydown(function(e){ alert(event); });
  38. 38. Events Bindingfunction buttonClicked(e){ jQuery(div.panel).hide(); jQuery(; jQuery(#desc).text(You clicked the 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);
  39. 39. 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 dont 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.
  40. 40. <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>
  41. 41. Django
  42. 42. Create Project and Applicationbash-3.00$ python startproject ProjectName command creates the following files: – is an empty file that tells Python that the website directory should be treated as a Python package. – is the command-line utility that allows the administrator to start and manage the Django project. – configuration file of the Django project (Need DB to manage internal Process). – 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 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 = ‘ # Set to empty string for localhost. DATABASE_PORT = # Set to empty string for default.bash-3.00$ python runserverbash-3.00$ python syncdbYou can now visit the default server home page at
  43. 43. Create Your First Applicationbash-3.00$ python startapp eulcProj1 command creates the following files: – website directory should be treated as a Python package. – code for model classes – code for viewsReedit add new project name to the listINSTALLED_APPS = (django.contrib.auth,django.contrib.contenttypes,django.contrib.sessions,django.contrib.sites, ProjectName.eulcProj1)
  44. 44. Django Has built in ORMOPEN filefrom django.db import modelsclass Person(models.Model): name = models.CharField(name, max_length=200) text = models.TextField(Desc, max_length=500, blank=True) def __str__(self): return %s % ( call python syncdb to create the table in DB
  45. 45. Test DB Using commad linepython shellfrom ProjectName.eulcProj1.models import Personp = Person(name="your name", email="your eMail")
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.