CIS 192: Lecture 10 Web Development with Flask



Similar documents
CIS 192: Lecture 10 Web Development with Flask

Web Development with Flask and the Raspberry Pi Leading by Example CUAUHTEMOC CARBAJAL ITESM CEM 22/04/2014

Flask Documentation. Release

Web [Application] Frameworks

latest Release 0.2.6

Flask Web Development. Miguel Grinberg

Modern Web Application Framework Python, SQL Alchemy, Jinja2 & Flask

Server-side Development using Python and SQL

Outline. Lecture 18: Ruby on Rails MVC. Introduction to Rails

Implementing 2-Legged OAuth in Javascript (and CloudTest)

CME 193: Introduction to Scientific Python Lecture 8: Unit testing, more modules, wrap up

Electronic Ticket and Check-in System for Indico Conferences

Flask-SSO Documentation

Mojolicious. Marcos Rebelo

MYOB EXO BUSINESS WHITE PAPER

Slides from INF3331 lectures - web programming in Python

The Django web development framework for the Python-aware

Omicron Server Documentation

Advanced Tornado TWENTYONE Advanced Tornado Accessing MySQL from Python LAB

7 Why Use Perl for CGI?

Salesforce Opportunities Portlet Documentation v2

Force.com Canvas Developer's Guide

Cloud Elements! Marketing Hub Provisioning and Usage Guide!

Programming Autodesk PLM 360 Using REST. Doug Redmond Software Engineer, Autodesk

Nupic Web Application development

Configuration Guide - OneDesk to SalesForce Connector

How to Re-Direct Mobile Visitors to Your Library s Mobile App

People Data and the Web Forms and CGI CGI. Facilitating interactive web applications

HTTP - METHODS. Same as GET, but transfers the status line and header section only.

Cloud Elements ecommerce Hub Provisioning Guide API Version 2.0 BETA

CSC 551: Web Programming. Spring 2004

Webmail Using the Hush Encryption Engine

Drupal CMS for marketing sites

Office365Mon Developer API

Step One Check for Internet Connection

socketio Documentation

Rapid Website Deployment With Django, Heroku & New Relic

Riverbed Cascade Shark Common REST API v1.0

Creating Java EE Applications and Servlets with IntelliJ IDEA

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

Build an ArcGIS Online Application

Enterprise Access Control Patterns For REST and Web APIs

SYSPRO App Store: Registration Guide

Evaluation. Chapter 1: An Overview Of Ruby Rails. Copy. 6) Static Pages Within a Rails Application

itds OAuth Integration Paterva itds OAuth Integration Building and re-using OAuth providers within Maltego 2014/09/22

Pentesting Web Frameworks (preview of next year's SEC642 update)

PaaS Operation Manual

Administering Jive Mobile Apps

OpenID Single Sign On and OAuth Data Access for Google Apps. Ryan Dave Primmer May 2010

OAuth 2.0 Developers Guide. Ping Identity, Inc th Street, Suite 100, Denver, CO

Dell One Identity Cloud Access Manager How to Develop OpenID Connect Apps

Save Actions User Guide

Oracle Forms Services Secure Web.Show_Document() calls to Oracle Reports Server 6i

A detailed walk through a CAS authentication

Configuring Single Sign-on for WebVPN

eccharts: Behind the scenes

CROWNPEAK C# API SYSTEM CONFIGURATION GUIDE VERSION 3.0.1

T320 E-business technologies: foundations and practice

From Delphi to the cloud

CrownPeak Platform Dashboard Playbook. Version 1.0

ICON UK 2015 node.js for Domino developers. Presenter: Matt White Company: LDC Via

IERG 4080 Building Scalable Internet-based Services

Intruduction to Groovy & Grails programming languages beyond Java

Whisler 1 A Graphical User Interface and Database Management System for Documenting Glacial Landmarks

Rails 4 Quickly. Bala Paranj.

Administering Jive for Outlook

CGI Programming. Examples

What about MongoDB? can req.body.input 0; var date = new Date(); do {curdate = new Date();} while(curdate-date<10000)

The Social Accelerator Setup Guide

A Tour of Silex and Symfony Components. Robert

Web development... the server side (of the force)

Traitware Authentication Service Integration Document

Creating Web Services Applications with IntelliJ IDEA

Integrating LivePerson with Salesforce

Version USER GUIDE

Bubble Code Review for Magento

skype ID: store.belvg US phone number:

Copyright Pivotal Software Inc, of 10

Tableau Server Trusted Authentication

TROUBLESHOOTING RSA ACCESS MANAGER SINGLE SIGN-ON FOR WEB-BASED APPLICATIONS

Modern Web Applications with Flask and Backbone.js. /Yaniv (Aknin Ben-Zaken)/ February 2013

Login with Amazon. Getting Started Guide for Websites. Version 1.0

Lecture 11 Web Application Security (part 1)

JupyterHub Documentation

Creating federated authorisation

Multi Factor Authentication API

Salesforce Files Connect Implementation Guide

Magento Security and Vulnerabilities. Roman Stepanov

int_adyen Version

Salesforce Integration User Guide Version 1.1

Transcription:

CIS 192: Lecture 10 Web Development with Flask Lili Dworkin University of Pennsylvania

Web Frameworks We ve been talking about making HTTP requests What about serving them? Flask is a microframework small and simple, and you can see how and why everything is happening Django is the big guy on the block more fully featured, but also more black magic / mysterious

Hello World from flask import Flask app = Flask( name ) @app.route('/') def hello_world(): return "Hello World!" if name == ' main ': app.run() prompt$ python flask.py * Running on http://127.0.0.1:5000/

Hello World app = Flask( name ) When we create an instance of the Flask class, the first argument is the name of the application s module or package When using a single module, use name because this will work regardless of whether name equals main or the actual import name

Hello World @app.route('/') def hello_world(): return "Hello World!" The app.route('/') decorator tells Flask to call the hello_world() function when the relative url / is accessed The hello_world() function returns the web page (in this case, a simple string) to be displayed

Hello World app.run() The app.run() function runs the application on a local server This will only be visible on your own computer! We will talk about deployment later

Debugging When testing, use app.run(debug=true) Now the server will reload itself on code changes Additionally, you will see error messages in the browser But never leave this on in production!

More Routing @app.route('/bad') def bad(): return 'hi' + 4 @app.route('/bye') def bye_world(): return "Bye World!"

Variable Rules To add variable parts to a url, use <variable_name> The variables are passed as arguments to the function @app.route('/user/<username>') def greet_user(username): return "Hello %s!" % username

Variable Rules Multiple urls can route to the same function: @app.route('/name/<first>') @app.route('/name/<first>/<last>') def greet_name(first, last=none): name = first + ' ' + last if last else first return "Hello %s!" % name

Templating What about some real HTML? Flask uses a templating system called Jinja. <!doctype html> <title>hello from Flask</title> {% if name %} <h1>hello {{ name }}!</h1> {% else %} <h1>hello World!</h1> {% endif %} Need to put this in a templates folder.

Templating from flask import render_template @app.route('/template/') @app.route('/template/<name>') def template(name=none): return render_template('index.html', name=name)

GET Requests Recall: a url can be accessed with parameters, i.e. /hello?key=value Retrieve these parameters from the request.args dictionary from flask import request @app.route('/args') def args(): html = '' for key, value in request.args.items(): html += '%s=%s' % (key, value) html += '<br/>' return html

GET Requests Even better, using templates: <!doctype html> <title>displaying Params</title> <ul> {% for key, value in params.items() %} <li>{{ key }}={{ value }}</li> {% endfor %} </ul> @app.route('/template_args') def template_args(): return render_template('params.html', params= request.args)

POST Requests We can also make POST requests to a url Add keyword argument methods=['post', 'GET'] to the app.route() decorator Check if a request was a POST by looking at request.method The data from a POST request can be retrieved from the request.form dictionary

POST Requests @app.route('/post', methods=['post', 'GET']) def post(): if request.method == 'POST': return request.form.get('data', 'default') else: return 'That was a GET request.' >>> req = requests.post('http://127.0.0.1:5000/post', data={'data':'test data'}) >>> req.text u'test data' >>> req = requests.post('http://127.0.0.1:5000/post') >>> req.text u'default'

Returning JSON Instead of returning HTML source, what if we want to return JSON? from flask import jsonify @app.route('/json') def return_json(): return jsonify({'some': 'data'}) >>> req = requests.get('http://127.0.0.1:5000/json') >>> req.json() {u'some': u'data'}

Sessions Sometimes you need to store information between requests. For this we use the session object, which is essentially a cookie. from Flask import session app.secret_key = os.urandom(24) @app.route('/step1') def step1(): session['key'] = '12345' return 'Saved key.' @app.route('/step2') def step2(): key = session['key'] return 'Retrieved key: %s.' % (key)

url for What if we need to know the link for one of our functions? from Flask import url_for @app.route('/url') def url(): html = 'relative url: %s <br/>' % (url_for('bye_world')) html += 'absolute url: %s' % (url_for('bye_world', _external=true)) return html

Back to Twitter Let s recall the 3-legged OAuth process: 1. Get a request token 2. Send user to an authorization url 3. Redirect user back to application with their pin/verifier 4. Get an access token 5. Post to Lili s Twitter account

Back to Twitter Getting request/access tokens is a little tricky we need to: 1. Put together the consumer/key secret (use oauth.consumer) 2. For the access token only: Put together the request token key/secret (use oauth.token) 3. Put our params in a dictionary For the request token, this is {oauth_callback:...} For the access token, this is {oauth_verifier:...} 4. Make a signed request (use oauth.request) 5. POST to the signed url 6. Parse the body of the response for the key and secret The response body will be of the form oauth token=xxx&oauth token secret=xxx

Back to Twitter Posting the status update is pretty similar: 1. Put together the consumer/key secret (use oauth.consumer) 2. Put together the access token key/secret (use oauth.token) 3. Put our params in a dictionary: {status:...} 4. Make a signed request (use oauth.request) 5. POST to the signed url