Publications: 82 | Followers: 0

HTML & CSS - eecg.toronto.edu

Publish on Category: Birds 0

Web Framework
Presenter: James HuangDate: Sept. 29, 2014
1
HTTP and WWWBottle Web FrameworkRequest RoutingSending Static FilesHandling HTML <Form>HTTP Errors and RedirectsCookiesTemplatesPluginsDemo
Outline
2
World Wide Web (WWW) uses Hypertext Transfer Protocol (HTTP) as a standard for web client and web server to communicate.HTTP uses arequest-responsecomputing model.A server listens for clients’ connection over TCP.A client (e.g. web browser) sends a request message to server.The server sends back a status line followed by a response message.HTTP is a stateless protocol.Web applications often usecookiesto maintain states.
3
HTTP and WWW
An HTTP client specifies request methods to distinguish different types of actionsto be performed onthe server.GETRetrievesdatafrom the serverShould not have other effect on the serverPOSTRequests that the server accepts the data enclosed in the requestUsed to submit a form, upload a file, etc.
4
HTTP Request Methods
An HTTP session is a sequence of request-response transactions.
5
HTTP Session
GET /index.html HTTP/1.1Host: www.example.com
HTTP/1.0200 OKDate: Mon, 29 Sep 2014 03:50:21 GMTServer:WSGIServer/0.1 Python/2.7.2Content-Length:32Content-Type: text/html;charset=UTF-8<html><body>Hello World.</body></html>
1.
2.
Web Server
Web Client
Bottle is a web server that allows developers to write web applications in Python.It is easy to install and use.Implemented in PythonHas no dependency on any external librariesWriting web application for Bottle is simple.A web application consists ofcallback functionsthat are called by Bottle to handle HTTP requests.Bottle handles errors and exceptions automatically.
6
Bottle Web Framework
7
Bottle Web Application - Example
#Asimple webapplicationfrombottle importrun, route@route('/')defhome():return'<html><body>Hello World.</body></html>‘run(host='localhost', port=8080, debug=True)
hello.py:
Links ‘/’ to home()
Starts web server on port 8080
Imports Bottle web framework
URLs are linked to callback functions withroute()decorator.URLcontains wildcards,dynamic route,can be used to match more than one URL.@route(‘/hello/<name>’)defhello(name):return greet(name)More than one route can be used for a single callback function.@route(‘/’)@route(‘/hello/<name>’)defhello(name=‘Stranger’):return greet(name)
8
Request Routing
A simple wildcard (e.g. <name>) matches one or more characters up to the next slash (‘/’).E.g. ‘/hello/<name>’ matches ‘/hello/bob’, but not ‘/hello’ or ‘/hello/john/smith’.Each wildcard passes the matched part of URL as a keyword argument to the callback function.Filterscan be used to match specific wildcards and converts matched part of URL.:int– matches digits only and converts the value to integer:path – matches more than one path segment:re – matches with a regular expression
9
Dynamic Route
Aweb application needs to have a callback to handle which files to serve to aclient.Bottledoes not automatically serve files to client.Bottle providesstatic_file()helper function.
10
Sending Static Files
from bottle importstatic_file@route('/images/<filename:re:.*\.png>')defsend_image(filename):returnstatic_file(filename, root='/path/to/image/files',mimetype='image/png')@route('/html/<filepath:path>')defserver_static(filepath):returnstatic_file(filepath, root='/path/to/your/html/files')
match URL with regular expression
match URL with path
HTML usually specify to use POST request method to send form data.Bottle’s route decorator applies to GET request method by default.A web application can specify request method as an argument of route decorator.E.g.@route(‘/login’, method=‘POST’)Bottle also provides different decorators to handle different request methods:@get,@post, etc. as shortcuts.The value of an Input field of a form can be retrieved withrequestobject.
11
Handling HTML <Form>
12
Handling HTML <Form> - Example
login() is called when user browseto /login
do_login() is called when user submit the form
request object is used to retrievethe value of an input field
Theabort()function is used to generate an HTTP error page.from bottle import route, abort@route('/restricted')defrestricted():abort(401, "Sorry, access denied.")Theredirect()function redirects a client to a different URL.from bottle importredirect@route('/wrong/url')defwrong():redirect("/right/url")
13
HTTP Errors and Redirects
A cookie stores site-specific text information in a web browser’s profile.A web application creates a new cookie withResponse.set_cookie(), access a cookie withRequest.get_cookie().
14
Cookies
@route('/hello')defhello_again():ifrequest.get_cookie("visited"):return"Welcome back! Nice to see you again"else:response.set_cookie("visited", "yes")return"Hello there! Nice to meet you"
A cookie can be controlled with different settings.max_age: maximum age in secondsexpires: the timestamp when the cookie expiressecure: limit the cookie to HTTPS connectionsThese settings can be specified as keyword arguments toResponse.set_cookie().Cookie expires at the end of a browser session, unlessmax_ageorexpiresis set.
15
Cookies - Continued
Bottle provide a convenient way to generate web page from templates.Here is an example template:A web application uses templates withtemplate()function.
16
Templates
%if name == 'World':<h1>Hello{{name}}!</h1><p>This is a test.</p>%else:<h1>Hello {{name.title()}}!</h1><p>How are you?</p>%end
@route('/hello/<name>')defhello(name):returntemplate('hello_template', name=name)
Python-like syntax
hello_template.tpl
Bottle supports third-party plugins:Bottle-Sqlite: SQLite3 database pluginBottle-Redis:Redisdatabase pluginBottle-Flash: flash plugin
17
Plugins
from bottle import route, install, templatefrombottle_sqliteimportSQLitePlugininstall(SQLitePlugin(dbfile='/tmp/test.db'))@route('/show/<post_id:int>')defshow(db,post_id):c =db.execute('SELECT title, content FROM posts WHERE id = ?', (post_id,))row =c.fetchone()return template('show_post', title=row['title'], text=row['content'])
SQLitePlugindetects the use ofdband creates a new database connection.
Thank you!contact: z.huang@utoronto.ca
18

0

Embed

Share

Upload

Make amazing presentation for free
HTML & CSS - eecg.toronto.edu