I have a index.html file, which has the absolute path 'c:\project\web\frontend\index.html'
I am trying to return it using the following function
#webserver.route('/')
def home()
return webserver.send_static_file(path)
I have verified that the path is correct by accessing it directly in the browser.
I have tried to replace '\' with '/' without any luck.
It is running on a windows machine.
If you look at flask's documentation for send_static_file. You'll see that it says that it's used internally by flask framework to send a file to the browser. If you want to render an html, it's common to use render_template. You need to make sure that your index.html is in a folder called templates first.
So I would do the following:
#webserver.route('/')
def home()
return flask.render_template('index.html')
I had to define the path to be the static_folder, when creating the flask object. Once I defined the folder to be static, the html page was served.
Related
I am using a django template to generate pdf via feeding it a context object from the function but not the view, it works fine in case of view, but I am not able to load the local static images on the template from the function. but this is possible in view because there I can tell which base path to use. But I not able to do the same in the function.
As you can see I can how I am getting the base url from the view. Here I can get because I have requests object but in function I do not have any requests object. So images are not loading.
html = HTML(string=html_string, base_url=request.build_absolute_uri('/'))
This is how I am trying to do in the function:
html_string = render_to_string('experiences/voucher.html', data)
html = HTML(string=html_string, base_url=settings.STATIC_ROOT)
result = html.write_pdf("file_new.pdf", stylesheets=[css],optimize_images=True)
I would like to know how can I tell, where are my images so that images can be rendered on the pdf.
It was not working because base_url had not way to know where the images are located especially on the running server, so I had to explicitly define the path to the local resources so I did something like this:
first I added an envoirnment variable in my .env file:
like HOST=http://localhost:8000 and then I get this url in my actuall code like this:
path = os.environ["HOST"]+"/static/"
and at the end i pass this path to base_url parameter in HTML()
html = HTML(string=html_string, base_url=path)
and after all this it worked like a charm.
I'm using apidoc to generate a documentation website. On running, it creates a folder called doc, which contains an index.html file and accompanying css and js.
I'd like to be able to serve this folder with a Flask server, but can't work out how to do it.
My folder structure looks like this
-root
--- doc/ #contains all of the static stuff
--- server.py
I've tried this, but can't get it to work:
app = Flask(__name__, static_url_path="/doc")
#app.route('/')
def root():
return app.send_from_directory('index.html')
One of the problems is that all of the static files referenced in the index.html generated by apidoc are relative to that page, so /js/etc. doesn't work, since it's actually /doc/js...
It would be great if someone could help me with the syntax here. Thanks.
I spot three problems in code.
a) you do not need to use static_url_path, as send_from_directory is independent of it
b) when I try to run above code, and go to /, I get a AttributeError: 'Flask' object has no attribute 'send_from_directory' - this means translates to app.send_from_directory is wrong - you need to import this function from flask, ie from flask import send_from_directory
c) when I then try to run your code, I get a TypeError: send_from_directory() missing 1 required positional argument: 'filename', which means send_from_directory needs another argument; it needs both a directory and a file
Putting this all together you get something like this:
from flask import Flask
from flask import send_from_directory
app = Flask(__name__)
#app.route("/")
def index():
return send_from_directory("doc", "index.html")
As a takeway (for myself):
reading the documentation helps a lot ( https://flask.palletsprojects.com/en/1.1.x/api/ )
having a close look at the - at first scary - error messages gives really good hints on what to do
I am new to flask and python and I was trying to use the render template function open an URL. the 404 error keeps showing instead of the HTML that is in the templates folder.
My folder structure is as follows:
coding folder/
main.py
templates/
----profile.html
The code in my main.py file is as follows:
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/profile/<name>")
def profile(name):
return render_template("profile.html", name=name)
if __name__ == "__main__":
app.run()
my profile.html file contains the following code:
<!doctype html>
<title>sambit's page</title>
<h3>Wassup {{ name }} </h3>
I have been scratching my head over this for more than 4 hours. Please Help!!!!
Are you trying to access using /profile/myname/ or /profile/myname ?
Since your route definition doesn't have a trailing slash, Flask will throw a 404 if you access that route with a trailing slash in your browser. Read more here: Doc
Though they look rather similar, they differ in their use of the trailing slash in the URL definition. In the first case, the canonical URL for the projects endpoint has a trailing slash. In that sense, it is similar to a folder on a filesystem. Accessing it without a trailing slash will cause Flask to redirect to the canonical URL with the trailing slash.
In the second case, however, the URL is defined without a trailing slash, rather like the pathname of a file on UNIX-like systems. Accessing the URL with a trailing slash will produce a 404 “Not Found” error.
So I have the following environment; django 1.8. apache on ubuntu 14 with mod_wsgi and mod x-sendfile enabled.
I have a very simple view to server the files as follows:
def foo(request, filename):
response = HttpResponse()
response['Content-Disposition'] = 'attachment; filename={0}'.format(filename)
response['X-Sendfile'] = "/home/amir/DjV/Files/{0}".format(filename)
return response
and here's my urlconf regarding the view:
url(r'^foo/(.+)/$', foo)
I've written a snippet that generate absolute path to files to be presented in a download list. The generated paths work fine if I enter them in the browser; but if I use them as hyperlinks, when clicked it goes to blank page. For examlple here is one the urls that is generated by the snippet I mentioned:
http://192.168.43.6:8000/foo/uuid.txt
it works fine and I get to download the uuid.txt, but when I put it into django template as follows, it doesn't work:
192.168.43.6:8000/foo/uuid.txt
My question being: why my link works fine when entered manually but not when used as a hyperlink? Could it be because of being a local address? How can I fix it?
You need to specify a protocol inside your template when doing such things:
192.168.43.6:8000/foo/uuid.txt
However, you should not hard code urls in this way in special not if they are handled inside your Django application. Check {% url %} templating whether it could be a benefit for you
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?
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()
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"
I don't recommend serving static files with web.py. You'd better have apache or nginx configured for that.
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