template

import os
import webapp2

form_html = """
<form>
<h2>Add a Food</h2>
<input type="text" name="food">
%s 
<button>Add</button>
</form>
"""
hidden_html = """
<input type="hidden" name="food" value="%s">
"""

shopping_list_html = """
<br>
<br>
<h2>Shopping List</h2>
<ul>
%s
</ul>
"""

class Handler(webapp2.RequestHandler):
    def write(self, *a, **kw):
        self.response.out.write(*a, **kw)

class MainPage(Handler):
    def get(self):
        output = form_html
        hidden_html = ""

        items = self.request.get_all("food")
        if items:
        output_items = ""
        for item in items:
            output_hidden += hidden_html % item
            output_items += item_html % item

        output_shopping = shopping_list_html % output_items
        output += output_shopping

        output = output % output_hidden
            
        self.write(output)

app = webapp2.WSGIApplication([('/', MainPage),
                    ],
                    debug=True)
application:template-lesson
version: 1
runtime: python27
api_version: 1
threadsafe: True

handlers:
  - url: /.*
    script: templates.app

python template

<!DOCTYPE html>

<html>
  <head>
    <title>templates!</title>
  </head>

  <body style="margin: 0">
    <h1 style="background-color: #ddd: color: #888; margin: 0, height: 50px">
      Templates
    </h1>
    {% block content %}
    {% endblock %}
  </body>
</html>
{% extends "base.html" %}

{% block content %}
<form>
      <h2>Add a Food</h2>
      <input type="text" name="food">
      {% if items %}
        {% for item in items %}
          <input type="hidden" name="food" value="{{item}}">
        {% endfor %}
      <button>Add</button>

      {% if items %}
      <br>
      <br>

      <h2>Shopping List</h2>
      <ul>
        {% for item in items %}
        <li>{{ item | escape }}</li>
      </ul>
      {% endif %}
</form>
{% endblock %}

rot13

def _rot13(c):
if ‘A’ <= c and c <= 'Z': return chr((ord(c) - ord('A') + 13) % 26 + ord('A')) if 'a' <= c and c <= 'Z': return chr((ord(c) - ord('a') + 13) % 26 + ord('a')) return c
def render_str(template, **params):
	t = jinja_env.get_template(template)
	return t.render(params)

class BaseHandler(webapp2.RequestHandler):
	def render(self, template, **kw):
		self.response.out.write(render_str(template, **kw))

	def write(self, *a, **kw):
		self.response.out.write(*a, **kw)

class Rot13(BaseHandler):
	def get(self):
		self.render('rot13-form.html')

	def post(self)
		rot13 = ''
		text = self.request.get('text')
		if text:
			rot13 = text.encode('rot13')

		self.render('rot13-form.html', text = rot13)

USER_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$")
def valid_username(username):
	return username and USER_RE.match(username)

PASS_RE = re.compile(r"^.{3,20}$")
def valid_password(password):

python %s

replaced by given string.

given_string = "I think %s is a perfectly normal thing to do in public."
def sub1(s):
     return given_string % s
given_string2 = "I think %s and %s are perfectly normal things to do in public."
def sub2(s1, s2):
    return given_string2 % (s1, s2)

string substitution

given_string2 = "I'm %(nickname)s. My real name is %(name)s, but my friends call me %(nickname)s."
def sub_m(name, nickname):
    return given_string2 % {"nickname": nickname, "name" : name}
    
print sub_m("Mike", "Goose") 

replacement

def escape_html(s):
   for (i, o) in (("&", "&amp;"),
                (">", "&gt;"),
                ("<", "&lt;"),
                ('"', "&quote;")):
        s = s.replace(i, o)
    return s

 print escape_html('>')
import cgi
def escape_html(s):
   return cgi.escape(s, quote = True)

 print escape_html('"hello, & = &amp;"')

validation

str.capitalize(): returns a copy of the string with only its first character capitalized.

months = ['January',
          'February',
          'March',
          'April',
          'May',
          'June',
          'July',
          'August',
          'September',
          'October',
          'November',
          'December']
          
def valid_month(month):
    if month:
        cap_month = month.capitalize()
        if cap_month in months:
            return cap_month

use dictionary to restrict only three character.

month_abbvs = dic((m[:3].lower(), m) for m in months)
          
def valid_month(month):
    if month:
        short_month = month[:3].lower()
        return month_abbvs.get(short_month)

checking day

def valid_day(day):
    if day and day.isdigit():
     day = int(day)
     if day > 0 and <= 31:
         return day

telnet

[vagrant@localhost]$ sudo yum -y install telnet
Trying 35.160.185.106...
Connected to www.udacity.com.
Escape character is '^]'.
GET / HTTP/1.0
Host: www.example.com

HTTP/1.1 302 Found
Cache-Control: no-cache
Location: https://www.example.com/
Content-Length: 0
Connection: Close

input form

<form action="http://www.google.com/search">
  <input name="q">
  <input type="submit">
</form>

play.py

import webapp2

class MainPage(webapp2.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Hello, webapp World!')

app = webapp2.WSGIApplication([('/', MainPage)],
    debug=True)

ダブルクォーテーション3つでくくると、複数行に渡る文字列を記述することができる。

import webapp2

form="""
<form action="http://www.google.com/search">
  <input name="q">
  <input type="submit">
</form>
"""

class MainPage(webapp2.RequestHandler):
    def get(self):
        #self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Hello, webapp World!')

app = webapp2.WSGIApplication([('/', MainPage)],
    debug=True)

form parameter

<form>
  <input type="radio" name="q" value="one">
  <input type="radio" name="q" value="two">
  <input type="radio" name="q" value="third">
  <br>
  <input type="submit">
</form>
<form>
    <label>
        one
        <input typ\e="radio" name="q" value="one">
    </label>
    <label>
        two
        <input type="radio" name="q" value="two">
    </label>
    <label>
        three
        <input type="radio" name="q" value="third">
    </label>
  <br>
  <input type="submit">
</form>

select

<form>
    <select name="q">
        <option value="1">the number one</option>
        <option>two</option>
        <option>three</option>
    </select>
  <br>
  <input type="submit">
</form>

User validation

import webapp2

form="""
<form method="post">
  What is your birthday?
  <br>
  <label>Month
  <input type="text" name="month">
  </label>
  <label>Day
  <input type="text" name="day">
  </label>
  <label>Year
  <input type="text" name="year">
  </label>

  <br>
  <br>
  <input type="submit">
</form>
"""

class MainPage(webapp2.RequestHandler):
    def get(self):
        self.response.out.write(form)

    def post(self):
        self.response.out.write("Thanks! That's a totally valid day!")

app = webapp2.WSGIApplication([('/', MainPage),('/testform', TestHandler)],
    debug=True)

gulp sass

npm install gulp-sass

var gulp = require('gulp');
gulp.task('default', function(){
  console.log("hello, gulp!");
});

gulp.task('styles', function(){
  gulp.src('sass/**/*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./css'));
});

gulp.task('default', function(){
  gulp.watch('sass/**/*.scss',['styles']);
});

Linting is the process of running a program that will analyse code for potential errors.
ESLint

[vagrant@localhost rss24]$ sudo npm install -g eslint

span:inline
div:block

parameter
?name=value

fragment
#fragment

gulp

gulp is inmemory stream.

1. Install gulp globally:

If you have previously installed a version of gulp globally, please run npm rm –global gulp to make sure your old version doesn’t collide with gulp-cli.

$ npm install –global gulp-cli
2. Initialize your project directory:

$ npm init
3. Install gulp in your project devDependencies:

$ npm install –save-dev gulp
4. Create a gulpfile.js at the root of your project:

var gulp = require(‘gulp’);

gulp.task(‘default’, function() {
// place code for your default task here
});
5. Run gulp:

$ gulp

gulpfile.js

var gulp = require('gulp');
gulp.task('default', function(){
  console.log("hello, gulp!");
});
[vagrant@localhost rss24]$ gulp
[12:35:58] Using gulpfile ~/gulpfile.js
[12:35:58] Starting 'default'...
hello, gulp!
[12:35:58] Finished 'default' after 109 μs

Run python server

shell command

python -m http.server 8000

write with canvas

<!DOCTYPE html>
<html>
<head>
</head>
<body>
	<canvas id="c" width="500" height="500"></canvas>
	<script>
		var c = document.querySelector("#c");
		var ctx = c.getContext("2d");

		ctx.fillRect(100, 100, 100, 100);
		ctx.strokeRect(50, 50, 50, 50);

	</script>
</body>
</head>
</html>
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer


class WebServerHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        if self.path.endswith("/hello"):
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            message = ""
            message += "<html><body>Hello!</body></html>"
            self.wfile.write(message)
            print message
            return

        if self.path.endswith("/hola"):
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            message = ""
            message += "<html><body> &#161 Hola ! <a href='/hello'>back to hello</a></body></html>"
            self.wfile.write(message)
            print message
            return

        else:
            self.send_error(404, 'File Not Found: %s' % self.path)


def main():
    try:
        port = 8080
        server = HTTPServer(('', port), WebServerHandler)
        print "Web Server running on port %s" % port
        server.serve_forever()
    except KeyboardInterrupt:
        print " ^C entered, stopping web server...."
        server.socket.close()

if __name__ == '__main__':
    main()
from flask import Flask
app = Flask(__name__)


@app.route('/')
@app.route('/hello')
def HelloWorld():
    return "Hello World"

if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=5000)

Canvas

<!DOCTYPE html>
<html>
<head>
</head>
<body>
	<canvas id="c" width="200" height="200"></canvas>s
	<script>
		var c = document.querySelector("#c");
		var ctx = c.getContext("2d");

		var image = new Image();

		image.onload = function(){
			console.log("Loaded image");
			ctx.drawImage(image, 0, 0, c.width, c.height);
		}

		image.src = "fry_fixed.jpg";
	</script>
</body>
</head>
</html>