Showing posts with label web.py. Show all posts
Showing posts with label web.py. Show all posts

Friday, January 25, 2013

Sidekick 3

RaspberryPi the sidekick


McDonald's is currently advertising that "every hero needs a sidekick". Of course, if you've been following my blog, you already know this for a fact.

In the previous Sidekick articles (sidekick and sidekick 2), we saw how we could run a program on the Raspberry Pi, and the display would then be forwarded to another computer, through the use of X forwarding with ssh (-X).

One side effect of that mode is that the program will detect the X Windows property of the PC, and not the Raspberry Pi. For example, if your X server on your PC supports Open GL, although the Raspberry Pi supports only Open GL ES 2.0, the program will see the full Open GL stack.

It can be a good thing, but sometimes it can lead to surprises. Another limitation is the windowing.

Windowed


When running a single application, this is the best way to use the Raspberry Pi as a sidekick. But don't forget to use the X forwarding, else you get:

pi@raspberrypi ~ $ idle
Traceback (most recent call last):
  File "/usr/bin/idle", line 5, in <module>
    main()
  File "/usr/lib/python2.7/idlelib/
PyShell.py", line 1406, in main
    root = Tk(className="Idle")
  File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1688, in __init__
    self.tk = _tkinter.create(screenName, baseName, className,
interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable


If we use ssh -X (or X forwarding in putty), it works as intended:

idle main window

And if we go to file and do an open, we see the files that are on the Raspberry Pi. Let me open the quick and dirty cam server we did at the last PyHack workshop (I'm putting the code in text too)


#!/usr/bin/env python

import web

class Images:
    def GET(self):
        typemap = {
        "png":"image/png",
        "jpg":"image/jpeg",
        }
        web.header("Content-Type",typemap["png"])
        return open("fablocker.png","rb").read()

URLS = ( "/secret", Images ,
)

app = web.application(URLS, globals())

if __name__ == "__main__":
    app.run()

 This is just the web server side of things and is using web.py

idle new editor window

We now have 2 windows of programs running on the Raspberry Pi, but displaying on our computer's desktop.

But sometimes it's important to have a full desktop. So how do we do this, to see the whole Raspberry Pi desktop?

VNC


The solution is Virtual Network Computing (VNC).

There are many implementations of the protocol, and they fall into 2 camps.
  • The kind that gives you a new desktop (it is not the same as the one that is on the HDMI output)
  • and the kind that attaches to the original desktop.

 

the client


Before installing the server, let's talk about the client. On your PC, if you have a unix or linux machine, there is a chance that you have a program called vncviewer. Try it and see if you do. If not, you will have to install it. This will depend greatly on what operating system you run, as far as how to do that. If your desktop is a *nix, I'm sure you know how to use your package manager to get vncviewer.

Under Windows you can get tightvnc for windows or you can try the multiplatform (Linux, Solaris, Windows, Mac) RealVNC. Many Mac users are partial to Chicken of the VNC.

tightvnc

Tightvnc is of the first category of servers. This has the advantage that you can get a graphical desktop, even if your Raspberry Pi is on the command line, without X windows started.

First we will have to install it:

$ ssh -X pi@raspberrypi

pi@raspberrypi ~ $ sudo apt-get install tightvncserver
pi@raspberrypi ~ $ tightvncserver :1

You will require a password to access your desktops.

Password:
Verify:
Would you like to enter a view-only password (y/n)? n

New 'X' desktop is raspberrypi:1

Creating default startup script /home/pi/.vnc/xstartup
Starting applications specified in /home/pi/.vnc/xstartup
Log file is /home/pi/.vnc/raspberrypi:1.log

 And that should work, when you access your Pi remotely with a client.

It is also possible with tightvnc to specify a screen resolution that you choose, and it wont have anything to do with the Raspberry Pi screen resolution or your monitor's capability. For example, to get a 1024x768 desktop:

pi@raspberrypi ~ $ tightvncserver -geometry 1024x768 :1

Of course if tightvnc works well for you, you will want to automate the startup of the server. Stewart Watkiss posted the following startup script on elinux.org (would go under /etc/init.d as tightvncserver):

#!/bin/sh
# /etc/init.d/tightvncserver
# Customised by Stewart Watkiss
#http://www.penguintutor.com/linux/tightvnc
# Set the VNCUSER variable to the name of the user
# to start tightvncserver under
VNCUSER='pi'
eval cd ~$VNCUSER
case "$1" in
 start)
   su $VNCUSER -c '/usr/bin/tightvncserver :1'
   echo "Starting TightVNC server for $VNCUSER "
   ;;
 stop)
   pkill Xtightvnc
   echo "Tightvncserver stopped"
   ;;
 *)
   echo "Usage: /etc/init.d/tightvncserver {start|stop}"
   exit 1
   ;;
esac
exit 0

And then under .vnc, a xstartup file that contains the following:

!/bin/sh
xrdb $HOME/.Xresources
xsetroot -solid black
/usr/bin/lxsession -s LXDE &
  
And that should be it. After rebooting, it should start automatically. If you prefer x11vnc, then follow the next set of instructions instead.

x11vnc


x11vnc falls into the second category of servers. It will attach to the X server of the Raspberry Pi. As such, you have to run LXDE, you can't stay in console text mode.

To install it:

$ ssh -X pi@raspberrypi

pi@raspberrypi ~ $ sudo apt-get install x11vnc
pi@raspberrypi ~ $ x11vnc -storepasswd

You'll have to enter a password. Next we need to configure the startup with lxde:

pi@raspberrypi ~ $ cd .config
pi@raspberrypi ~ $ mkdir autostart
pi@raspberrypi ~ $ cd autostart
pi@raspberrypi ~ $ wget http://brython.heliohost.org/x11vnc.desktop

Be patient on the last step, this is getting a startup file for x11vnc from my Brython playground site. It is usually pretty busy... Reboot the Pi and you should be set.


Accessing the Pi


Once you have the server running, you run the viewer on your PC, and specify the ip address (or name if you have avahi or the like), you will be greeted with a password prompt. That is the password you defined for the server, earlier:




And then, the desktop!


1024x768 Raspbian desktop, from my PC
@f_dion

Monday, January 14, 2013

encabezamientos http

web.py


El sábado pasado, llevamos a cabo un taller PyHack. El tema era sobre cámaras web, pygame y el raspberry pi, como servidor de seguridad vídeo. Y acceso por teléfono a este servidor. Para demostrarlo, utilizamos inicialmente python -m SimpleHTTPServer, pero después, con web.py.

Para salvar tiempo en el taller, busco con google un ejemplo de servidor de imágenes con web.py, y de inmediato encontramos esta pagina:

webpy.org/images

El codigo es asi:

import os
import web 
 
urls = (
'/images/(.*)', 'images'
)  
 
class images:
    def GET(self,name):
        ext = name.split(".")[-1]  # Gather extension

        cType = {
            "png":"images/png",
            "jpg":"images/jpeg",
            "gif":"images/gif",
            "ico":"images/x-icon"            }

        if name in os.listdir('images'):  # Security
            web.header("Content-Type", cType[ext]) 
            return open('images/%s'%name,"rb").read() 
        else:
            raise web.notfound()

Y después de añadir :

app = web.application(urls, globals())

if __name__ == "__main__":
    app.run() 
 
 
no operaba como lo esperamos. Normalmente, no va a descargar las imágenes con un Content-Type (web.header) apropiado, solo mostrarlas en el navegador. Pero aquí, si!

image/jpg


Es lo correcto de poner un Content-Type: image/jpeg, image/png etc. Pero en el código, en el sitio, hay images/jpeg, images/png etc. En vez de salvar tiempo, perdimos mucho sin ver el S extra...

Mi versión es la siguiente (URLS en vez de urls y Images como clase en vez de images, y image/ sin el S extra)

import os
import web

class Images:
    def GET(self,name):
        ext = name.split(".")[-1]  # Gather extension

        cType = {
            "png":"image/png",
            "jpg":"image/jpeg",
            "gif":"image/gif",
            "ico":"image/x-icon"            }

        if name in os.listdir('images'):  # Security
            web.header("Content-Type", cType[ext]) # Set the Header
            return open('images/%s'%name,"rb").read() # Notice 'rb' for reading images
        else:
            raise web.notfound()

URLS = (
'/images/(.*)', Images
)

app = web.application(URLS, globals())

if __name__ == "__main__":
    app.run()


Este código opera correctamente. 

Descargar


Seguimos y añadimos mas hasta que completamos el proyecto (el código sera en bitbucket un poco mas tarde en el mes), y ahora todo esta bien.

Pero, cual es la manera si uno realmente desea ofrecer la descarga de un fichero? Hacer un error de tipo? No.

Hay que añadir un otro encabezamiento http (por medio de web.header) que se llama Content-disposition:

web.header("Content-disposition", "attachment; filename=%s"%name)

@f_dion

Web.py: Aaron Swartz

A web framework

I've mentioned web.py a few times on this blog. It is a great web framework that doesn't get in your way.

I've done several presentations on the framework both in talks (PYPTUG web.py presentation) and as part of workshops. The latest workshop was this past saturday, for building a quick interface to a webcam on a Raspberry Pi. It will be online at some point this month.

Aaron Swartz


Little did I know as I was doing this workshop, that the author of the web.py framework had lost his life the day before (the 11th of January).

Although Aaron Swartz passed away, web.py being open source, will continue to have its impact on the world wide web.

Public domain


For open source works, I publish my source code under an open source license. But Aaron published web.py as public domain, about 6 years ago. That was bold.

This is probably one of the reasons why web.py is popular amongst the lightweight frameworks.

Even though there is no obligation tied to the code, there are a few that acknowledged web.py (and thus Aaron) publicly, such as this quote from the webpy.org web site:

"[web.py inspired the] web framework we use at FriendFeed [and] the webapp framework that ships with App Engine..."
  —  Brett Taylor, co-founder of FriendFeed and original tech lead on Google App Engine

Low key


There is a web.py google group. It is low volume (a lot of answers are off list, unfortunately), and I don't remember Aaron posting more recently than some time in 2011. This is mostly because web.py is a framework that is pretty trivial to use. Once you get it, you get it.

"The web.py slogan is: "Think about the ideal way to write a web app. Write the code to make it happen."
This is literally how I developed web.py. I wrote a web application in Python just imagining how I wanted the API to be. It started with import web, of course, and then had a place to define URLs, simple functions for GET and POST, a thing to deal with input variables and so on. Once the code looked right to me, I did whatever it took to make it execute without changing the application code -- the result was web.py."  Aaron Swartz
It is also because, for most people, the kit is complete. But there is another reason people don't need to ask that many questions.

Plenty of examples


Beside the webpy.org examples and cookbook, between the various open source repositories out there (sourceforge, bitbucket, github, gitorious, launchpad etc), there are a few gigabytes (GB!) of source code available out there, providing plenty of examples, ranging from feed aggregators, to blogs, to mp3 servers, etc. My own source is here as an hg repository

New audience


Due to the extremely short time required to be productive (minutes), web.py has been used quite a bit in the Raspberry Pi community. I personally use it in workshops because of that. Even without much background in Python or web programming, everybody seems to get it.

Conclusion


It is as good a time as any to conclude by pondering on this:

Behind every open source project, there are humans with their faults and qualities, their likes and dislikes. And perhaps tomorrow, they will be gone. Show your appreciation for what they do, today.

@f_dion

Saturday, November 24, 2012

It's more fun to compute

last track  - "It's more fun to compute"


Ah, Computer World, by Kraftwerk. The last track is titled "It's more fun to compute". I'm thinking Hutter, Schneider and Bartos must have written this song in November, after raking and blowing leaves for a few days... All joking aside, I hope you have this album on your ipod.

So what is it exactly that makes computing more fun? More fun than what, I hear you ask... What do you think, is it more fun to compute?

Also, either tomorrow or Monday, I'll post the bitbucket Mercurial repository for the web.py presentation at PYPTUG that I'll be doing on Monday. In the interim, go ahead and install web.py. I have the instructions on the sidekick page. Basically:

pi@raspberrypi ~/Desktop $ sudo easy_install web.py
Searching for web.py
Best match: web.py 0.37
Processing web.py-0.37-py2.7.egg
web.py 0.37 is already the active version in easy-install.pth

Using /usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg
Processing dependencies for web.py
Finished processing dependencies for web.py


If you've gone through the PyHack workshop #01, you already installed mercurial (hg). If not, you will need to install it on your Raspberry Pi before you can get the code:


pi@raspberrypi ~/Desktop $ sudo apt-get install mercurial

Tuesday, September 11, 2012

Sidekick

So, Batman has Robin, Sherlock Holmes has Dr John Watson, Sheriff Andy Taylor has Deputy Barney Fife... Well, you get the idea: All heroes have a sidekick (if not, they are missing out).

You need a sidekick

Or at least, your desktop does.

If your desktop is a Raspberry Pi, then you already know the life of a sidekick well, or at least you are learning it. This article is not really for you, although it might come in handy later. So, for all you Raspberry Pi owners who do everything on the Raspberry Pi, stay tuned to this blog for a future post: The Sidekick's Sidekick.

Unix, Linux or Mac Desktop

This will be smooth sailing. Open a terminal and type:
 $ ssh -X pi@raspberrypi  
 pi@raspberrypi's password:   
 Linux raspberrypi 3.1.9+ #168 PREEMPT Sat Jul 14 18:56:31 BST 2012 armv6l  
 The programs included with the Debian GNU/Linux system are free software;  
 the exact distribution terms for each program are described in the  
 individual files in /usr/share/doc/*/copyright.  
 Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent  
 permitted by applicable law.  
 Type 'startx' to launch a graphical session  
 Last login: Tue Sep 11 15:32:33 2012 from v480-sunray  
 pi@raspberrypi ~ $   
The first time you will be asked to accept the host key, say yes. Enter your password when prompted. If you entered the correct password, you are in.

Windows (XP, 7, ...)

Ok, this is a little more involved.
  1. Download Putty
  2. Enter the following information in the configuration:
  • Hostname: raspberrypi
  • go to the ssh tab and click X11 forwarding
  • Entere for Saved Session: raspberrypi
  • click Save

I'm not going to go through all the details here. Simply to say that you need to go to the ssh tab and click X11 forwarding download Xming server which will add an X server to Windows. You then need to start the Xming server from the start menu, then open the session in Putty. For more detail, go here
  • Double click on raspberrypi (or select and click open)
You will be asked to accept the host key, say yes. Enter your userid (pi) and password when prompted. If you entered the correct password, you are in.
With that setup however, you only get a fraction of the functionality of what we did for Unix, Linux or Mac.

What are we doing again?

You can now run any console application directly in that window, but even more interesting is the fact that you can run a graphical application on your Raspberry Pi, but the graphical display itself will be on your desktop.

Look, Ma, no VNC! For example, you want to run the midori browser. In the ssh window, at the prompt, type: midori
 $ pi@raspberrypi ~ $ midori
And you should get:
Or perhaps you want to write some Python code. After all, this is a Python centric blog...
 $ pi@raspberrypi ~ $ idle
And you should get:
Now, remember, although the idle window is on my desktop, when I type import web, it is importing a library on the Raspberry Pi, and not from my desktop. By default, web.py is not installed by default.

To install:

pi@raspberrypi ~/Desktop $ sudo easy_install web.py
Searching for web.py
Best match: web.py 0.37
Processing web.py-0.37-py2.7.egg
web.py 0.37 is already the active version in easy-install.pth

Using /usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg
Processing dependencies for web.py
Finished processing dependencies for web.py

In the above example, it actually didn't download the library, because I had installed it already. In fact, one of the first thing I did. Web.py is like duct tape for web applications. Or Web services. Or template driven apps. Or scripts that need database access. I could go on. Although a web framework, each module can be used individually, or can be replaced, or used alongside similar modules. On the screenshot, I did a dir(web) to show what modules are available. If there is some interest, I'll do a tutorial on using web.py, just let me know in the comments.

Concluding on this way of working, I could be editing python code in idle, while viewing the result of my web application in a web browser (either locally through midori or remotely using my desktop's browser). But that, is just touching the tip of the iceberg. There will be more to come in the coming weeks.

[Edit:]
Part 2


Tuesday, September 4, 2012

Raspberry Pi: From Kindergartners to MadScientists

Raspberry Pi: From Kindergartners to MadScientists

That is the title of the talk I will be giving on october 21st, at 4pm, part of the program for PyCarolinas 2012, the first Python conference held in the carolinas ( the states of North Carolina and South Carolina on the southern east coast of the United States, for our international readers).

When:
ical 
October 20th-21st

Kerr Hall
UNC Eshelman School of Pharmacy
Chapel Hill, NC

What:
  PyCarolinas' website



So what is the talk about?

  • A quick background on the Raspberry Pi
  • How it can be used in education
  • Comparison with a typical desktop
  • The mad scientist bit (interfacing with hardware)
As far as Python is concerned, there will be setup, demo, explanations of libraries etc and the last part will cover GPIO libraries, some Web.py and other cool bits. Be there or be square.

Friday, August 17, 2012

And the back

Not much to see but the sd card. It is 16gb, so there is plenty of space for installing software. Right now it is running web.py apps