How to serve file in webpy?

我们两清 提交于 2021-02-07 12:25:16

问题


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?


回答1:


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()



回答2:


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"




回答3:


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




回答4:


The other answers did not work for me. You can first load the html file in app.py or even write the html within app.py. Then, you can make the index class' GET method return the static html.

index_html = '''<html>hello world!</html>'''

class index:
    def GET(self):
        return index_html


来源:https://stackoverflow.com/questions/4751508/how-to-serve-file-in-webpy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!