Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serve file in webpy?

Tags:

python

web.py

I am using webpy framefork. I want to serve static file on one of requests. Is there special method in webpy framework or I just have to read and return that file?

like image 368
codez Avatar asked Jan 20 '11 19:01

codez


3 Answers

If you are running the dev server (without apache):

Create a directory (also known as a folder) called static in the location of the script that runs the web.py server. Then place the static files you wish to serve in the static folder.

For example, the URL http://localhost/static/logo.png will send the image ./static/logo.png to the client.

Reference: http://webpy.org/cookbook/staticfiles


Update. If you really need to serve a static file on / you can simply use a redirect:

#!/usr/bin/env python

import web

urls = (
  '/', 'index'
)

class index:
    def GET(self):
        # redirect to the static file ...
        raise web.seeother('/static/index.html')

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

if __name__ == "__main__": app.run()
like image 88
miku Avatar answered Nov 13 '22 05:11

miku


I struggled with this for the last couple of hours... Yuck!

Found two solutions which are both working for me... 1 - in .htaccess add this line before the ModRewrite line:

RewriteCond %{REQUEST_URI} !^/static/.*

This will make sure that requests to the /static/ directory are NOT rewritten to go to your code.py script.

2 - in the code.py add a static handler and a url entry for each of several directories:

urls = (
    '/' , 'index' ,
    '/add', 'add' ,
    '/(js|css|images)/(.*)', 'static', 
    '/one' , 'one'
    )

class static:
    def GET(self, media, file):
        try:
            f = open(media+'/'+file, 'r')
            return f.read()
        except:
            return '' # you can send an 404 error here if you want

Note - I stole this from the web.py google group but can't find the dang post any more!

Either of these worked for me, both within the templates for web.py and for a direct call to a web-page that I put into "static"

like image 29
tom stratton Avatar answered Nov 13 '22 06:11

tom stratton


I don't recommend serving static files with web.py. You'd better have apache or nginx configured for that.

like image 1
Andrey Kuzmin Avatar answered Nov 13 '22 05:11

Andrey Kuzmin