Lecture 10(-ish) Web [Application] Frameworks

Similar documents
generates scaffolding/framework for models, views

widgets, events, layout loosely similar to Swing test browser, or plugin for testing with real browser on local system

정재성

NODE.JS SERVER SIDE JAVASCRIPT. Introduc)on Node.js

MIT AITI Python Software Development Lab DJ1:

Tomasz Szumlak WFiIS AGH 23/10/2017, Kraków

CE419 Web Programming. Session 15: Django Web Framework

A Sample Approach to your Project

Web technologies. Web. basic components. embellishments in browser. DOM (document object model)

Quick housekeeping Last Two Homeworks Extra Credit for demoing project prototypes Reminder about Project Deadlines/specifics Class on April 12th Resul

We are assuming you have node installed!

Javascript, Java, Flash, Silverlight, HTML5 (animation, audio/video, ) Ajax (asynchronous Javascript and XML)

HOW TO FLASK. And a very short intro to web development and databases

Information Retrieval CS Lecture 13. Razvan C. Bunescu School of Electrical Engineering and Computer Science

CIS 192: Lecture 11 Databases (SQLite3)

CSc 337 LECTURE 16: WRITING YOUR OWN WEB SERVICE

Graphene Documentation

Webdev: Building Django Apps. Ryan Fox Andrew Glassman MKE Python

CIS192 Python Programming

Server-Side Web Programming: Python (Part 2) Copyright 2017 by Robert M. Dondero, Ph.D Princeton University

Now go to bash and type the command ls to list files. The unix command unzip <filename> unzips a file.

welcome to BOILERCAMP HOW TO WEB DEV

NETB 329 Lecture 13 Python CGI Programming

29-27 May 2013 CERN WEB FRAMEWORKS. Adrian Mönnich

Reminders. Full Django products are due next Thursday! CS370, Günay (Emory) Spring / 6

About the Tutorial. Audience. Prerequisites. Disclaimer & Copyright. Django

Technology modeling. Ralf Lämmel Software Languages Team University of Koblenz-Landau

web.py Tutorial Tom Kelliher, CS 317 This tutorial is the tutorial from the web.py web site, with a few revisions for our local environment.

Strategies for Rapid Web Prototyping. Ruby on Rails. Clemens H. Cap

Asynchronous WebSockets using Django

Fundamentals of Web Programming

Web Programming with Python and JavaScript

Persistence. SWE 432, Fall 2017 Design and Implementation of Software for the Web

IERG Tutuorial 5. Benedict Mak

Reminders. Github & HTTP steps, together with the minimally viable Django product are due this coming Tuesday! CS370, Günay (Emory) Spring / 8

Backend Development. SWE 432, Fall Web Application Development

Flask Guide. Meher Krishna Patel. Created on : Octorber, 2017 Last updated : May, More documents are freely available at PythonDSP

SAURASHTRA UNIVERSITY

Module 6 Node.js and Socket.IO

Django urls Django Girls Tutorial

CSE 115. Introduction to Computer Science I

What is Node.js? Tim Davis Director, The Turtle Partnership Ltd

CMPT 165 INTRODUCTION TO THE INTERNET AND THE WORLD WIDE WEB

CIS192 Python Programming

LECTURE 14. Web Frameworks

Front End Programming

Accelerating Information Technology Innovation

Quoting Wikipedia, software

Accelerating Information Technology Innovation

CS50 Quiz Review. November 13, 2017

POSTGRESQL - PYTHON INTERFACE

South Africa Templates.

PHP: Hypertext Preprocessor. A tutorial Introduction

django-scaffold Documentation

Moving to a Sustainable Web Development Environment for Library Web Applications

Django starting guide

Ninja Typers Web Application Design Document By Marvin Farrell C

Back-end development. Outline. Example API: Chatter. 1. Design an example API for Chatter. Tiberiu Vilcu.

The Django Web Framework Part II. Hamid Zarrabi-Zadeh Web Programming Fall 2013

Backend Development. SWE 432, Fall 2017 Design and Implementation of Software for the Web

Lecture 6 Web Technologies

Building a Django Twilio Programmable Chat Application

About the Tutorial. Audience. Prerequisites. Disclaimer & Copyright. TurboGears

SAURASHTRA UNIVERSITY

Real-time node.js: Instrumentation, Visualization & Debugging. Bryan Cantrill SVP,

Tools. SWE 432, Fall Design and Implementation of Software for the Web

DIGIT.B4 Big Data PoC

Lecture 6 Web Technologies

CSC 405 Computer Security. Web Security

Introduction to HTTP. Jonathan Sillito

delegator Documentation

nacelle Documentation

Web Development for Dinosaurs An Introduction to Modern Web Development

DATABASE SYSTEMS. Database programming in a web environment. Database System Course, 2016

silk Documentation Release 0.3 Michael Ford

Jquery Ajax Json Php Mysql Data Entry Example

Web Frameworks MMIS 2 VU SS Denis Helic. March 10, KMI, TU Graz. Denis Helic (KMI, TU Graz) Web Frameworks March 10, / 18

web frameworks design comparison draft - please help me improve it focus on Model-View-Controller frameworks

Building Web Applications

7401ICT eservice Technology. (Some of) the actual examination questions will be more precise than these.

Node.js. Node.js Overview. CS144: Web Applications

Persistence & State. SWE 432, Fall 2016 Design and Implementation of Software for the Web

django-osm-field Release 0.3.1

Django: Views, Templates, and Sessions

django-xross Documentation

NodeJS and JavaScripteverywhere

Introduction and first application. Luigi De Russis. Rails 101

Simple But Useful Tools for Interactive WWW Development

DATABASE SYSTEMS. Database programming in a web environment. Database System Course,

CS 155 Project 2. Overview & Part A

Flask-Genshi Documentation

The Impact of Django. Armin Ronacher. djangocon europe 2011

Server-Side Web Programming: Python (Part 1) Copyright 2017 by Robert M. Dondero, Ph.D. Princeton University

MIT Global Startup Labs México 2013

L6 Application Programming. Thibault Sellam Fall 2018

CSCI-UA: Database Design & Web Implementation. Professor Evan Sandhaus

1 Form Basics CSC309

Networking & The Web. HCID 520 User Interface Software & Technology

EXPERIENCES MOVING FROM DJANGO TO FLASK

END-TO-END JAVASCRIPT WEB APPS

Transcription:

Lecture 10(-ish) Web [Application] Frameworks

Minimal Python server import SocketServer import SimpleHTTPServer class Reply(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_get(self): # query arrives in self.path; return anything, e.g., self.wfile.write("query was %s\n" % self.path) def main(): # do initialization or whatever SocketServer.ForkingTCPServer('', 8080), Reply).serve_forever() main()

Overview of [web [application]] frameworks client-server relationship is stereotypical client sends requests using information from forms server parses request, calls proper function, which retrieves from database, formats response, returns it REST: URL filenames often used to encode requests /login/name /add/data_to_be_added /delete/id_to_delete server uses URL pattern to call proper function with right arguments server usually provides structured & safer access to database server may provide templating language for generating HTML e.g., replace {% foo %} with value of variable foo, etc. framework may automatically generate an administrative interface often library routines for user ids, passwords, registration, etc.

Flask: Python-based microframework $ cat hello.py import flask app = flask.flask( name ) @app.route('/') def hello(): return 'Hello world' app.run() $ python hello.py

Sending form data <html> <title>survey demo</title> <body> <form METHOD=POST ACTION="http://localhost:5000"> <p> Name: <input type="text" name=name id=name > <p> Netid: <input type="text" name=netid id=netid > <p> Class: <input type="radio" name=class value="2018"> '18 <input type="radio" name=class value="2019"> '19 <input type="radio" name=class value="2020"> '20 <p> Courses: <input type="checkbox" name=c126> 126 <input type="checkbox" name=c217> 217 <input type="checkbox" name=c226> 226 <p> <input type="submit" value="submit"> <input type=reset> </body> </html>

Processing form data # survey.py from flask import Flask, request app = Flask( name ) @app.route('/', methods=['post','get']) def survey(): s = "" for (k,v) in request.form.iteritems(): s = "%s %s=%s<br>" % (s, k, v) return 'Form contents:<br>' + s app.run()

Add a database with SQLite (1) from flask import Flask import re import sqlite3 from flask import g from flask import request DATABASE = '/Users/bwk/flask/database.db' app = Flask( name ) def get_db(): db = getattr(g, '_database', None) if db is None: db = g._database = sqlite3.connect(database) return db @app.teardown_appcontext def close_connection(exception): db = getattr(g, '_database', None) if db is not None: db.close()

Add a database with SQLite (2) def query_db(query, args=(), one=false): cur = get_db().execute(query, args) rv = cur.fetchall() cur.close() return (rv[0] if rv else None) if one else rv @app.route('/save/<str>') def save(str): t = (str,) cur = get_db().execute('insert into lines values (?)', t) get_db().commit() cur.close() return 'save ' + str @app.route('/find/<str>') def find(str): all = query_db('select * from lines') s = '' for i in all: if re.search(str, i[0])!= None: s = "%s%s\n" % (s, i[0]) return '<pre>%s\n%s</pre>' % (str, s)

Add a database with SQLite (3) @app.route('/') def index(): return 'Usage: /save/text or /find/regexp' if name == " main ": app.run()

Python @ decorators a way to insert or modify code in functions and classes @decorate function foo(): compilation compiles foo, passes the object to decorate, which does something and replaces foo by the result used in Flask to manage URL routing @app.route('/find/<str>') def find(str): all = query_db('select * from lines') s = '' for i in all: if re.search(str, i[0])!= None: s = "%s%s\n" % (s, i[0]) return '<pre>%s\n%s</pre>' % (str, s)

Django: more heavyweight Python-based framework by Adrian Holovaty and Jacob Kaplan-Moss (released July 2005) a collection of Python scripts to create a new project / site generates Python scripts for settings, etc. configuration info stored as Python lists create a new application within a project generates scaffolding/framework for models, views run a development web server for local testing Django Reinhart, 1910-1953 generate a database or build interface to an existing database provide a command-line interface to application create an administrative interface for the database run automated tests...

Conventional approach to building a web site user interface, logic, database access are all mixed together import MySQLdb print "Content-Type: text/html" print print "<html><head><title>books</title></head>" print "<body>" print "<h1>books</h1>" print "<ul>" connection = MySQLdb.connect(user='me', passwd='x', db='my_db') cursor = connection.cursor() cursor.execute("select name FROM books ORDER BY pub_date DESC") for row in cursor.fetchall(): print "<li>%s</li>" % row[0] print "</ul>" print "</body></html>" connection.close()

Model-View-Controller (MVC) pattern model: the structure of the data how data is defined and accessed view: the user interface what it looks like on the screen can have multiple views for one model controller: how information is moved around processing events, gathering and processing data, generating HTML,... separate model from view from processing so that when one part changes, the others need not used with varying fidelity in frameworks not always clear where to draw the lines but trying to separate concerns is good

Django web framework write client code in HTML, CSS, Javascript,... Django template language helps separate form from content write server code in Python some of this is generated for you write database access with Python library calls they are translated to SQL database commands djangobook.com URLs on web page map mechanically to Python function calls regular expressions specify classes of URLs URL received by server is matched against regular expressions if a match is found, that identifies function to be called and arguments to be provided to the function

Django automatically-generated files generate framework/skeleton of code by program three basic files: models.py: database tables, etc. views.py: business logic, formatting of output urls.py: linkage between web requests and view functions plus others for special purposes: settings.py: db type, names of modules,... tests.py: test files admin.py: admin info templates: for generating and filling HTML info

Example database linkage DATABASES = { in settings.py 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '/Users/bwk/django/sql3.db',... from django.db import models class Post(models.Model): title = models.textfield(5) text = models.textfield() in models.py BEGIN; CREATE TABLE "blog_post" ( "id" integer NOT NULL PRIMARY KEY, "title" text NOT NULL, "text" text NOT NULL ) ; generated by Django

URL patterns regular expressions used to recognize parameters and pass them to Python functions provides linkage between web page and what functions are called for semantic actions urlpatterns = patterns('', (r'^time/$', current_datetime), ) (r'^time/plus/(\d{1,2})/$', hours_ahead), a reference to web page /time/ calls the function current_datetime() tagged regular expressions for parameters: url /time/plus/12 calls the function hours_ahead(12)

Templates for generating HTML try to separate page design from code that generates it Django has a specialized language for including HTML within code loosely analogous to PHP mechanism # latest_posts.html (the template) <html><head><title>latest Posts</title></head> <body> <h1>posts</h1> <ul> {% for post in post_list %} <li>{{ post.title }} {{ post.text }}</li> {% endfor %} </ul> </body></html>

Administrative interface most systems need a way to modify the database even if initially created from bulk data add / remove users, set passwords,... add / remove records fix contents of records... often requires special code Django generates an administrative interface automatically loosely equivalent to MyPhpAdmin

Alternatives Ruby on Rails Google App Engine Node + Express Google Web Toolkit and lots of others

Node.js server var http = require('http'); http.createserver(function (req, res) { res.writehead(200, {'Content-Type': 'text/plain'}); res.end('hello World\n'); }).listen(1337, '127.0.0.1'); Express framework for Node analogous to Flask

Express framework var express = require('express') var app = express() app.get('/', function (req, res) { res.send('hello World!') }) app.listen(3000, function () { console.log('example app listening on port 3000!') })

Assessment of Web Frameworks advantages takes care of repetitive parts more efficient in programmer time automatically generated code is likely to be more reliable, have more uniformity of structure "DRY" (don't repeat yourself) is encouraged "single point of truth"... information is in only one place so it's easier to change things potential negatives automatically generated code can be hard to figure out what's going on can be hard to change if you don't want to do it their way systems are large and can be slow... read Joel Spolsky's "Why I hate frameworks" http://discuss.joelonsoftware.com/default.asp?joel.3.219431.12

Package managers pip Python (pypi.python.org/pypi/pip) pip install Django apt-get Ubuntu Linux apt-get install whatever npm Node.js (yarn is a wrapper around npm) npm install node port Macports port install ruby brew Homebrew brew install ruby gem Ruby...