CS2021- Week 10 – Models and Views Web Development Model, Views, Controller Templates Databases.

Slides:



Advertisements
Similar presentations
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
Advertisements

The Librarian Web Page Carol Wolf CS396X. Create new controller  To create a new controller that can manage more than just books, type ruby script/generate.
Tutorial 6 Creating a Web Form
Web Basics Willem Visser RW334. Overview Basic Browser and Server Interaction – Forms with actions, url encoding and handlers – Parameters – Having more.
Chapter 6 Basic forms 1. Forms and query string 2 form : a group of user input (UI) controls that accepts information from the user and sends the information.
Intermediate Level Course. Text Format The text styles, bold, italics, underlining, superscript and subscript, can be easily added to selected text. Text.
Drupal Create a website/web app quickly with this Content Management System Jiaying Xu Spring 2011 COMS E6125 Web-enHanced Information.
When are projects due? #infomgmtFAIL – This is why you never duplicate data. – Project 4 is Due To get it done in time you will need to work smart, cut.
Chapter 4 Relational Databases Copyright © 2012 Pearson Education, Inc. publishing as Prentice Hall 4-1.
Computer Science 101 Web Access to Databases Overview of Web Access to Databases.
Creating Web Page Forms
Chapter 4 Relational Databases Copyright © 2012 Pearson Education 4-1.
Platform as a Service (PaaS)
Google AppEngine. Google App Engine enables you to build and host web apps on the same systems that power Google applications. App Engine offers fast.
Web Development & Design Foundations with XHTML Chapter 9 Key Concepts.
Chapter 10 Form Basics Key Concepts Copyright © 2013 Terry Ann Morris, Ed.D 1.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide
CST JavaScript Validating Form Data with JavaScript.
A little engineering on Rails Robert W. Hasker. Goals Intro to the Rails framework ▫Basic concepts: MVC, Active Record ▫A bit of Ruby Using Rails to build.
RUBY ON RAILS Mark Zhang. In this talk  Overview of Ruby on Rails  Core ideas  Show a tiny bit of example code  Touch on several general web development/
1 Events Lect 8. 2 Event-driven Pages one popular feature of the Web is its interactive nature e.g., you click on buttons to make windows appear e.g.,
Tutorial #9 – Creating Forms. Tutorial #8 Review – Tables Borders (table, gridlines), Border-collapse: collapse; empty-cells: show; and rowspan, colspan.
Drboots presents. Web 101 Utility links | Join SWIFT | Pylons Navigation links Some place Another place Links Nothinghere Content goes here This is content…seriously.
Googe App Engine Codelab Marzia Niccolai May 28-29, 2008.
Server-side Scripting Powering the webs favourite services.
Web Technologies Website Development Trade & Industrial Education
HTML II. Factors to consider in designing a website. Organizing your files. HTML Tables. Unordered Lists. Ordered Lists. HTML Forms. Learning Objectives.
Cloud computing lectures: Programming with Google App Engine Keke Chen.
Amber Annett David Bell October 13 th, What will happen What is this business about personal web pages? Designated location of your own web page.
Meet with the AppEngine Márk Gergely eu.edge. What is AppEngine? It’s a tool, that lets you run your web applications on Google's infrastructure. –Google's.
PHP meets MySQL.
Just A Few More Fun Objectives 1 Having Some Fun With Java Script 2 Using Style Sheets.
Tutorial 7 Creating Forms. Objectives Session 7.1 – Create an HTML form – Insert fields for text – Add labels for form elements – Create radio buttons.
Creating Dynamic Web Pages Using PHP and MySQL CS 320.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
Android Boot Camp for Developers Using Java, 3E
Week 9 - Form Basics Key Concepts 1. 1.Describe common uses of forms on web pages 2.Create forms on web pages using the form, input, textarea, and select.
HTML: Hyptertext Markup Language Doman’s Sections.
Google App Engine Using Templates Jim Eng Thanks to Chuck Severance
PHP Form Introduction Getting User Information Text Input.
Google App Engine Data Store ae-10-datastore
Web Development 101 Presented by John Valance
App Engine Web App Framework Jim Eng
Caching Willem Visser RW334. Overview AppEngine Datastore No Caching Naïve Caching Caching invalidation Cache updating Memcached Beyond your code.
Visual Basic for Application - Microsoft Access 2003 Programming applications using Objects.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
Introduction to HTML. _______________________________________________________________________________________________________________ 2 Outline Key issues.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Bookstore Web Application: Client Tier Introducing Web Controls.
Spiderman ©Marvel Comics Creating Web Pages (part 1)
CPSC 203 Introduction to Computers T97 By Jie (Jeff) Gao.
Cascading Style Sheets Primary readings Presentations Explain & review projects with class mates.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
Chapter 12© copyright Janson Industries Java Server Faces ▮ Explain the JSF framework ▮ SDO (service data objects) ▮ Facelets ▮ Pagecode classes.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Web Database Programming Using PHP.
INTERNET APPLICATIONS CPIT405 Forms, Internal links, meta tags, search engine friendly websites.
HTML III (Forms) Robin Burke ECT 270. Outline Where we are in this class Web applications HTML Forms Break Forms lab.
Introduction to Database Programming with Python Gary Stewart
Google App Engine An Example!. Schedule Today: AppEngine and Python Wednesday: Review and CES! Friday Quiz!!! Next week: – DEMO MADNESS!!! – Approx 20.
Jim Fawcett CSE686 – Internet Programming Spring 2014
Web Database Programming Using PHP
Jim Fawcett CSE686 – Internet Programming Spring 2012
Human Computer Interaction
Web Database Programming Using PHP
Play Framework: Introduction
Python Web Development
Web DB Programming: PHP
Web Application Development Using PHP
Presentation transcript:

CS2021- Week 10 – Models and Views Web Development Model, Views, Controller Templates Databases

Model, View, Controller The MVC pattern is simple and very useful in web development. MVC pattern forces one to think of the application in terms of these three modules - Model : The core logic of the application. This maintains the state and data that the application represents. Controller : The functions of the user interface that manipulate the application. View : The user interface which displays information about the model to the user. Templates – DRY out Views (Don’t Repeat Yourself)

Templates Jinja2 is a powerful templating engine modeled after Django's templating system. Templates help to separate your logic (or model) from your presentation (or views). Here's the basic 3-Step process to get it working in AppEngine. Step 1: Modify 'app.yaml’ Open app.yaml from your AppEngine project directory in the editor of your choice. You need to do a few things here: 1) change the runtime attribute to python27, 2) add threadsafe: true, and 3) add the Jinja2 library in the configuration. Here's what your app.yaml might look like after you're done: application: foobar version: 1 runtime: python27 api_version: 1 threadsafe: true libraries: - name: jinja2 version: latest handlers: - url: /.* script: main.app

Templates in GAE Step 2: Move your HTML to a separate file – For the sake of this example, let's create a directory in your project folder called templates. Place your HTML code into a file called index.html, underneath your templates folder. Step 3: Modify your main Python script to use a Jinja2 template import os import webapp2 import jinja2 #copy this to set up jinja environment template_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape=True) class MainPage(webapp2.RequestHandler): def get(self): template_values = {'name': 'SomeGuy', 'verb': 'extremely enjoy'} template = jinja_env.get_template('index.html') self.response.out.write(template.render(template_values))

Databases and Python Traditional databases are organized around tables with schemas that name columns. We insert rows into tables and Queries such as SELECT return sets of rows referenced by “cursors”. Cursors can be used to operate and manipulate whole sets of rows. In Python we have lists and dictionaries – so there must be some mapping and glue to link python with a database application. Let’s start with construction of low level table in Python using the module from collections import namedtuple. The namedtuple class allows us to use sorted tuples with named columns.

Implementing a Table in Python with namedtuples from collections import namedtuple # make a basic Link class Link = namedtuple('Link', ['id', 'submitter_id', 'submitted_time', 'votes', 'title', 'url']) # list of Links to work with links = [ Link(0, 60398, , 109, "C overtakes Java as the No. 1 programming language in the TIOBE index.", " Link(1, 60254, , 891, "This explains why technical books are all ridiculously thick and overpriced", " Link(23, 62945, , 351, "Learn Haskell Fast and Hard", " Link(2, 6084, , 81, "Announcing Yesod 1.0- a robust, developer friendly, high performance web framework for Haskell", " Link(3, 30305, , 270, "TIL about the Lisp Curse", " Link(4, 59008, , 19, "The Downfall of Imperative Programming. Functional Programming and the Multicore Revolution", " Link(5, 8712, , 26, "Open Source - Twitter Stock Market Game - ", " Link(6, 48626, , 63, "First look: Qt 5 makes JavaScript a first-class citizen for app development", " 5-making-javascript-a-first-class-citizen-for-native-cross-platform- developme.ars"), Link(7, 30172, , 5, "Benchmark of Dictionary Structures", " Link(8, 678, , 7, "If It's Not on Prod, It Doesn't Count: The Value of Frequent Releases", " Link(9, 29168, , 18, "Language proposal: dave", " Link(17, 48626, , 1, "LispNYC and EmacsNYC meetup Tuesday Night: Large Scale Development with Elisp ", " Link(101, 62443, , 4, "research!rsc: Zip Files All The Way Down", " Link(12, 10262, , 5, "The Tyranny of the Diff", " tyranny-of-the-diff.html"), Link(13, 20831, , 14, "Understanding NIO.2 File Channels in Java 7", " Link(15, 62443, , 1244, "Why vector icons don't work", " icons.html"), Link(14, 30650, , 3, "Python - Getting Data Into Graphite - Code Examples", " graphite-code.html"), Link(16, 15330, , 9, "Mozilla: The Web as the Platform and The Kilimanjaro Event", " Y9v46wFeejA"), Link(18, 62443, , 104, "github is making me feel stupid(er)", " stupider/"), Link(19, 6937, , 39, "BitC Retrospective: The Issues with Type Classes", " Link(20, 51067, , 14, "Object Oriented C: Class-like Structures", " structures.html"), Link(10, 23944, , 188, "The LOVE game framework version has been released - with GLSL shader support!", " Link(22, 39191, , 11, "An open letter to language designers: Please kill your sacred cows. (megarant)", " Link(21, 3777, , 2, "Developers guide to Garage48 hackatron", " Link(24, 48626, , 17, "An R programmer looks at Julia", " Create a new python file from text at left, which uses the namedtuple module. Link is a class with 5 fields or columns. links is a list of Link objects each can be thought of as a row with 5 columns, each addressable using a name and dot notation. For example, a Link's number of votes can be accessed by alink.votes if ”alink" is Link. #Todo: make the function query() that returns the title of the link with the most number of votes. def query():

Databases and Python # make and populate a table of reddit links Import sqlite3 db = sqlite3.connect(':memory:') db.execute('create table links ' + '(id integer, submitter_id integer, submitted_time integer, ' + 'votes integer, title text, url text)') for l in links: db.execute('insert into links values (?, ?, ?, ?, ?, ?)', l) # db is an in-memory sqlite database that can respond to sql queries using the # execute() function. cursor1 = db.execute("select * from links where id = 5") cursor2 = db.execute(“select * from links where submitter_id = 5 OR votes > 23”) cursor3 = db.execute(“select * from links where votes > 10 order by votes”)

Queries in Python def query(): results = [] c = db.execute("select id from links where submitter_id = order by submitted_time asc") results = [t[0] for t in c] return results

Google App Engine Datastore We will be using the Google App Engine Datastore. This is a modern, non- relational database provided by App Engine. There are a couple of things you need to know about Google App Engine Datastore. What we have been referring to as tables are known as entities in Google App Engine Datastore. From a programmers point of view – GAE Datastore entities are somewhat analogous to set of Python Dictionaries each with a unique id and a common set of keys. The Python App Engine SDK includes a data modeling library for representing Datastore entities as instances of Python classes, and for storing and retrieving those instances in Datastore. See GQL In the App Engine Datastore we have something a little different then standard SQL database. Here we call it GQL and it is basically a simplified version of SQL that only works in the Datastore. The main difference between GQL and SQL is that all queries begin with SELECT *. There is no way to select individual columns. This also means we cannot do joins.

ASCII Chan We will build a website called ASCII Chan – a message board for sharing ASCII art. We will have a form that takes a title, some ASCII art and a submit button. A user can submit this and below the form the users will see ASCII art that has been submitted by other people. import os import webapp2 import jinja2 from google.appengine.ext import db template_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape=True) class Handler(webapp2.RequestHandler): def write(self, *a, **kw): self.response.out.write(*a, **kw) def render_str(self, template, **params): t = jinja_env.get_template(template) return t.render(params) def render(self, template, **kw): self.write(self.render_str(template, **kw)) class MainPage(Handler): def get(self): self.write("asciichan!") app = webapp2.WSGIApplication([('/', MainPage)], debug=True) Next Modify Main Handler: class MainPage(Handler): def get(self): self.render("front.html")

Create the Form /ascii/ /ascii/ title art

Handler for the form def post(self): title = self.request.get("title") art = self.request.get("art") if title and art: self.write("thanks!") else: error = "we need both a title and some artwork!" self.render("front.html", error = error) Add an error message at the bottom of the form (“front.html”): title art {{ error }}

Adding Parameters to preserve input in forms def post(self): title = self.request.get("title") art = self.request.get("art") if title and art: self.write("thanks!") else: error = "we need both a title and some artwork!" self.render_front(title, art, error)

Modified MainPage Handler class MainPage(Handler): def render_front(self, title="", art="", error=""): self.render("front.html", title=title, art=art, error = error) def get(self): self.render_front() def post(self): title = self.request.get("title") art = self.request.get("art") if title and art: self.write("thanks!") else: error = "we need both a title and some artwork!" self.render_front(error = error)

Creating Entities in GAE Datastore The way to define an entity in Google App Engine is to define a class derived from db.Model: from google.appengine.ext import db class Art(db.Model): title = db.StringProperty(required = True) art = db.TextProperty(required = True) created = db.DateTimeProperty(auto_now_add = True)

Working with Entities # Extend the success case in post Form Handler: if title and art: a = Art(title = title, art = art) a.put() self.redirect("/")

Queries in render_front function def render_front(self, title="", art="", error=""): arts = db.GqlQuery("SELECT * FROM Art ORDER BY created DESC") self.render("front.html", title=title, art=art, error = error, arts = arts) ______________________________________________________________________________________________________ /ascii/ title art {% for art in arts %} { {art.title}} { {art.art}} {% endfor %}

Styling body { font-family: sans-serif; width: 800px; margin: 0 auto; padding: 10px; } error { color: red; } label { display: block; font-size: 20px; } input[type=text] { width: 400px; font-size: 20px; padding: 2px; } textarea { width: 400px; height: 200px; font-size: 17px; font-family: monospace; } input[type=submit] { font-size: 24px; } hr { margin: 20px auto; }.art +.art { margin-top: 20px; }.art-title { font-weight: bold; font-size: 20px; }.art-body { margin: 0; font-size: 17px; } Improve the appearance of our web pages. Within the style element, we can specify the characteristics for the various elements in our HTML code. As an example, we can define the default style for the body (i.e. between the and of our web page using the style block to left.

Homework for Problem Set 3 Build a Blog cs253/l /e /m cs253/l /e /m