Last Updated: February 25, 2016
·
2.621K
· tonyseek

Play with PyPy

Creating a virtualenv and enter it

The virtualenv creating script of CPython could be used for PyPy

$ mkdir experiment
$ virtualenv -p $(which pypy) ./experiment
$ source ./experiment/bin/activate

Now pip is available

$ pip install Pillow bottle

Writing a hello world with a web interface

import bottle

@bottle.route("/")
def hello():
    return "hello, world"

if __name__ == "__main__":
    bottle.run(port="8000")

Using the Greenlet of PyPy built-in library

@greenlet.greenlet
def second():
    print "now you are in the second greenlet"
    first.switch()

@greenlet.greenlet
def first():
    second.switch()
    print "the return of the first greenlet"     

first.switch()

Writing a hello world with PIL

#!/usr/bin/env python
#-*- coding:utf-8 -*-

from StringIO import StringIO

from bottle import route, response, debug, run
from PIL import Image, ImageDraw

def draw_text(text):
    background = Image.new("RGBA", (500, 20), "white")
    draw = ImageDraw.Draw(background)
    draw.text((5, 5), text, fill="red")
    return background

def get_image_bytes(image, format="PNG"):
    image_buffer = StringIO()
    image.save(image_buffer, format=format)
    return image_buffer.getvalue()

@route("/:name")
@route("/")
def hello(name="world"):
    image = draw_text("hello, %s" % name.lower())
    image_bytes = get_image_bytes(image, "PNG")
    response.content_type = "image/png"
    return image_bytes

if __name__ == "__main__":
    debug(True)
    run(reloader=True, port=8001)